title: Is volatile needed for a lazy boolean shutdown flag in Java?
body: <p>Assume the following code</p>
  
  <pre><code>public class Singleton {
  
    boolean shuttingDown = false;
  
  
    void action() {
      if (shuttingDown) {
        throw new RuntimeException("already shutting down");
      } 
      // do some more stuff
    }
  
    // Called by a single thread only
    void onShutDown() {
      shuttingDown = true;
      // perform some more actions to remedy the class
    }
  }
  </code></pre>
  
  <p>Basically I want to block all upcoming calls to <code>action()</code> with an exception.
  I know that setting <code>shuttingDown</code> is an atomic operation. However the question is if I would need to make <code>shuttingDown</code> volatile to make the change visible to the other threads, which might be re-used from a thread pool.</p>
  
  <p>I saw <a href="http://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html" rel="nofollow">this oracle tutorial</a> and also the javadoc on <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicBoolean.html" rel="nofollow">AtomicBoolean</a>.
  However the latter <a href="http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/concurrent/atomic/AtomicBoolean.java#63" rel="nofollow">uses volatile</a>, too. I set the value only once in a single thread, so I don't need the locking mechanisms provided by AtomicBoolean.
  I just want to make the change visible to all threads as soon as the variable is updated. </p>
  
  <p>As far as I understand the oracle tutorial, the update operation is <em>atomic</em>, that is no other thread can intecept while setting the value. The question is, <em>when</em> will the updated value be populated to the other threads (if at all?).</p>