Video in progress
Where does "OutOfMemoryError: Direct buffer memory" come from, and how do you investigate it?
It is not about the heap. It means the limit for memory allocated off-heap with ByteBuffer.allocateDirect has run out. The usual causes are Netty, NIO channels or gRPC buffers that weren't released, or -XX:MaxDirectMemorySize being too small.
📖 Answer
Direct buffers are convenient for I/O: the OS writes data straight into them, with no extra copy. But their memory is not on the heap. Only the small DirectByteBuffer object lives on the heap, and the native memory is freed through a Cleaner when the GC collects that object.
This causes two problems:
- if the heap is lightly used, the GC runs rarely, the buffer objects aren't collected and the native memory isn't freed. When the limit is reached, the JDK tries calling
System.gc(), which is why-XX:+DisableExplicitGCis dangerous here; - Netty manages buffers by hand with its own pool: if you forget
release(), you get a real leak.
The limit is set with -XX:MaxDirectMemorySize, and by default it is roughly equal to -Xmx.
To check:
jcmd $PID VM.native_memory summary # the "Other" or "NIO" section
From inside the application, use BufferPoolMXBean:
for (var pool : ManagementFactory.getPlatformMXBeans(BufferPoolMXBean.class)) {
System.out.printf("%s: %d buffers, %d bytes%n",
pool.getName(), pool.getCount(), pool.getMemoryUsed());
}
Spring Boot Actuator exposes this as the jvm_buffer_memory_used_bytes metric. If you use Netty, run the tests with -Dio.netty.leakDetection.level=paranoid: it logs where a buffer that wasn't released was created.
Sign up to mark studied questions and save your progress.