Scrivio Interview library
ConceptFoundations7 min read · updated 12 November 2026

What is off-heap memory in Java, and why would a service use it? Name the ways to allocate it.

Off-heap memory is native memory that a Java program uses outside the garbage-collected heap. Services use it for large caches and I/O buffers that would otherwise add work for the garbage collector, and for data shared with native code or the operating system. We allocate it with ByteBuffer.allocateDirect, with a MemorySegment from an Arena, by memory-mapping a file, and historically with sun.misc.Unsafe; in every case the application, not the GC, must manage its size and lifetime.

Why this question is asked

When we start a Java service with -Xmx4g, it is easy to believe the process will use about 4 GB. In reality, a busy service often uses a good deal more, and some of that is off-heap memory that it asked for on purpose. Interviewers ask about it because it explains how libraries like Netty and Kafka clients get their speed, and also why containers get killed when the heap looks healthy. In this answer, we will recap the heap, see what off-heap memory is and why a service would want it, go through the four ways to allocate it with code, and finish with the responsibilities it brings, including sizing in containers.

1A Quick Recap of the Java Heap

Every object we create with new lives on the heap, the area of memory the JVM manages for us. The garbage collector, or GC, regularly finds objects that are no longer reachable and frees their space. Its size is capped by -Xmx, or by -XX:MaxRAMPercentage in a container.

This is convenient, but it has a cost that grows with the amount of live data. The GC must trace live objects, and many collectors copy them from one region to another. If a service keeps 10 GB of cached objects on the heap, the GC keeps scanning and moving those 10 GB even though they rarely change. Modern collectors such as ZGC do most of that work concurrently, but it still costs CPU.

2What Off-Heap Memory Is

Off-heap memory is memory that belongs to the Java process but sits outside the heap. The JVM asks the operating system for it directly, and the GC never scans or moves it. From Java we see it only through a handle object, such as a ByteBuffer or a MemorySegment, which holds the address and the size.

Two kinds of work benefit. The first is large, long-lived data such as a cache of a few gigabytes of serialised values: off-heap, it adds almost nothing to GC work. The second is data that crosses into native code or the operating system. When we write a heap ByteBuffer to a socket, the JDK first copies it into a temporary native buffer, because the GC might move the heap array during the system call. A direct buffer is already in native memory, so that copy disappears. This is why network libraries like Netty use direct buffers for I/O.

Step throughMemory of one Java process
  1. Java heapobjects created with new; scanned and freed by the GC; capped by -Xmx
  2. Off-heap memory chosen by the applicationdirect buffers, MemorySegments, mapped files
  3. JVM internal memorymetaspace, thread stacks, code cache, GC structures
  4. Native librariesmemory allocated by C code loaded into the process

4 layers, from the top down. Step through them one at a time.

All four layers count towards the process size and a container's memory limit.

3Four Ways to Allocate It

The oldest supported way is a direct ByteBuffer. Its memory is freed when the small ByteBuffer object on the heap is garbage collected, which can be much later than we would like.

Java
ByteBuffer direct = ByteBuffer.allocateDirect(64 * 1024); // 64 KB outside the heap
System.out.println(direct.isDirect()); // true
direct.putLong(0, 42L);
System.out.println(direct.getLong(0)); // 42
// FFM API (final in Java 22): the Arena decides when memory is freed
try (Arena arena = Arena.ofConfined()) {
MemorySegment seg = arena.allocate(1024 * 1024); // 1 MB, zero-filled
seg.set(ValueLayout.JAVA_LONG, 0, 42L);
System.out.println(seg.get(ValueLayout.JAVA_LONG, 0)); // 42
} // freed right here
// seg.get(...) after this point throws IllegalStateException: already closed
// Memory-mapped file: the OS pages the file in and out for us
try (FileChannel ch = FileChannel.open(Path.of("prices.bin"), READ);
Arena arena = Arena.ofConfined()) {
MemorySegment file = ch.map(FileChannel.MapMode.READ_ONLY, 0, ch.size(), arena);
System.out.println(file.byteSize()); // size of the file in bytes
}
Ways to get off-heap memory
WayFreed whenNotes
ByteBuffer.allocateDirectthe buffer object is collectedlimited by -XX:MaxDirectMemorySize
MemorySegment from an Arenathe arena is closed (or GC for ofAuto)Java 22+, bounds and lifetime checked
Memory-mapped filethe mapping is releasedthe OS loads pages on demand
sun.misc.Unsafeonly when we call freeMemoryunchecked, deprecated for removal

The FFM API's MemorySegment is the modern choice. Notice that the Arena makes the lifetime explicit: a confined arena frees its memory deterministically when the try block ends, and any later access fails with an exception instead of reading freed memory. Arena.ofShared() allows several threads, Arena.ofAuto() leaves freeing to the GC like a direct buffer, and Arena.global() never frees.

