AtomicBoolean提供了一种原子性地读写布尔类型变量的解决方案,通常情况下,该类将被用于原子性地更新状态标识位
1 AtomicBoolean的基本用法
AtomicBoolean提供的方法比较少也比较简单,只对其做简单介绍,其基本原理与AtomicInteger极为类似。
1.1 AtomicBoolean的创建
// AtomicBoolean 无参构造: 此时为false 等价于 AtomicBoolean(false)
AtomicBoolean ab = new AtomicBoolean();
// AtomicBoolean 有参构造,
ab = new AtomicBoolean(false);
1.2 AtomicBoolean值的更新
/**
对比并且设置boolean最新的值
其中expect代表当前的AtomicBoolean数值,update则是需要设置的新值,
该方法会返回一个boolean的结果:当expect和AtomicBoolean的当前值不相等时,修改会失败,返回值为false;
若修改成功则会返回true。
**/
public final boolean compareAndSet(boolean expect, boolean update);
// 同上
public final boolean weakCompareAndSet(boolean expect, boolean update)
// 设置AtomicBoolean最新的value值,该新值的更新对其他线程立即可见。
set(boolean newValue)
// 设置AtomicBoolean的布尔值
lazySet(boolean newValue)
// 返回AtomicBoolean的前一个布尔值,并且设置新的值。
getAndSet(boolean newValue);
eg:
public static void main(String[] args) {
AtomicBoolean atomicBoolean = new AtomicBoolean(false);
boolean res = atomicBoolean.compareAndSet(false, true);
System.out.println(res); // true,更新成功
System.out.println(atomicBoolean.get()); // 更新为true了
res = atomicBoolean.compareAndSet(false, false);
System.out.println(res); // fasle,更新失败
System.out.println(atomicBoolean.get()); // 所以还是true
}
1.3 其他方法
// 获取AtomicBoolean的当前布尔值。
get()
2 AtomicBoolean内幕
AtomicBoolean的实现方式比较类似于AtomicInteger类,实际上AtomicBoolean内部的value本身就是一个volatile关键字修饰的int类型的成员属性
public class AtomicBoolean implements java.io.Serializable {
private static final long serialVersionUID = 4654671469794556979L;
// setup to use Unsafe.compareAndSwapInt for updates
private static final Unsafe unsafe = Unsafe.getUnsafe();
// valueOffset将用于存放value的内存地址偏移量
private static final long valueOffset;
static {
try {
// 获取value的内存地址偏移量
valueOffset = unsafe.objectFieldOffset
(AtomicInteger.class.getDeclaredField("value"));
} catch (Exception ex) { throw new Error(ex); }
}
private volatile int value;