Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

What is the difference between a heap ByteBuffer and a direct ByteBuffer in Java NIO? When is the memory of a direct buffer freed?

ByteBuffer.allocate creates a buffer backed by an ordinary byte array on the Java heap, while ByteBuffer.allocateDirect reserves native memory outside the heap that the operating system can read and write directly, which saves a copy during I/O. A direct buffer's native memory is freed only after the ByteBuffer object becomes unreachable, a GC notices it and its Cleaner runs, which can be much later; the total is capped by MaxDirectMemorySize, which defaults to the maximum heap size.

Why this question is asked

Direct buffers are behind most fast networking in Java: Netty, gRPC, Kafka clients and the JDK's own socket code all use them. They are also behind a class of memory problems that heap dumps do not show, because the memory lives outside the heap. Interviewers ask this to see whether we know the trade-off and, above all, when that memory actually comes back. In this answer, we will compare the two kinds of buffer, see why direct buffers make I/O cheaper, follow the life of a direct buffer until its memory is freed, look at the limit and its error, and see how libraries avoid relying on the garbage collector.

1Two Kinds of ByteBuffer

A ByteBuffer is a container of bytes with a position and a limit, used by NIO channels to read and write data. The two factory methods create very different things behind the same interface.

Java
ByteBuffer heap = ByteBuffer.allocate(8192);
System.out.println(heap.isDirect()); // false
System.out.println(heap.hasArray()); // true: backed by a byte[8192] on the heap
ByteBuffer direct = ByteBuffer.allocateDirect(8192);
System.out.println(direct.isDirect()); // true
System.out.println(direct.hasArray()); // false: 8,192 bytes of native memory
// The ByteBuffer object itself is small and lives on the heap; only its data is outside.
Heap and direct buffers side by side
allocateallocateDirect
Where the bytes livebyte[] on the Java heapNative memory outside the heap
Allocation costCheapMore expensive, best reused
Copy during channel I/OCopied into a temporary direct bufferOS reads and writes it directly
When memory is freedNormal GCAfter GC finds the object and its Cleaner runs
Limit-XmxMaxDirectMemorySize

Notice the last comment. A direct buffer is a small Java object on the heap that holds the address of a block of native memory. That split is the key to everything that follows: the GC sees a tiny object, while the real cost sits outside the heap.

2Why Direct Buffers Save a Copy

When we write to a socket, the operating system needs the data at a fixed native address. A byte array on the heap does not have one, because the GC may move it at any time. So when we pass a heap buffer to a channel, the JDK first copies the bytes into a temporary direct buffer, which it caches per thread, and then hands that to the OS. With a direct buffer, the data is already in native memory, so the OS reads it in place and the extra copy disappears.

For a service moving gigabytes per minute through sockets or files, removing one copy per I/O operation is a real saving in CPU and memory bandwidth. For code that only processes bytes in Java, heap buffers are just as good and simpler.

3When the Native Memory Is Freed

There is no free() method on a direct ByteBuffer in the public API. When the JDK allocates one, it also registers a Cleaner, an object that runs a small release action once the buffer becomes unreachable. The sequence is what makes direct memory surprising.

Step throughThe life of a direct buffer
ApplicationJDK (Bits, Cleaner)GCNative memory
allocateDirect(1 MB)
reserve and allocate 1 MB
use the buffer, then drop the last reference
later: a GC runs and finds the buffer unreachable
the Cleaner becomes eligible to run
free 1 MB, unreserve the amount

6 messages in order. Play them, or step through them one at a time.

Until a GC happens to examine the buffer's object, its native memory stays allocated.

4The Limit and Its Error

The total size of direct buffers is limited by MaxDirectMemorySize. If we do not set it, the limit is about the maximum heap size, so a JVM with -Xmx4g may hold up to 4 GB of direct buffers on top of its heap, which matters in a container. When an allocation would cross the limit, the JDK first tries to free memory: it triggers a GC through System.gc() and waits briefly for Cleaners to run. If there is still not enough room, it throws an error.

