AtomicBoolean做了哪些volatile boolean不能做到的事情?


当前回答

如果有多个线程访问类级别变量,则 每个线程都可以在其线程本地缓存中保留该变量的副本。

将变量设置为volatile将防止线程将变量的副本保存在线程本地缓存中。

原子变量是不同的,它们允许对其值进行原子修改。

其他回答

两者都是相同的概念,但在原子布尔中,它将为操作提供原子性,以防cpu切换发生在两者之间。

AtomicBoolean有一些方法可以原子地执行复合操作,而不必使用同步块。另一方面,volatile布尔值只能在同步块中执行复合操作。

读取/写入volatile boolean的内存效果分别与AtomicBoolean的get和set方法相同。

例如,compareAndSet方法将自动执行以下操作(没有同步块):

if (value == expectedValue) {
    value = newValue;
    return true;
} else {
    return false;
}

因此,compareAndSet方法将允许您编写保证只执行一次的代码,即使是从多个线程调用时也是如此。例如:

final AtomicBoolean isJobDone = new AtomicBoolean(false);

...

if (isJobDone.compareAndSet(false, true)) {
    listener.notifyJobDone();
}

保证只通知侦听器一次(假设没有其他线程将AtomicBoolean设置为true后再次设置为false)。

如果你只有一个线程修改你的布尔值,你可以使用一个volatile布尔值(通常你这样做是为了在线程的主循环中定义一个停止变量)。

但是,如果有多个线程修改布尔值,则应该使用AtomicBoolean。否则,以下代码是不安全的:

boolean r = !myVolatileBoolean;

该操作分两步完成:

读取布尔值。 写入布尔值。

如果其他线程修改了#1到2#之间的值,您可能会得到错误的结果。AtomicBoolean方法通过原子地执行步骤#1和#2来避免这个问题。

I use volatile fields when said field is ONLY UPDATED by its owner thread and the value is only read by other threads, you can think of it as a publish/subscribe scenario where there are many observers but only one publisher. However if those observers must perform some logic based on the value of the field and then push back a new value then I go with Atomic* vars or locks or synchronized blocks, whatever suits me best. In many concurrent scenarios it boils down to get the value, compare it with another one and update if necessary, hence the compareAndSet and getAndSet methods present in the Atomic* classes.

检查java.util.concurrent.atomic包中的JavaDocs,以获得Atomic类的列表和它们如何工作的出色解释(刚刚了解到它们是无锁的,因此它们比锁或同步块更有优势)

Volatile boolean vs AtomicBoolean

Atomic*类包装了相同类型的volatile原语。来源:

public class AtomicLong extends Number implements java.io.Serializable {
   ...
   private volatile long value;
   ...
   public final long get() {
       return value;
   }
   ...
   public final void set(long newValue) {
       value = newValue;
   }

如果你所做的只是获取和设置一个Atomic*,那么你也可以用一个volatile字段来代替。

AtomicBoolean做了哪些volatile boolean不能做到的事情?

原子类为您提供了提供更高级功能的方法,例如用于数字的incrementAndGet(),用于布尔值的compareAndSet(),以及其他实现多重操作(get/increment/set, test/set)而无需锁定的方法。这就是为什么Atomic*类如此强大。

例如,如果多个线程使用++使用下面的代码,就会出现竞争条件,因为++实际上是:get、increment和set。

private volatile value;
...
// race conditions here
value++;

然而,下面的代码将在多线程环境中安全工作,没有锁:

private final AtomicLong value = new AtomicLong();
...
value.incrementAndGet();

同样重要的是要注意,从对象的角度来看,使用Atomic*类包装volatile字段是封装关键共享资源的好方法。这意味着开发人员不能假设字段不共享就处理它,可能会在字段++中注入问题;或其他引入竞态条件的代码。