简体   繁体   中英

Is volatile needed for a lazy boolean shutdown flag in Java?

Assume the following 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
  }
}

Basically I want to block all upcoming calls to action() with an exception. I know that setting shuttingDown is an atomic operation. However the question is if I would need to make shuttingDown volatile to make the change visible to the other threads, which might be re-used from a thread pool.

I saw this oracle tutorial and also the javadoc on AtomicBoolean . However the latter uses volatile , 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.

As far as I understand the oracle tutorial, the update operation is atomic , that is no other thread can intecept while setting the value. The question is, when will the updated value be populated to the other threads (if at all?).

The short answer is yes, you must make it volatile.

Although the operation is atomic, for it to be guaranteed visible to other threads you need to establish a happens before relationship. Volatile is the simplest way to do this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM