title: In what situations can do-while be more efficient than while?
body: <p><strong>While vs. do-while</strong></p>
  
  <p>While and do-while are functionally equivalent <strong>when the blocks are empty</strong>, although while seems more natural:</p>
  
  <pre><code>do {} while (keepLooping());
  while (keepLooping()) {}
  </code></pre>
  
  <p>One typical use case of a while/do-while with an empty block is to force an update of atomic objects with a compareAndSet (CAS). For example the code below will increment <code>a</code> in a thread-safe way:</p>
  
  <pre><code>int i;
  AtomicInteger a = new AtomicInteger();
  while (!a.compareAndSet(i = a.get(), i + 1)) {}
  </code></pre>
  
  <p><strong>Context</strong></p>
  
  <p>Several parts of java.util.concurrent use the <code>do {} while (...)</code> idiom for CAS operations and the javadoc of <code>ForkJoinPool</code> explains:</p>
  
  <blockquote>
    <p>There are several occurrences of the unusual <code>do {} while (!cas...)</code> which is the simplest way to force an update of a CAS'ed variable.</p>
  </blockquote>
  
  <p>Since they admit it is unusual, I suppose they meant <em>best</em> rather than <em>simplest</em>.</p>
  
  <p><strong>Question</strong></p>
  
  <p>Are there situations where <code>do {} while (!cas)</code> can be more efficient than <code>while (!cas) {}</code> and for what reasons?</p>