Java Language Uses of Unsafe


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`