sun.misc.Unsafe and Off Heap Memory
Join the DZone community and get the full member experience.Join For Free
OverviewThe class sun.misc.Unsafe allows you to many of the things you shouldn't be able to do in Java, but are still useful in very specific cases. It is to be avoided 99% of the time, however there are rare occasions where this is the only solution which makes sense.
This blog considers how it has been using in OpenHFT and what functionality I would like to see in Java 9. In particular, accessing large amount of memory without impacting the GC can be done this way. Sharing memory between processes, without significant overhead, can only be done this way in Java.
Allocating and freeing off heap memory.
public native long allocateMemory(); public native void freeMemory(long address);These two method allow you to allocate any size of off heap memory. It is not limited to Integer.MAX_VALUE bytes and you get raw memory where you can apply bounds checking as you need to. e.g. Bytes.writeUTF(String) calculates the length of the encoded string, and checks that the whole string would fit, once, not on each byte.
Java-Lang uses the same internal Cleaner class that DirectByteBuffer uses to ensure the memory is freed. Ideally this wouldn't be so internal.
Raw access to memory
public native Xxx getXxx(Object, long offset); public native void putXxx(Object, long offset);
Thread safe access to memory
public native Xxx getVolatileXxx(Object, long offset); public native void putOrderedXxx(Object, long offset);
public native boolean compareAndSwapXxxx(Object, long offset, Xxx expected, Xxx setTo)
- TCP - 9 micro-seconds.
- FileLocks - 5.5 micro-seconds.
- CAS - 0.12 micro-seconds.
- Ordered write - 0.02 micro-seconds (Half round trip, if this pattern can be used)
On heap object allocation
public native Object allocateInstance(Class clazz);
Published at DZone with permission of Peter Lawrey, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.