In the given scenario, if we wants to run FIVE events and do some specific operation after every event compeletion. If this is fixed number of events it is very easy to fall in CountDownLatch otherwise we have to go with ExecutorCompletionService .
More than that we can use our own ExecutorService to build the ExecutorCompletionService and also cabable of running Callable and Runnable and returns the result. If it is Runnable, whatever the value we passed for the result will be returned after Thread completion.
- This method helps to add Runnable and Callable
- Removes first Runnable and Callable from the completion Queue, if no thread completed it waits for completion
- Removes first Runnable and Callable from the completion Queue, if no thread completed, returns null
CompletionService<Result> ecs = new ExecutorCompletionService<Result>(e); ecs.submit(t1); ecs.submit(t2); ..... ecs.take(); //wait for atleast one thread to complete while(ecs.poll() != null); //continue this loop to complete second thread in queue.