Getting Instance of Unsafe

suggest change

Unsafe is stored as a private field that cannot be accessed directly. The constructor is private and the only method to access public static Unsafe getUnsafe() has privileged access. By use of reflection, there is a work-around to make private fields accessible:

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;
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents