In Java, how do I wait for all tasks, but stop the first error?

I have a number of simultaneous tasks to run. If any of them fails, I want to interrupt them all and wait for completion. But, believing that none of them failed, I want to wait until they all end.

The ExecutorCompletionService seems almost what I want here, but there seems to be no way to determine if all my tasks are running, save for keeping a separate count of the number of tasks. (Note that both examples in the Javadoc for ExecutorCompletionService track the number of "n" tasks and use this to determine if the service has completed.)

Am I missing something, or do I really need to write this code myself?

+6
java multithreading concurrency
source share
2 answers

Yes, you need to keep track if you use ExecutorCompletionService. Typically, you call get () on futures to see if an error has occurred. Without repeating tasks, how else could you say that one failed?

+2
source share

If your job series is a known size, you should use the second example in javadoc.

However, if you do not know the number of tasks that you submit to CompletionService, you have a problem with the consumer producer. One thread creates tasks and places them in ECS, the other will consume task futures using take (). You can use the general Semaphore, which allows the Producer to call release () and the Consumer to call the receive () method. The completion of the semantics will depend on your application, but a volatile or atomic logical value for the manufacturer to indicate that this is done will be sufficient.

I suggest Semaphore via wait / notify using poll (), because there is an undefined delay between the time the task was created and the time available for consumption. Therefore, the consumer and the manufacturer should be a little smarter.

+1
source share

All Articles