1. getAndSet(int newValue)
它调用的是unsafe的getAndSetInt,如下List-1,不断的循环比较,而后设置结果。会阻塞,一直到设置完成。
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-2
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
3. weakCompareAndSet(int expect, int update)
它的实现与compareAndSet一样,如下:
List-3
public final boolean weakCompareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
4. lazySet(int newValue)
它的实现如下
List-4
public final void lazySet(int newValue) {
unsafe.putOrderedInt(this, valueOffset, newValue);
}
5. getAndIncrement、getAndDecrement
如下
List-5
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