http://blog.youkuaiyun.com/hsuxu/article/details/9467651
CAS是Compare and Swap的简写,比较然后交换。
以类AtomicInteger中的compareAndSet方法为例,可以看到调用的是unsafe中的compareAndSwapInt来实现的,并没有使用锁。
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
这里要注意的是valueOffset,是通过unsafe方法中的objectFieldOffset来取得AtomicInteger中对应的value的偏移量valueOffset。
static {
try {
valueOffset = unsafe.objectFieldOffset
(AtomicInteger.class.getDeclaredField("value"));
} catch (Exception ex) { throw new Error(ex); }
}
private volatile int value;
剩下才是关键就是unsafe类了,Unsafe分析:

本文详细介绍了CAS(Compare and Swap)机制的实现原理,以AtomicInteger类中的compareAndSet方法为例,展示了如何通过Unsafe类中的compareAndSwapInt方法实现无锁操作。文章深入探讨了valueOffset的获取方式及其作用。
877

被折叠的 条评论
为什么被折叠?



