user2382539
user2382539

Reputation:

Tracking Completed Tasks in ExecutorService

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

Upvotes: 7

Views: 3967

Answers (2)

Woody
Woody

Reputation: 7992

Note that the call to Future.get will block until the answer is available. So you don't need another thread to iterate over the array list.

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

Upvotes: 2

goblinjuice
goblinjuice

Reputation: 3214

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.

This is very simple: Just use: CompletionService. You can easily wrap your existing executor into it. From 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(). It is a blocking function and the caller will block until the results are available.


Upvotes: 6

Related Questions