獲得不安全的例項

不安全儲存為無法直接訪問的私有欄位。建構函式是私有的,訪問 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;
}