JAVA裏的CAS算法簡析

Atomic 從JDK5開始, java.util.concurrent包裏提供了不少面向併發編程的類. 使用這些類在多核CPU的機器上會有比較好的性能.
主要緣由是這些類裏面大多使用(失敗-重試方式的)樂觀鎖而不是synchronized方式的悲觀鎖.

跟蹤了一下AtomicInteger的incrementAndGet的實現。僅作個筆記, 方便之後再深刻研究。

1. incrementAndGet的實現

    public final int incrementAndGet() {
        for (;;) {
            int current = get();
            int next = current + 1;
            if (compareAndSet(current, next))
                return next;
        }
    }

首先能夠看到他是經過一個無限循環(spin)直到increment成功爲止.  html

循環的內容是java

1.取得當前值編程

2.計算+1後的值windows

3.若是當前值還有效(沒有被)的話設置那個+1後的值多線程

4.若是設置沒成功(當前值已經無效了即被別的線程改過了), 再從1開始.架構


2. compareAndSet的實現

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

直接調用的是UnSafe這個類的compareAndSwapInt方法併發

全稱是sun.misc.Unsafe. 這個類是Oracle(Sun)提供的實現. 能夠在別的公司的JDK裏就不是這個類了app


3. compareAndSwapInt的實現

    /**
     * Atomically update Java variable to <tt>x</tt> if it is currently
     * holding <tt>expected</tt>.
     * @return <tt>true</tt> if successful
     */
    public final native boolean compareAndSwapInt(Object o, long offset,
                                                  int expected,
                                                  int x);

能夠看到, 不是用Java實現的, 而是經過JNI調用操做系統的原生程序.函數


4. compareAndSwapInt的native實現

若是你下載了OpenJDK的源代碼的話在hotspot\src\share\vm\prims\目錄下能夠找到unsafe.cpp

UNSAFE_ENTRY(jboolean, Unsafe_CompareAndSwapInt(JNIEnv *env, jobject unsafe, jobject obj, jlong offset, jint e, jint x))
  UnsafeWrapper("Unsafe_CompareAndSwapInt");
  oop p = JNIHandles::resolve(obj);
  jint* addr = (jint *) index_oop_from_field_offset_long(p, offset);
  return (jint)(Atomic::cmpxchg(x, addr, e)) == e;
UNSAFE_END

能夠看到實際上調用Atomic類的cmpxchg方法.oop


5. Atomic的cmpxchg
這個類的實現是跟操做系統有關, 跟CPU架構也有關, 若是是windows下x86的架構
實如今hotspot\src\os_cpu\windows_x86\vm\目錄的atomic_windows_x86.inline.hpp文件裏

inline jint     Atomic::cmpxchg    (jint     exchange_value, volatile jint*     dest, jint     compare_value) {
  // alternative for InterlockedCompareExchange
  int mp = os::is_MP();
  __asm {
    mov edx, dest
    mov ecx, exchange_value
    mov eax, compare_value
    LOCK_IF_MP(mp)
    cmpxchg dword ptr [edx], ecx
  }
}

在這裏能夠看到是用嵌入的彙編實現的, 關鍵CPU指令是 cmpxchg

到這裏無法再往下找代碼了. 也就是說CAS的原子性其實是CPU實現的. 其實在這一點上仍是有排他鎖的. 只是比起用synchronized, 這裏的排他時間要短的多. 因此在多線程狀況下性能會比較好.

代碼裏有個alternative for InterlockedCompareExchange

這個InterlockedCompareExchange是WINAPI裏的一個函數, 作的事情和上面這段彙編是同樣的

http://msdn.microsoft.com/en-us/library/windows/desktop/ms683560%28v=vs.85%29.aspx


6. 最後再貼一下x86的cmpxchg指定

Opcode CMPXCHG


CPU: I486+ 
Type of Instruction: User 

Instruction: CMPXCHG dest, src 

Description: Compares the accumulator with dest. If equal the "dest" 
is loaded with "src", otherwise the accumulator is loaded 
with "dest". 

Flags Affected: AF, CF, OF, PF, SF, ZF 

CPU mode: RM,PM,VM,SMM 
+++++++++++++++++++++++ 
Clocks: 
CMPXCHG reg, reg 6 
CMPXCHG mem, reg 7 (10 if compartion fails) 

源地址:http://www.blogjava.net/mstar/archive/2013/04/24/398351.html

相關文章
相關標籤/搜索