Using the sun.misc.Unsafe class

The sun.misc.Unsafe class, like other sun classes, is not officially documented or supported. It has been used to circumvent some of Java's built-in memory management safety features. While this can be viewed as a window to greater control and flexibility in our code, it is a terrible programming practice.

The class had a single private constructor, so an instance of the class could not easily be instantiated. So, if we tried to instantiate an instance with myUnsafe = new Unsafe()SecurityException would be thrown in most circumstances. This somewhat unreachable class has over 100 methods that permitted operations on arrays, classes, and objects. Here is a brief sampling of those methods:

    
Arrays           Classes           Objects
arrayBaseOffset           defineAnonymousClass           allocateInstance
arrayIndexScale           defineClass           objectFieldOffset
           ensureClassInitialized           
           staticFieldOffset           

Here is a secondary grouping of the sun.misc.Unsafe class method for information, memory, and synchronization:

    
Information           Memory           Synchronization
addressSize           allocateMemory           compareAndSwapInt
pageSize           copyMemory           monitorEnter
           freeMemory           monitorExit
           getAddress           putOrderedEdit
           getInt           tryMonitorEnter
           putInt           

 

The sun.misc.Unsafe class was earmarked for removal in Java 9. There was actually some opposition to this decision in the programming industry. To put their concerns to rest, the class has been depreciated, but will not be completely removed.