java.util.concurrent的AtomicInteger类详解

java.util.concurrent包下面有不少原子性的线程安全的数据结构的实现。研究一下经常使用的AtomicInteger类。html

AtomicInteger类对应着经常使用的int类型,看一下它如何实现原子性的。java

static {
  try {
    valueOffset = unsafe.objectFieldOffset
        (AtomicInteger.class.getDeclaredField("value"));
  } catch (Exception ex) { throw new Error(ex); }
}
private volatile int value;
public AtomicInteger(int initialValue) {
    value = initialValue;
}
public AtomicInteger() {
}

static块里面的看不懂。里面的unsafe会在后面提到。windows

下面的代码能够看出,基本的数据存数是靠volatile int value来实现的。安全

可是volatile关键字是实现不了并发安全的(volatile关键字详解),他对数据操做的方法确定是还有其余缘由。数据结构

get()、set()等不对原有值依赖的方法volatile就能够实现指望的功能。咱们看一下多线程

getAndIncrement()、incrementAndGet()等方法是如何实现的。
public final int incrementAndGet() {
        for (;;) {
            int current = get();
            int next = current + 1;
            if (compareAndSet(current, next))
                return next;
        }
    }

关键的是compareAndSet(current,next)方法的实现。架构

/**
     * 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 true if successful. False return indicates that
     * the actual value was not equal to the expected value.
     */
    public final boolean compareAndSet(int expect, int update) {
        return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
    }

能够看到它的注解说明,当value与当前指望的值相等的时候,原子性的更新value。照这样说就实现了并发安全,但他到底怎么实现的呢?并发

下面是Unsafe类中的方法app

public final native boolean compareAndSwapInt(Object var1, long var2, int var4, int var5);

不是用Java实现的, 而是经过JNI调用操做系统的原生程序.一般状况下周到这里就中止了,但在网上找了一下,有说明,水平还没到能本身往下搞明白。函数

下面都是截取的网上的说明:

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

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

最后再贴一下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

C语言的东西都忘干净了,看不太懂了,最后的CPU的实现更看不明白了。可是知道了它是并发安全的是在cpu层实现的,目测效率应该比synchronized高。

这里还有两篇文章,一篇是Volatile、AtomicLong、synchronized三者效率的http://hehongwei44.iteye.com/blog/1244732

一篇是volatile正确使用场景的http://www.ibm.com/developerworks/cn/java/j-jtp06197.html

相关文章
相关标签/搜索