是否需要volatile是Java中的惰性布尔关闭标志? [英] Is volatile needed for a lazy boolean shutdown flag in Java?

查看:125
本文介绍了是否需要volatile是Java中的惰性布尔关闭标志?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设下面的代码

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
  }
}

基本上,我想阻止所有即将调用的 action()有一个异常。
我知道设置 shuttingDown 是一个原子操作。但是问题是如果我需要使 shuttingDown volatile,使更改对其他线程可见,这可能从线程池中重用。

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.

我看到这个oracle教程以及 AtomicBoolean上的javadoc
但是后者也使用volatile 。我在一个线程只设置一次,所以我不需要由AtomicBoolean提供的锁定机制。
我只想让变量在变量更新后对所有线程可见。

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.

据我理解oracle教程,更新操作是 atomic ,这是没有其他线程可以设置的值。问题是,何时将更新的值填充到其他线程(如果有的话)。

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.

虽然操作是原子操作,但是为了保证其他线程可见,你需要建立一个发生在关系之前。 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是Java中的惰性布尔关闭标志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