title: When is it preferable to use volatile boolean in Java rather than AtomicBoolean?
body: <p>I've looked at the other volatile vs. Atomicxxxx questions in SO (including <a href="https://stackoverflow.com/questions/3786825/java-volatile-boolean-vs-atomicboolean">this one</a>) and have read <a href="http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/atomic/package-summary.html" rel="noreferrer">the description of java.util.current.atomic</a>, and I am not quite satisfied with the nuances.</p>
  
  <p>If I'm trying to decide between using <code>volatile boolean</code> and <code>AtomicBoolean</code>, are there practical differences besides the atomic read-modify-write operations offered by AtomicBoolean? (e.g. <code>compareAndSet()</code> and <code>getAndSet()</code>)</p>
  
  <p>Suppose I have</p>
  
  <pre><code>volatile boolean flag;
  </code></pre>
  
  <p>Then one or more threads set the flag (but not clear it). If I have one thread that reads the flag, and if set, does an action, and then clears the flag, is <code>volatile</code> adequate?</p>
  
  <p>Is there a higher cost to AtomicBoolean than volatile boolean, in terms of</p>
  
  <ul>
  <li>memory space</li>
  <li>performance hit (<code>volatile boolean</code> appears to require memory fencing, <code>AtomicBoolean</code> appears to require memory fencing + some minor locking on CAS operations as per the java.util.current.atomic description)</li>
  </ul>
  
  <p>My gut call is to just go with AtomicBoolean and be safe, but I want to understand if there's ever a situation to use <code>volatile boolean</code> instead (e.g. if I had thousands of instances of them and performance were an issue).</p>