A memory-mapped file is a third way. The operating system maps the file into the process's address space and loads pages on demand, so a 20 GB file can be read as if it were memory without loading it all. Before Java 22 we used FileChannel.map returning a MappedByteBuffer; the overload with an Arena returns a MemorySegment.

The fourth way is historical: sun.misc.Unsafe.allocateMemory returned a raw address with no bounds checks at all. Libraries used it for years, but its memory-access methods are deprecated for removal, and new code should use the FFM API.

4The Responsibilities That Come With It

Off-heap memory gives up the GC's help, so the application takes on its jobs. We must cap the size ourselves; direct buffers are limited by -XX:MaxDirectMemorySize (by default about the same as the maximum heap), but MemorySegments and native libraries have no JVM-wide limit. We must free memory at the right time, which is easy with a confined arena and easy to get wrong with direct buffers that wait for a GC.

Off-heap data is also invisible in a heap dump. A heap dump shows a 48-byte DirectByteBuffer object, not the 64 MB it points to. To see off-heap usage we look at BufferPoolMXBean metrics for direct and mapped buffers, at Native Memory Tracking (jcmd <pid> VM.native_memory summary), or at the process's resident size from the operating system.

5Sizing a Container That Uses Off-Heap Memory

A container's memory limit applies to the whole process, not to the heap. If the limit is 8 GB and we set -Xmx7g, then 1 GB of direct buffers plus metaspace and thread stacks pushes the process over the limit, and the kernel kills it with no Java error at all.

Java
# container limit 8 GB; the service keeps up to 2 GB in direct buffers
java -XX:MaxRAMPercentage=50 \
-XX:MaxDirectMemorySize=2g \
-jar service.jar
# heap max 4 GB + direct 2 GB + about 0.5 to 1 GB JVM overhead = room to spare

So the rule is to size the heap smaller and leave room. We add up the heap, the planned off-heap usage and an allowance for JVM overhead, and make sure the total stays well under the limit.

6Follow-up questions

Is off-heap memory faster to access than the heap?

Not in general. Reading a field of a heap object is as fast as reading off-heap memory, and often simpler. Off-heap wins on GC cost for large data and on avoiding copies for I/O, but values usually need to be serialised into bytes and read back, which costs CPU.

Why can a direct buffer leak even though it is freed automatically?

Because its native memory is freed only after the small ByteBuffer object becomes unreachable and the GC processes it. If the heap is quiet, the GC may not run for a long time, so the native memory stays allocated. When direct memory runs out, the JDK triggers a GC and then throws OutOfMemoryError: Direct buffer memory if that is not enough.

What does MaxRAMPercentage default to?

25 percent of the container's memory, which is conservative. Many services raise it to between 50 and 75 percent, but services that use a lot of off-heap memory should stay at the lower end.

7Conclusion

In this answer, we saw that off-heap memory is native memory outside the garbage-collected heap. Services use it to keep large caches and buffers out of the GC's way and to share data with native code and the operating system without copies. We can allocate it with ByteBuffer.allocateDirect, with a MemorySegment from an Arena, with memory-mapped files, and historically with Unsafe. In return, the application must limit and free that memory itself, cannot see it in heap dumps, and must leave room for it when sizing a container.

What to say in the interviewAbout 80 seconds aloud

Open with

Off-heap memory is native memory that the Java process uses outside the garbage-collected heap. The GC never scans or moves it; we only hold a small handle object, like a ByteBuffer or a MemorySegment.

Then, if they want more

A service uses it for two reasons. One is large, long-lived data such as a multi-gigabyte cache, which would otherwise add tracing and copying work for the GC. The other is I/O and native interop: a direct buffer can be passed to a socket or to C code without the extra copy a heap array needs.

There are four ways to allocate it: ByteBuffer.allocateDirect, a MemorySegment from an Arena in the FFM API, which is the modern option because the arena frees the memory deterministically, a memory-mapped file through FileChannel.map, and historically sun.misc.Unsafe, which is now deprecated for memory access.

The trade-off is that I manage size and lifetime myself, for example with MaxDirectMemorySize, and that it does not appear in heap dumps, so I watch it with buffer pool metrics or Native Memory Tracking. And because a container limit covers the whole process, I size the heap smaller, maybe 50 percent of the limit, to leave room for it.

About this answer

Last updated
12 November 2026
Versions it names
Java 22
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What is off-heap memory in Java, and why would a service use it? Name the ways to...": https://scrivio-interview-library.netlify.app/java/foreign-memory-and-native/0d1a523a73/