Java Language sun.misc.Unsafe Uses of Unsafe

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!


Some uses of unsafe is s follows:

Off heap / direct memory allocation, reallocation and deallocationallocateMemory(bytes), reallocateMemory(address, bytes) and freeMemory(address)
Memory fencesloadFence(), storeFence(), fullFence()
Parking current threadpark(isAbsolute, time), unpark(thread)
Direct field and or memory accessget* and put* family of methods
Throwing unchecked exceptionsthrowException(e)
CAS and Atomic OperationscompareAndSwap* family of methods
Setting out memorysetMemory
Volatile or concurrent operationsget*Volatile, put*Volatile, putOrdered*

The get and put family of methods are relative to a given object. If the object is null then it is treated as an absolute address.

// Putting a value to a field
protected static long fieldOffset = UNSAFE.objectFieldOffset(getClass().getField("theField"));
UNSAFE.putLong(this, fieldOffset , newValue);

// Puting an absolute value
 UNSAFE.putLong(null, address, newValue);
 UNSAFE.putLong(address, newValue);

Some methods are only defined for int and longs. You can use these methods on floats and doubles using floatToRawIntBits, intBitsToFloat,doubleToRawLongBits,longBitsToDouble`

Got any Java Language Question?