Using off-heap memory in Java

Ray Suliteanu
3 min readJan 1, 2021
Photo by Zan on Unsplash

One of the nice things about modern programming languages is Garbage Collection. As a developer you don’t have to worry much about allocating and freeing memory for your objects. With Java you just ‘new’ your class and voila a new instance of the class. And when the instance is no longer referenced, Java will take care of freeing the memory. When you create objects this way, the JVM allocates memory from ‘heap’ memory — memory it manages for you.

So why would you want to do anything else?

In Java, the JVM allocates only so much heap space, when the JVM is launched. How much heap is allocated can be controlled by command line arguments:

-Xms<size>        set initial Java heap size
-Xmx<size> set maximum Java heap size

If you run out of heap, kaboom.

Also, depending on your use case, there could be performance reasons to avoid the heap.

So how do you avoid the heap i.e. use “off-heap” memory? Java has provided the java.nio package for quite a while now, and part of the java.nio package is a Buffer interface and a Channel interface, with various implementations like ByteBuffer and MappedByteBuffer and a FileChannel and SocketChannel. I won’t get into all the various things you can do with the java.nio package here, but rather focus on the use of off-heap memory.

--

--