title: How to test if Future is complete without race?
body: <p>I'm tracking execution of a task with standard <code>Future</code> object. There are the following valid states of that task (as I see in Guava code of <code>AbstractFuture</code> class):</p>
  
  <ul>
  <li><em>Running</em>;</li>
  <li><em>Completing</em>;</li>
  <li><em>Completed</em> successfully or with exception;</li>
  <li><em>Cancelled</em>;</li>
  <li><em>Interrupted</em>.</li>
  </ul>
  
  <p><code>Future.isDone()</code> returns <code>true</code> if and only if the state is <em>completed</em>, <em>cancelled</em> or <em>interrupted</em>. <code>Future.isCancelled()</code> returns <code>true</code> if and only if the state is either <em>interrupted</em> or <em>cancelled</em>.</p>
  
  <p>Ok, but I need to check if the task is <em>completed</em>. There is an obvious way to do this:</p>
  
  <pre><code>boolean isCompleted = future.isDone() &amp;&amp; !future.isCancelled();
  </code></pre>
  
  <p>Unfortunatelly, a nasty concurrency bug hides there.</p>
  
  <ol>
  <li>Thread #1 invokes <code>future.isCancelled()</code>. The result is <code>false</code>, because the task is still in progress.</li>
  <li>Thread #2 cancels the task calling <code>future.cancel()</code>.</li>
  <li>Thread #1 invokes <code>future.isDone()</code>. The result is <code>true</code> now.</li>
  <li>Evaluation of expression above yields <code>true</code>, and it's incorrect answer.</li>
  </ol>
  
  <p>How to avoid this issue?</p>