源码看JAVA【二十七】AtomicBoolean

版权声明: https://blog.csdn.net/jiangxuexuanshuang/article/details/88095410

1、定义

valueOffet保存了value变量的内存偏移量的值

value是AtomicBoolean保存的实际数据。1:true;0:false。因为int默认值为0,所以AtomicBoolean默认值为false

value使用了关键字volatile,保证线程间的数据都是最新的。具体的作用可参考:

https://mp.csdn.net/postedit/88094147

    // setup to use Unsafe.compareAndSwapInt for updates
    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;

2、构造

初始化value的值,无参构造默认为0

    /**
     * Creates a new {@code AtomicBoolean} with the given initial value.
     *
     * @param initialValue the initial value
     */
    public AtomicBoolean(boolean initialValue) {
        value = initialValue ? 1 : 0;
    }

    /**
     * Creates a new {@code AtomicBoolean} with initial value {@code false}.
     */
    public AtomicBoolean() {
    }

3、get():非0则为true。因为对象中各个方法的值都是1与0,所以与value == 1等价

    /**
     * Returns the current value.
     *
     * @return the current value
     */
    public final boolean get() {
        return value != 0;
    }

4、使用CAS:boolean compareAndSet(boolean expect, boolean update)

底层调用了本地方法:public final native boolean compareAndSwapInt(Object var1, long var2, int var4, int var5);

与原值进行比较,如果相等则进行更新,如果不相等则取消更新。更新成功返回true,更新失败返回false。

weakCompareAndSet与compareAndSet目前是一样的实现,想了解其中的细节差异可自行了解。

    /**
     * Atomically sets the value to the given updated value
     * if the current value {@code ==} the expected value.
     *
     * @param expect the expected value
     * @param update the new value
     * @return {@code true} if successful. False return indicates that
     * the actual value was not equal to the expected value.
     */
    public final boolean compareAndSet(boolean expect, boolean update) {
        int e = expect ? 1 : 0;
        int u = update ? 1 : 0;
        return unsafe.compareAndSwapInt(this, valueOffset, e, u);
    }

    /**
     * Atomically sets the value to the given updated value
     * if the current value {@code ==} the expected value.
     *
     * <p><a href="package-summary.html#weakCompareAndSet">May fail
     * spuriously and does not provide ordering guarantees</a>, so is
     * only rarely an appropriate alternative to {@code 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);
    }

举例一:保证一个方法的逻辑只执行一次

AtomicBoolean test = new AtomicBoolean()
public void onlyOnt() {
    if ( test.compareAndSet(false, true) ) {

    }
}

举例二:保证一个方法的同一时间只能执行一次

AtomicBoolean test = new AtomicBoolean()
public void onlyOnt() {
    if ( test.compareAndSet(false, true) ) {

        test.compareAndSet(true, false); 或者 test.set(true);
    }
}

5、set

    /**
     * Unconditionally sets to the given value.
     *
     * @param newValue the new value
     */
    public final void set(boolean newValue) {
        value = newValue ? 1 : 0;
    }

6、lazySet:并非对其它线程立即可见。

    /**
     * Eventually sets to the given value.
     *
     * @param newValue the new value
     * @since 1.6
     */
    public final void lazySet(boolean newValue) {
        int v = newValue ? 1 : 0;
        unsafe.putOrderedInt(this, valueOffset, v);
    }

7、boolean getAndSet(boolean newValue)

原子操作写入新值,直至成功写入,并返回写入前的值。

    /**
     * Atomically sets to the given value and returns the previous value.
     *
     * @param newValue the new value
     * @return the previous value
     */
    public final boolean getAndSet(boolean newValue) {
        boolean prev;
        do {
            prev = get();
        } while (!compareAndSet(prev, newValue));
        return prev;
    }

猜你喜欢

转载自blog.csdn.net/jiangxuexuanshuang/article/details/88095410