7

I'm writing an application in Java which uses ExecutorService for running multiple threads.

I wish to submit multiple tasks (thousands at a time) to the Executor as Callables and when done, retrieve their result. The way I'm approaching this is each time I call submit() function, I get a Future which I store in an ArrayList. 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. 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. 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. That is why I need to keep iterating with timeouts.

thanks in advance

4

2 回答 2

6

这是正确的方法还是效率太低?

这本身不是正确的方法。您不必要地反复ArrayList检查任务完成情况。

这很简单:只需使用:CompletionService。您可以轻松地将现有的执行程序包装到其中。来自 JavaDocs:

生产者提交任务以供执行。消费者接受已完成的任务并按照他们完成的顺序处理他们的结果。

本质上,CompletionService它提供了一种简单地通过调用来获取结果的方法take()。它是一个阻塞函数,调用者将阻塞直到结果可用。


于 2013-05-14T16:13:32.990 回答
1

请注意,对 Future.get 的调用将被阻塞,直到答案可用。所以你不需要另一个线程来遍历数组列表。

见这里https://blogs.oracle.com/CoreJavaTechTips/entry/get_netbeans_6

于 2013-05-14T16:16:05.937 回答