Java Unsafe类理解

2022-03-05 18:40:29 浏览数 (1)

作用: 提供一种线程安全的方式,在底层进行变量的操作,如CAS等

关键点:

  1. Unsafe类使用时是单例;
  2. Unsafe类的指令是原子的,并对其它线程是可见的,因此命令是线程安全的;

Unsafe类的使用

  1. 实例化时必须用bootStrap类加载器进行加载,因此无法在自己编写的类中进行实例化。可以通过JVM参数指定classPath的形式将编写的类用bootStrap类加载器进行加载;
  2. 可以通过反射进行加载: 下面是通过反射使用Unsafe操作类变量的例子:
代码语言:java复制
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

0 人点赞