Java
// -XX:MaxDirectMemorySize=64m
List<ByteBuffer> keep = new ArrayList<>();
for (int i = 0; i < 100; i++) {
keep.add(ByteBuffer.allocateDirect(1024 * 1024)); // fine for the first 64
}
// java.lang.OutOfMemoryError: Cannot reserve 1048576 bytes of direct buffer memory
// (allocated: 67108864, limit: 67108864)

The exact wording depends on the JDK version, but it always mentions direct buffer memory. The problem appears in two shapes: real leaks, where buffers stay reachable, and slow release, where buffers are dead but the GC has not run, because the heap is quiet while native memory fills up.

5How Libraries Avoid Waiting for the GC

Because allocation is expensive and release depends on the GC, high-performance libraries do not create a direct buffer per request. Netty, for example, allocates large direct chunks once, hands out slices from a pool, and tracks each buffer with a reference count. When the count drops to zero after release(), the slice goes straight back to the pool; no GC is needed. Netty also has a leak detector that reports buffers garbage-collected without being released.

The JDK's own Foreign Function and Memory API, final since JDK 22, offers the same kind of control for our own code: memory allocated in an Arena is freed exactly when the arena is closed.

6Follow-up questions

Why does -XX:+DisableExplicitGC interact badly with direct buffer allocation?

Because the JDK's own recovery step uses System.gc(). When a direct allocation would exceed MaxDirectMemorySize, the JDK calls System.gc() so that unreachable buffers are found and their Cleaners run, then retries. With DisableExplicitGC, that call does nothing, so dead buffers whose objects have already been promoted to the old generation are not found, and the allocation fails with OutOfMemoryError even though most of the memory belongs to garbage. If we want to stop libraries from forcing full GCs, -XX:+ExplicitGCInvokesConcurrent with G1 is a safer choice, because the call still triggers a concurrent cycle.

Should I always use direct buffers for I/O?

No. They pay off for long-lived buffers that are reused for large amounts of I/O. Allocating a fresh direct buffer for each small operation is slower than using a heap buffer, because direct allocation and release are expensive and the JDK copies through its cached temporary buffers anyway.

How can I see how much direct memory is in use?

The BufferPoolMXBean named direct reports the count and total capacity, and Spring Boot Actuator exposes it as jvm.buffer.memory.used. Native memory tracking includes it in the Other category.

7Conclusion

In this answer, we saw that ByteBuffer.allocate uses a heap byte array while allocateDirect uses native memory, which lets the OS do I/O without an extra copy. A direct buffer's memory is freed only after the GC finds its small heap object unreachable and its Cleaner runs, which can be much later, and the total is limited by MaxDirectMemorySize, by default the maximum heap size, with OutOfMemoryError: Direct buffer memory when it is exceeded. Libraries such as Netty pool and release direct buffers explicitly instead of relying on the GC.

What to say in the interviewAbout 80 seconds aloud

Open with

A heap ByteBuffer, from allocate, is backed by a normal byte array on the Java heap. A direct ByteBuffer, from allocateDirect, is a small object on the heap that points to a block of native memory outside the heap.

Then, if they want more

The reason to use direct buffers is I/O: the operating system needs data at a stable native address, so with a heap buffer the JDK first copies the bytes into a temporary direct buffer, while a direct buffer can be read or written by the OS in place. The catch is freeing.

There is no public free method; the JDK registers a Cleaner, and the native memory is released only after the ByteBuffer object becomes unreachable, a GC actually notices it, and the Cleaner runs. If the heap is quiet, that can be much later, so native memory can grow while the heap looks fine.

The total is capped by MaxDirectMemorySize, which by default is about the maximum heap size, and when an allocation would exceed it the JDK calls System.gc, waits for cleaners, and then throws OutOfMemoryError Direct buffer memory. That is also why DisableExplicitGC is risky with direct buffers.

Libraries like Netty avoid all this by pooling direct memory and releasing buffers explicitly with reference counting.

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 the difference between a heap ByteBuffer and a direct ByteBuffer in Java NIO?...": https://scrivio-interview-library.netlify.app/java/memory-layout/48c159fabf/