How to garbage collect a direct buffer in Java

mglmnc picture mglmnc · Dec 6, 2009 · Viewed 42.3k times · Source

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.

Answer

Stephen C picture Stephen C · Dec 6, 2009

I suspect that somewhere your application has a reference to the ByteBuffer instance(s) and that is preventing it from being garbage collected.

The buffer memory for a direct ByteBuffer is allocated outside of the normal heap (so that the GC doesn't move it!!). However, the ByteBuffer API provides no method for explicitly disposing of / deallocating a buffer. So I assume that the garbage collector will do it ... once it determines that the ByteBuffer object is no longer referenced.