Top 3 Direct Byte Buffer Leak Triggers

Common culprits include forgetting explicit deallocation, long-lived references preventing garbage collection, and the JDK's internal NIO thread-local buffer cache.

The top 3

  1. Cleaner vs. GC: Why Off-Heap Memory Lingers: Direct buffers rely on a `Cleaner` thread, not direct garbage collection, to asynchronously free native memory. This non-deterministic mechanism can delay deallocation, making memory appear to leak if the JVM heap has ample space, as GC cycles might not be triggered promptly.
  2. NIO's Secret Cache: Unbounded Native Memory Use: The JDK internally caches a single, maximum-sized temporary direct `ByteBuffer` per thread for NIO I/O operations, even when application code uses heap buffers. This unbounded cache can unexpectedly consume gigabytes of off-heap memory, a behavior mitigated by the `-Djdk.nio.maxCachedBufferSize` flag in JDK 9 and later.
  3. Persistent References: The Root of Unfreed Buffers: If Java heap objects maintain strong references to `DirectByteBuffer` instances, the JVM's garbage collector cannot reclaim these objects, thereby preventing the crucial `Cleaner` from releasing the associated native memory. Common scenarios include `ArrayList`s, static maps, or `ThreadLocal` variables retaining these references.

Sources

Open the full topic