Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If waiting for all tasks in the <code>ExecutorService</code> to finish isn't precisely your goal, but rather waiting until a <em>specific batch of tasks</em> has completed, you can use a <a href="http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletionService.html" rel="noreferrer"><code>CompletionService</code></a> &mdash; specifically, an <a href="http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorCompletionService.html" rel="noreferrer"><code>ExecutorCompletionService</code></a>.</p> <p>The idea is to create an <code>ExecutorCompletionService</code> wrapping your <code>Executor</code>, <a href="http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorCompletionService.html#submit(java.util.concurrent.Callable)" rel="noreferrer">submit</a> some <em>known number</em> of tasks through the <code>CompletionService</code>, then draw that <em>same number</em> of results from the <em>completion queue</em> using either <a href="http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorCompletionService.html#take()" rel="noreferrer"><code>take()</code></a> (which blocks) or <a href="http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorCompletionService.html#poll()" rel="noreferrer"><code>poll()</code></a> (which does not). Once you've drawn all the expected results corresponding to the tasks you submitted, you know they're all done.</p> <p>Let me state this one more time, because it's not obvious from the interface: You must know how many things you put into the <code>CompletionService</code> in order to know how many things to try to draw out. This matters especially with the <code>take()</code> method: call it one time too many and it will block your calling thread until some other thread submits another job to the same <code>CompletionService</code>.</p> <p>There are <a href="http://jcip.net.s3-website-us-east-1.amazonaws.com/listings/Renderer.java" rel="noreferrer">some examples showing how to use <code>CompletionService</code></a> in the book <a href="http://jcip.net/" rel="noreferrer"><em>Java Concurrency in Practice</em></a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload