Search code examples
javaclassloader

Is it possible to use Java Unsafe in user code?


I'm reading code in java.util.concurrent package, and i find the class Unsafe(which is used to implement those synchronizers) interesting. I may never use it in any real code because the class name itself seems to discourage doing that, but out of curiosity, i have 2 questions on this class.

1). The singleton accessor of this class is like this:

    public static Unsafe getUnsafe() {
        Class cc = sun.reflect.Reflection.getCallerClass(2);
        if (cc.getClassLoader() != null)
            throw new SecurityException("Unsafe");
        return theUnsafe;
    }

So if this method is invoked from user code, it will throw an exception. How to work around this? (possibly by making my own class loaded by the bootstrap class loader? is this possible?)

2). The above code assumes that getClassLoader will return null for classes that are loaded by the boostrap class loader. But the javadoc of Class#getClassLoader says "Some implementations may use null to represent the bootstrap class loader.", which means there is NO guarantee on this assumption. For implementations that do violate this assumption, wouldn't Unsafe(as well as various classes such as ReentrantLock that depends on it) fail to work at all?

Thanks!


Solution

  • How to work around this?

    You can gain access to the class like so (provided the security manager will permit the change of accessibility):

    public static Unsafe getUnsafe() {
        try {
                Field f = Unsafe.class.getDeclaredField("theUnsafe");
                f.setAccessible(true);
                return (Unsafe)f.get(null);
        } catch (Exception e) { /* ... */ }
    }
    

    For implementations that do violate this assumption, wouldn't Unsafe ... fail to work at all?

    The details of the Unsafe class are also implementation-specific. There is no reason to expect this particular Unsafe to be able to work with any other implementation of the class loader subsystem.