How to garbage collect a direct buffer in Java

Viewed 46412

I have a memory leak that I have isolated to incorrectly disposed direct byte buffers.

ByteBuffer buff = ByteBuffer.allocateDirect(7777777);

The GC collects the objects that harbor these buffers but does not dispose of the buffer itself. If I instantiate enough of the transient objects containing buffers, I get this encouraging message:

java.lang.OutOfMemoryError: Direct buffer memory

I have been searching up this problem and apparently

buff.clear();

and

System.gc();

do not work.

7 Answers

There are many caveats missing from the existing answers to this question, e.g. requirements when running under JDK 9+ for the module descriptor to contain requires jdk.unsupported, the inability to access MappedByteBuffer.cleaner() without workarounds under JDK 16+ due to the enforcement of strong encapsulation, the requirements if running with a SecurityManager under JDK 7-16, etc. I go over the full details here:

https://stackoverflow.com/a/54046774/3950982

Related