Video in progress

What is the difference between ByteBuffer.allocate() and ByteBuffer.allocateDirect(), and when do you pick which?

allocate creates a buffer over a byte[] on the regular Java heap, while allocateDirect uses native memory outside the heap. With a direct buffer the OS IO needs no extra copy, but it is more expensive to create and the GC cleans it up late.

📖 Answer

When you write a heap buffer to a channel, the JVM internally copies the data into a temporary direct buffer, because the GC may move the array on the heap in the middle of the IO. A direct buffer skips that copy.

When to use direct:

  • long-lived, reused IO buffers, for example Netty's pools;
  • large network or file IO.

When to use heap:

  • short-lived, small buffers;
  • you process the data a lot in Java code (array() only works on a heap buffer).

Problems with direct memory on prod:

  • it is not part of -Xmx; it is capped separately by -XX:MaxDirectMemorySize. In a container, if you set the heap to 75% and don't account for direct memory: OOMKilled;
  • the error message is OutOfMemoryError: Direct buffer memory;
  • creating a new direct buffer on every request is a classic antipattern: slow, and the memory isn't freed until the GC runs.

To monitor: jcmd <pid> VM.native_memory summary (if NMT is on) or the BufferPoolMXBean metrics, which Micrometer exposes as jvm.buffer.memory.used.