4.4.3 Java中的指针:Unsafe类

java多线程编程的无锁CAS底层都是通过 Unsafe进行操作的:源码如下

public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
this:我们要操作的对象
valueOffset:偏移量,方便我们快速查找这个对象信息
expect:期望值
update:要修改的值



其中 Unsafe还有几个方法如下



但是在jdk中我们并不能直接使用此类,而是必须通过 Unsafe.getUnsafe()获取,它是jdk的内部使用的专属类。

@CallerSensitive
public static Unsafe getUnsafe() {
Class var0 = Reflection.getCallerClass();
if(var0.getClassLoader() != null) {
throw new SecurityException("Unsafe");
} else {
return theUnsafe;
}
}

原文地址:https://www.cnblogs.com/anxbb/p/8658757.html