title: Future and ExecutorService, how to know when a cancelled task has terminated?
body: <p>Suppose I have some code that start a task using an <code>ExecutorService</code> and then the invoker cancels it, by means of the <code>Future</code> returned by the <code>submit()</code> method:</p>
  
  <pre><code>execService = Executors.newSingleThreadExecutor ();
  Future&lt;String&gt; result = execService.submit ( () -&gt; {
    for ( ... ) {
      if ( Thread.interrupted() ) break;
      // Stuff that takes a while
    }
    return "result";
  });
  ...
  result.cancel ( true );
  // I'm not sure the corresponding thread/task has finished and the call() method 
  // above returned
  // result.isDone() is immediately true. result.get() throws CancellationException
  </code></pre>
  
  <p>So, I can cancel the background task and make the executor ready to start again. However, I cannot do the latter before the interrupted task completes the interruption and the corresponding method returns.</p>
  
  <p>Note that in the code above the main flow returns straight after <code>result.cancel()</code> and <code>result.isCancelled()</code> is true straight after that, at the same time, the parallel task might take still a while before checking <code>Thread.interrupted()</code> again and terminate. I need to be sure that the side task is completely finished before continuing in the main thread.</p>
  
  <p>Moreover, note that the use of a single thread executor is accidental, apart from this simple example, I'd like to solve the problem for both the case of just one parallel thread and for the one where more than one thread are running.</p>
  
  <p>What's the best way to be sure of that?</p>
  
  <p>So far I've thought of either introducing a flag that is visible to both the task and the invoker, or shutting down the executor and waiting for that to complete. The latter solution might be inefficient if one wants to reuse the executor many other times, the former is better, but I'd like to know if there is another simpler or more canonical way.</p>