Scrivio Interview library
ConceptIntermediate7 min read · updated 12 November 2026

What is the difference between a heap ByteBuffer and a direct ByteBuffer? When is each the better choice, and what operational problems can direct buffers cause?

A heap ByteBuffer is backed by an ordinary byte array in the Java heap, while a direct ByteBuffer uses native memory outside the heap. Direct buffers let the operating system read and write their memory directly during channel I/O, which saves a copy, but they are expensive to allocate and their memory is freed only when the small Java object that owns it is garbage collected. Their total size is capped by -XX:MaxDirectMemorySize, and running out gives OutOfMemoryError: Direct buffer memory, which is why frameworks such as Netty pool them.

Why this question is asked

Most of the time we never choose between heap and direct buffers; a framework chooses for us. But when a service fails with OutOfMemoryError: Direct buffer memory while its heap is half empty, or its container is killed for using more memory than the heap settings suggest, we need to understand what direct buffers are and how they are freed. Interviewers ask this to test our model of JVM memory beyond the heap and our ability to connect a design choice to operational behaviour. In this answer, we will recap the two kinds of buffer, see why direct buffers help I/O, look at what they cost, and then cover the failure modes and how frameworks avoid them.

1A Quick Recap of the Two Kinds of Buffer

ByteBuffer.allocate(n) creates a heap buffer. Its bytes live in a normal byte[] inside the Java heap, managed by the garbage collector like any other object; hasArray() returns true and array() gives us that array. ByteBuffer.allocateDirect(n) creates a direct buffer. Its bytes live in native memory, memory the JVM asks the operating system for outside the heap, and the Java object we hold is only a small handle with the address and size. hasArray() returns false.

Both kinds behave identically through the ByteBuffer API: put, get, flip, position and limit all work the same. The differences are where the memory lives, what that means for I/O, and how it is allocated and freed.

Heap and direct buffers compared
Heap ByteBufferDirect ByteBuffer
Created byByteBuffer.allocate(n)ByteBuffer.allocateDirect(n)
Memorybyte[] in the Java heapnative memory outside the heap
Channel I/OJDK copies via a temporary direct bufferOS uses the memory directly
Allocation costcheap, like any arrayexpensive: native allocation and zeroing
Freed whenarray is garbage collectedowning object is collected (Cleaner runs)
Limit-Xmx-XX:MaxDirectMemorySize

2Why Direct Buffers Save a Copy

When we call channel.write(buffer), the operating system needs the address of a block of memory that will not move while it works. Heap objects can move, because the garbage collector compacts the heap. So when we pass a heap buffer to a channel, the JDK first copies its bytes into a temporary direct buffer (it keeps a small per-thread cache of these), and the system call works on that. A direct buffer's memory never moves, so the JDK hands its address straight to the system call and skips the copy.

For a service that pushes large amounts of data through sockets or files, that copy is real work on every operation, and avoiding it saves CPU and memory bandwidth. For code that mostly fills and reads buffers from Java, the picture can reverse: accessing a heap buffer's array is as fast as any array, and creating many short-lived direct buffers is slow.

3What Direct Buffers Cost

Allocating a direct buffer means a native allocation plus zeroing the memory, and registering a Cleaner, a hook that frees the native memory later. That is much slower than creating a byte array, so allocating a new direct buffer for every request is a known anti-pattern.

Freeing is the bigger problem. The native memory is released only when the garbage collector finds that the small ByteBuffer object is unreachable and its Cleaner runs. That object is tiny, so it puts almost no pressure on the heap, and if it has been promoted to the old generation it may survive for a long time before a collection looks at it. Meanwhile the native memory it holds can be megabytes. A service can therefore accumulate a lot of native memory that is logically garbage but not yet freed.

Java
ByteBuffer heap = ByteBuffer.allocate(1024);
ByteBuffer direct = ByteBuffer.allocateDirect(1024);
System.out.println(heap.isDirect() + " " + heap.hasArray()); // false true
System.out.println(direct.isDirect() + " " + direct.hasArray()); // true false
// Anti-pattern: a new direct buffer per request
void handle(SocketChannel ch) throws IOException {
ByteBuffer buf = ByteBuffer.allocateDirect(64 * 1024); // slow, and freed only after a GC
ch.read(buf);
}

4The Operational Failure Modes

