JAVA裡的CAS演算法簡析

來源:互聯網
上載者:User

標籤:nbsp   ted   his   job   oop   post   index   wrap   resolve   

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成功為止.  

迴圈的內容是

1.取得當前值

2.計算+1後的值

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裡就不是這個類了


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方法.


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, reg6 
CMPXCHG mem, reg7 (10 if compartion fails) 

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

JAVA裡的CAS演算法簡析

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.