Getting Instance of Unsafe

suggest change

sun.misc.Unsafe is stored in a private field and its constructor is private. public static Unsafe getUnsafe() throws SecurityException unless the caller is loaded by the bootstrap class loader. Reflection can read the field on Java 8. From Java 9 the same setAccessible call throws InaccessibleObjectException unless jdk.unsupported/sun.misc is open. AccessController.doPrivileged does not open it.

public static final sun.misc.Unsafe UNSAFE;

static {
    sun.misc.Unsafe unsafe = null;

    try {
        final java.security.PrivilegedExceptionAction<sun.misc.Unsafe> action = () -> {
            final java.lang.reflect.Field f = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
            f.setAccessible(true);

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

        unsafe = java.security.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