Uses of Unsafe

suggest change

Some uses of Unsafe are as follows:

Use API
Off heap / direct memory allocation, reallocation and deallocation allocateMemory(bytes), reallocateMemory(address, bytes) and freeMemory(address)
Memory fences loadFence(), storeFence(), fullFence()
Parking the current thread park(isAbsolute, time), unpark(thread)
Direct field and/or memory access get* and put* family of methods
Throwing unchecked exceptions throwException(e)
CAS and atomic operations compareAndSwap* family of methods
Setting memory setMemory
Volatile or concurrent operations get*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);

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

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents