天天看點

cas調用鍊,cmpxchg解釋

//java.util.concurrent.atomic.AtomicInteger.java
    public final boolean compareAndSet(int expect, int update) {
        return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
    }
           
//sun.misc.Unsafe.java
    public final native boolean compareAndSwapInt(Object o, long offset,
                                                  int expected,
                                                  int x);
           
// http://hg.openjdk.java.net/jdk8u/jdk8u/  \hotspot\src\share\vm\prims\unsafe.cpp

// These are the methods prior to the JSR 166 changes in 1.6.0
static JNINativeMethod methods_15[] = {
//...
    {CC "compareAndSwapInt",  CC "(" OBJ "J""I""I"")Z",      FN_PTR(Unsafe_CompareAndSwapInt)},
//...

};

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
           
// http://hg.openjdk.java.net/jdk8u/jdk8u/  \hotspot\src\share\vm\runtime\atomic.cpp

unsigned Atomic::cmpxchg(unsigned int exchange_value,
                         volatile unsigned int* dest, unsigned int compare_value) {
  assert(sizeof(unsigned int) == sizeof(jint), "more work to do");
  return (unsigned int)Atomic::cmpxchg((jint)exchange_value, (volatile jint*)dest,
                                       (jint)compare_value);
}
           
// http://hg.openjdk.java.net/jdk8u/jdk8u/ \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
  }
}
           
cas調用鍊,cmpxchg解釋

繼續閱讀