AtomicBoolean详解

在Java语言中,boolean相关的,如下:

  • 原始类型:boolean
  • 原始类型的包装类:java.lang.Boolean
  • 可以原子性更新的{@code boolean}值:java.util.concurrent.atomic.AtomicBoolean

 下面的代码来自于JDK1.8:

package java.util.concurrent.atomic;
import sun.misc.Unsafe;

/**
 * 
 *用于自动更新一个boolean类型的值,AtomicBoolean可以在应用中用来实现更新一个标志,但是不能用来替换一个{@link java.lang.Boolean}

 * @since 1.5
 * @author Doug Lea
 */
public class AtomicBoolean implements java.io.Serializable {

    private static final long serialVersionUID = 4654671469794556979L;
    // setup to use Unsafe.compareAndSwapInt for updates  // 通过Unsafe类,使用了计算机硬件底层的一个功能,CAS
    private static final Unsafe unsafe = Unsafe.getUnsafe(); 
    private static final long valueOffset;  // 该值是一个确定的值

    static {
        try {
            valueOffset = unsafe.objectFieldOffset
                (AtomicBoolean.class.getDeclaredField("value"));
        } catch (Exception ex) { throw new Error(ex); }
    }

    private volatile int value; // volatile修饰,保证并发条件下,value可见性

    /**
     * Creates a new {@code AtomicBoolean} with the given initial value.
   * 带参数的构造方法,这里可以看出,true用1表示 , false用0表示,分别对应value = 1,value = 0 * *
@param initialValue the initial value */ public AtomicBoolean(boolean initialValue) { value = initialValue ? 1 : 0; } /** * Creates a new {@code AtomicBoolean} with initial value {@code false}.
   * 无参构造,默认为false,value的初始值为0,即使不赋值
*/ public AtomicBoolean() { } /** * Returns the current value.
   * 返回当前值,使用了关键字volatile来保证,并发下数据的可见性 * *
@return the current value */ public final boolean get() { return value != 0; } /** * * @param expect the expected value 也就是当前值 * @param update the new value 需要新设定的值 *
   * 如果这里传入的当前值与真实值,相等,那么进行修改,并返回true;否则,不进行修改返回false。
*/ public final boolean compareAndSet(boolean expect, boolean update) { int e = expect ? 1 : 0; // 这里很简单,就是true用1表示,false用0表示 int u = update ? 1 : 0; return unsafe.compareAndSwapInt(this, valueOffset, e, u); // 这个方法调用了底层的CAS } /** *
* 可能出现虚假的故障并且不提供有序性保证,因此只有在很少的情况下是compareAndSet()方法的替代 *
@param expect the expected value * @param update the new value * @return {@code true} if successful */ public boolean weakCompareAndSet(boolean expect, boolean update) { int e = expect ? 1 : 0; int u = update ? 1 : 0; return unsafe.compareAndSwapInt(this, valueOffset, e, u); } /** * 无条件地设置为给定值,即这里不考虑并发的情况 * * @param newValue the new value */ public final void set(boolean newValue) { value = newValue ? 1 : 0; } /** * 最后再设置给定的值 * * @param newValue the new value * @since 1.6 */ public final void lazySet(boolean newValue) { int v = newValue ? 1 : 0; unsafe.putOrderedInt(this, valueOffset, v); // 这里可以猜测 + 验证的方式:这种设置方式可以多次设置不同的值(设置的值是有顺序的),不过在使用到该值的时候,会从内存中取到该值的最新值,后添加的值会覆盖新添加的值。 } /** * 自动设置新值,并返回旧值 * * @param newValue the new value * @return the previous value */ public final boolean getAndSet(boolean newValue) { boolean prev; do { prev = get(); } while (!compareAndSet(prev, newValue)); // 核心还是在compareAndSet()方法 return prev; } /** * 返回当前值的字符串形式, "true" , "false" * @return the String representation of the current value */ public String toString() { return Boolean.toString(get()); } }

 

总结:这里通过定义一个 private volatile int value;通过设置 value = 1 (true) value = 0 (false),使用了硬件底层的CAS(调用UnSafe类中的本地方法)操作来保证并发情况下值的安全。

  

 

posted @ 2018-09-30 15:40  胜迹寻芳  阅读(3485)  评论(0)    收藏  举报