理解AtomicBoolean

這里我們就從AtomicBoolean開始說吧,自己正好也復(fù)習(xí)一下。對于官方的說明是:

可以用原子方式更新的 boolean 值。有關(guān)原子變量屬性的描述,請參閱 java.util.concurrent.atomic
包規(guī)范。AtomicBoolean 可用在應(yīng)用程序中(如以原子方式更新的標(biāo)志),但不能用于替換 Boolean。

換一句話說,Atomic就是原子性的意思,即能夠保證在高并發(fā)的情況下只有一個線程能夠訪問這個屬性值。(類似我們之前所說的volatile)

一般情況下,我們使用 AtomicBoolean 高效并發(fā)處理 “只初始化一次” 的功能要求:

private static AtomicBoolean initialized = new AtomicBoolean(false);
public void init()
{
   if( initialized.compareAndSet(false, true) )
   {
       // 這里放置初始化代碼....
   }
}

如果沒有AtomicBoolean,我們可以使用volatile做如下操作:

public static volatile initialized = false;
public void init()
{
    if( initialized == false ){
        initialized = true;
        // 這里初始化代碼....
    }
}

既然如此神奇,那么我們看看AtomicBoolean的源碼時如何實現(xiàn)的,查看源碼如下:

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();
    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;

    /**
     * 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() {
    }

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

    /**
     * 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);
    }

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

    /**
     * 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);
    }

    /**
     * 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;
    }

    /**
     * Returns the String representation of the current value.
     * @return the String representation of the current value
     */
    public String toString() {
        return Boolean.toString(get());
    }

}

你猜的沒錯,AtomicBoolean就是使用了Volatile屬性來完成的。

Java6以后出現(xiàn)的很多的原子行的類,除了上述我們所說的AtomicBoolean以外,AtomicBoolean家族還是比較強(qiáng)大的,后面我們有時間在一一介紹。包括:

基本類:
AtomicInteger、AtomicLong、AtomicBoolean;
引用類型:
AtomicReference、AtomicReference的ABA實例、AtomicStampedRerence、AtomicMarkableReference;
數(shù)組類型:
AtomicIntegerArray、AtomicLongArray、AtomicReferenceArray
屬性原子修改器(Updater):
AtomicIntegerFieldUpdater、AtomicLongFieldUpdater、AtomicReferenceFieldUpdater

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容