Unsafe获取
Unsafe unsafe = Unsafe.getUnsafe();
由于Unsafe为调用敏感,所以可能需要自行import,
import sun.misc.Unsafe;
使用
compareAndSwapInt
public final native boolean compareAndSwapInt(Object object, long offset, int expect, int update);
该方法为native方法,CAS核心代码,比较并交换,该方法主要逻辑就是比较传入的expect
与object
偏移offset
处对应的值是否相同,如果相同,则把update
赋给偏移位置,并返回true
,否则返回false
- object: 操作对象;
- offset: 偏移量,offset和object两个参数结合,可以确定object中某字段的内存地址;
unsafe.objectFieldOffset(Field field)
获取非静态字段的offset;unsafe.staticFieldOffset(Field field)
获取静态字段的offset;
- expect : 期望值,用于和当前内存值进行比较,如果相等则用update替换并返回true,不等返回false;
- update : 更新值,当前内存值与expect相同,则把update赋予内存值;
用例
java.util.concurrent.locks.AbstractQueuedSynchronizer
部分源码
private static final Unsafe unsafe = Unsafe.getUnsafe();
private static final long stateOffset;
private static final long headOffset;
private static final long tailOffset;
private static final long waitStatusOffset;
private static final long nextOffset;
static {
try {
stateOffset = unsafe.objectFieldOffset(AbstractQueuedSynchronizer.class.getDeclaredField("state"));
headOffset = unsafe.objectFieldOffset
(AbstractQueuedSynchronizer.class.getDeclaredField("head"));
tailOffset = unsafe.objectFieldOffset
(AbstractQueuedSynchronizer.class.getDeclaredField("tail"));
waitStatusOffset = unsafe.objectFieldOffset
(Node.class.getDeclaredField("waitStatus"));
nextOffset = unsafe.objectFieldOffset
(Node.class.getDeclaredField("next"));
} catch (Exception ex) { throw new Error(ex); }
}
/**
* Atomically sets synchronization state to the given updated
* value if the current state value equals the expected value.
* This operation has memory semantics of a {@code volatile} read
* and write.
*
* @param expect the expected value
* @param update the new value
* @return {@code true} if successful. False return indicates that the actual
* value was not equal to the expected value.
*/
protected final boolean compareAndSetState(int expect, int update) {
// See below for intrinsics setup to support this
return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
}