作用: 提供一种线程安全的方式,在底层进行变量的操作,如CAS等
关键点:
- Unsafe类使用时是单例;
- Unsafe类的指令是原子的,并对其它线程是可见的,因此命令是线程安全的;
Unsafe类的使用
- 实例化时必须用bootStrap类加载器进行加载,因此无法在自己编写的类中进行实例化。可以通过JVM参数指定classPath的形式将编写的类用bootStrap类加载器进行加载;
- 可以通过反射进行加载: 下面是通过反射使用Unsafe操作类变量的例子:
public class UnsafeTest {
private int i;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public static void main(String[] args) throws NoSuchFieldException {
UnsafeTest unsafeTest = new UnsafeTest();
Unsafe unsafe = null;
try {
Class<Unsafe> unsafeClass = Unsafe.class;
Field theUnsafe = unsafeClass.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
unsafe = (Unsafe) theUnsafe.get(unsafeClass);
}catch (Exception e) {
}
long offset = unsafe.objectFieldOffset(UnsafeTest.class.getDeclaredField("i"));
unsafe.putInt(unsafeTest, offset, 2);
System.out.println(unsafeTest.getI());
}
}
注:反射实例代码参考博文:https://blog.csdn.net/iteye_10121/article/details/82553203