简体   繁体   English

Java 中的惰性布尔关闭标志是否需要 volatile?

[英]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.基本上我想阻止所有即将到来的action()调用,但有一个例外。 I know that setting shuttingDown is an atomic operation.我知道设置shuttingDown是一个原子操作。 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.然而,问题是我是否需要使shuttingDown变得易失性以使更改对其他线程可见,这些线程可能会从线程池中重新使用。

I saw this oracle tutorial and also the javadoc on AtomicBoolean .我看到了这个 oracle 教程AtomicBoolean上的 javadoc。 However the latter uses volatile , too.然而,后者也使用 volatile I set the value only once in a single thread, so I don't need the locking mechanisms provided by AtomicBoolean.我在单个线程中只设置了一次值,所以我不需要 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.据我了解 oracle 教程,更新操作是原子的,即在设置值时没有其他线程可以拦截。 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. Volatile 是最简单的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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