获得不安全的实例

不安全存储为无法直接访问的私有字段。构造函数是私有的,访问 public static Unsafe getUnsafe() 的唯一方法是具有特权访问权限。通过使用反射,可以通过一种方法使私有字段可访问:

public static final Unsafe UNSAFE;

static {
    Unsafe unsafe = null;

    try {
        final PrivilegedExceptionAction<Unsafe> action = () -> {
            final Field f = Unsafe.class.getDeclaredField("theUnsafe");
            f.setAccessible(true);

            return (Unsafe) f.get(null);
        };

        unsafe = AccessController.doPrivileged(action);
    } catch (final Throwable t) {
        throw new RuntimeException("Exception accessing Unsafe", t);
    }

    UNSAFE = unsafe;
}