Total direct memory is capped by -XX:MaxDirectMemorySize. If we do not set it, the default is roughly the maximum heap size. When an allocation would go over the cap, the JDK first triggers a full garbage collection, hoping to run Cleaners and free memory, and waits briefly. If that does not free enough, allocateDirect throws OutOfMemoryError: Direct buffer memory. The heap itself may be fine at that moment, which confuses anyone who only watches heap graphs. The forced full GCs on that path can also cause pause spikes before the error appears, and running with -XX:+DisableExplicitGC can make this path behave worse, so check your version and flags.

In containers there is a second failure. Direct memory is outside the heap, so a JVM with -Xmx of 2 GB can use 2 GB of heap plus up to about 2 GB of direct memory, plus metaspace, thread stacks and other native memory. If the container limit was sized from the heap alone, the kernel's OOM killer ends the process with no Java error at all. When we size containers we must budget direct memory explicitly and usually set MaxDirectMemorySize to a known value.

5How Frameworks Avoid the Cost: Pooling

Netty, and most high-performance network libraries, solve both problems by allocating direct memory in large chunks once and then handing out pieces of it from a pool. A request borrows a buffer, uses it and releases it back to the pool, so there is no native allocation on the hot path and no dependence on the garbage collector to free memory. The price is manual lifecycle management: Netty's ByteBuf is reference counted, and a missing release() is a leak that Netty's leak detector can report. In our own code the practical rule is to allocate direct buffers rarely and reuse them, for example one per connection or per thread, and to use heap buffers for short-lived data handled mostly in Java.

6Follow-up questions

How would you monitor direct buffer usage in production?

The JVM exposes BufferPoolMXBean beans named direct and mapped, each with a count, total capacity and memory used. Spring Boot with Micrometer publishes them as jvm.buffer.count, jvm.buffer.memory.used and jvm.buffer.total.capacity tagged by pool, so we can graph and alert on them next to heap metrics. For a deeper look, Native Memory Tracking (-XX:NativeMemoryTracking=summary and jcmd <pid> VM.native_memory summary) breaks down all native memory, and Netty publishes its own pool metrics. We alert when direct memory approaches MaxDirectMemorySize and watch container memory against its limit.

Is a direct buffer always faster for file and socket I/O?

Not always. It removes one copy per channel operation, which matters for large or frequent transfers that are reused, but allocating a direct buffer per operation costs more than the copy it saves. For small or one-off transfers the JDK's internal temporary direct buffers already make heap buffers reasonably efficient. As with most performance choices, we measure with realistic sizes.

7Conclusion

In this answer, we saw that heap buffers live in a Java byte array while direct buffers live in native memory. Direct buffers save a copy during channel I/O because the operating system can use their memory directly, but they are expensive to allocate and are freed only when their owner is garbage collected. Their total is limited by -XX:MaxDirectMemorySize, exhausting it gives OutOfMemoryError: Direct buffer memory, and they count toward container memory, which is why frameworks like Netty pool them and why we monitor the direct buffer pool.

What to say in the interviewAbout 100 seconds aloud

Open with

A heap ByteBuffer, from allocate, is backed by a normal byte array in the Java heap. A direct one, from allocateDirect, uses native memory outside the heap and the Java object is just a handle to it.

Then, if they want more

The benefit of direct buffers is I/O: the operating system needs memory that does not move, and heap objects can be moved by the GC, so when I write a heap buffer to a channel the JDK first copies it into a temporary direct buffer.

With a direct buffer it passes the address straight to the system call and skips that copy. The costs are allocation, which is a native allocation plus zeroing and is much slower than creating an array, and freeing, which only happens when the small buffer object is garbage collected and its Cleaner runs.

Because the object is tiny, that can take a long time while megabytes of native memory sit unused. The total is capped by MaxDirectMemorySize, which defaults to about the heap size, and when it runs out we get OutOfMemoryError: Direct buffer memory even though the heap looks fine, often after some forced full GCs.

In containers it also counts toward the memory limit, so a pod can be OOM killed if we only sized it for the heap. So I use direct buffers for long-lived, reused I/O buffers, heap buffers for short-lived data, and in practice rely on Netty's pooled buffers. I monitor it with the BufferPool MXBeans, which Micrometer exposes as jvm.buffer metrics.

About this answer

Last updated
12 November 2026
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? When is each...": https://scrivio-interview-library.netlify.app/java/io-and-nio/57d61f5a59/