简体   繁体   English

跟踪ExecutorService中的已完成任务

[英]Tracking Completed Tasks in ExecutorService

I'm writing an application in Java which uses ExecutorService for running multiple threads. 我正在用Java编写一个应用程序,它使用ExecutorService来运行多个线程。

I wish to submit multiple tasks (thousands at a time) to the Executor as Callables and when done, retrieve their result. 我希望将多个任务(一次数千个)作为Callables提交给Executor,并在完成后检索其结果。 The way I'm approaching this is each time I call submit() function, I get a Future which I store in an ArrayList. 我接近这个的方式是每次调用submit()函数时,我得到一个存储在ArrayList中的Future。 Later I pass the List to a thread which keeps iterating over it, calling future.get() function with a timeout to see if the task completed. 稍后我将List传递给一个不断迭代它的线程,调用future.get()函数并超时以查看任务是否完成。 is this the right approach or is to too inefficient? 这是正确的方法还是效率太低?

EDIT --- More info --- Another problem is that each Callable takes different amount of processing time. 编辑---更多信息---另一个问题是每个Callable需要不同的处理时间。 So if I simply take the first element out of the List and call get() on it, it will block while results of others may become available and the program will not know. 因此,如果我只是从List中取出第一个元素并在其上调用get(),它将阻塞,而其他元素的结果可能变得可用而程序将无法知道。 That is why I need to keep iterating with timeouts. 这就是为什么我需要继续迭代超时。

thanks in advance 提前致谢

is this the right approach or is to too inefficient? 这是正确的方法还是效率太低?

This is not the correct approach per se. 这本身并不正确。 You are needlessly iterating over ArrayList checking for task completion. 你不必要地迭代ArrayList检查任务完成。

This is very simple: Just use: CompletionService . 这很简单:只需使用: CompletionService You can easily wrap your existing executor into it. 您可以轻松地将现有执行程序包装到其中。 From JavaDocs: 来自JavaDocs:

Producers submit tasks for execution. 生产者提交执行任务。 Consumers take completed tasks and process their results in the order they complete. 消费者完成任务并按照他们完成的顺序处理结果。

In essence, CompletionService provides a way to get the result back simply by calling take() . 实质上, CompletionService提供了一种简单地通过调用take()来获取结果的方法。 It is a blocking function and the caller will block until the results are available. 它是一个阻塞函数,调用者将阻塞,直到结果可用。


Note that the call to Future.get will block until the answer is available. 请注意,对Future.get的调用将阻止,直到答案可用。 So you don't need another thread to iterate over the array list. 所以你不需要另一个线程迭代数组列表。

See here https://blogs.oracle.com/CoreJavaTechTips/entry/get_netbeans_6 请参阅https://blogs.oracle.com/CoreJavaTechTips/entry/get_netbeans_6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM