AtomicInteger之實現簡析

1. getAndSet(int newValue)

    它調用的是unsafe的getAndSetInt,以下List-1,不斷的循環比較,然後設置結果。會阻塞,一直到設置完成。java

    List-1多線程

public final int getAndSetInt(Object var1, long var2, int var4) {
        int var5;
        do {
            var5 = this.getIntVolatile(var1, var2);
        } while(!this.compareAndSwapInt(var1, var2, var5, var4));

        return var5;
    }

2. compareAndSet(int expect, int update)

    它調用的直接就是unsafe的compareAndSwapInt,這個方法不會阻塞調用,會當即返回,根據返回的boolean結果來判斷是否成功併發

    List-2this

public final boolean compareAndSet(int expect, int update) {
        return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
    }

3. weakCompareAndSet(int expect, int update)

    它的實現與compareAndSet同樣,以下:atom

    List-3spa

public final boolean weakCompareAndSet(int expect, int update) {
        return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
    }

4. lazySet(int newValue)

    它的實現以下.net

    List-4線程

public final void lazySet(int newValue) {
        unsafe.putOrderedInt(this, valueOffset, newValue);
    }

5. getAndIncrement、getAndDecrement

    以下code

    List-5rem

public final int getAndIncrement() {
        return unsafe.getAndAddInt(this, valueOffset, 1);
    }

    List-6

public final int getAndDecrement() {
        return unsafe.getAndAddInt(this, valueOffset, -1);
    }

    unsafe的getAndAddInt的實現以下List-7:

    List-7

public final int getAndAddInt(Object var1, long var2, int var4) {
        int var5;
        do {
            var5 = this.getIntVolatile(var1, var2);
        } while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));

        return var5;
    }

 

    爲何AtomicInteger中的value有volatile修飾?這是因爲有多個線程併發修改它,爲了保證多線程之間的可見性。

    爲何AtomicBoolean中的value是int類型,而不是boolean類型,見https://stackoverflow.com/questions/13724858/why-java-util-concurrent-atomic-atomicboolean-is-internally-implemented-with-int ,感受也沒有真正的說清楚。

 

問題:

unsafe的compareAndSwapInt,底層上是如何實現的,它是native方法

unsafe的putOrderedInt,底層上是如何實現的,它是native方法

openjdk6的unsafe.cpp文件:http://hg.openjdk.java.net/jdk6/jdk6/hotspot/file/4fc084dac61e/src/share/vm/prims/unsafe.cpp 

openjdk7的unsafe.cpp文件:http://hg.openjdk.java.net/jdk7/jdk7/hotspot/file/4fc084dac61e/src/share/vm/prims/unsafe.cpp

openjdk8的unsafe.cpp文件:http://hg.openjdk.java.net/jdk8u/jdk8u60/hotspot/file/37240c1019fd/src/share/vm/prims/unsafe.cpp

相關文章
相關標籤/搜索