public final class Unsafe {
private Unsafe() {
}
@CallerSensitive
public static Unsafe getUnsafe() {
Class var0 = Reflection.getCallerClass();
if (!VM.isSystemDomainLoader(var0.getClassLoader())) {
throw new SecurityException("Unsafe");
} else {
return theUnsafe;
}
}
}
特点:
1.该类不能被继承
2.该类不能被实例化(new)
3.该类不能被其他的clasLoader装载
有趣的获取实例方式
@CallerSensitive
public static Unsafe getUnsafe() {
Class var0 = Reflection.getCallerClass();
if (!VM.isSystemDomainLoader(var0.getClassLoader())) {
throw new SecurityException("Unsafe");
} else {
return theUnsafe;
}
}
查看:VM.isSystemDomainLoader(var0.getClassLoader()) method
public static boolean isSystemDomainLoader(ClassLoader var0) {
return var0 == null;
}
var0加载器为null
只有bootstarp classLoad为null 只能被bootstarp clasload加载
有没有办法获取到UnSafe对象呢?
private Unsafe unsafe;
private int count = 0;
private Object obj = new Object();
public SafeDemo() {
try {
Class<Unsafe> unsafeClass = Unsafe.class;
Field theUnsafe = unsafeClass.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
unsafe = (Unsafe) theUnsafe.get(null);
} catch (Exception e) {
e.printStackTrace();
}
}
似曾相识的成员对象
/** @deprecated */
@Deprecated
public native void monitorEnter(Object var1);
/** @deprecated */
@Deprecated
public native void monitorExit(Object var1);
synchronized 中的monitorEnter/monitorExit
天使与魔鬼同在的方法
public native long allocateMemory(long var1);
public native long reallocateMemory(long var1, long var3);
使用UnSafe仿写synchronized锁
private Unsafe unsafe;
private int count = 0;
private Object obj = new Object();
public void toSomeThing() {
try {
unsafe.monitorEnter(obj);
} catch (Exception e) {
e.printStackTrace();
} finally {
unsafe.monitorExit(obj);
}
}
public int getCount() {
return count;
}