Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to garbage collect a direct buffer in Java

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.

like image 683
mglmnc Avatar asked Dec 06 '09 04:12

mglmnc


People also ask

How do I fix Java Lang OutOfMemoryError direct buffer memory?

OutOfMemoryError: Direct buffer memory is increasing JVM default memory limit. By default, JVM allows 64MB for direct buffer memory, you can increase it by using JVM option -XX:MaxDirectMemorySize=512m. That's all on How to fix java. lang.

What is a direct buffer Java?

A direct buffer is a chunk of native memory shared with Java from which you can perform a direct read. An instance of DirectByteBuffer can be created using the ByteBuffer. allocateDirect() factory method.

What is direct memory buffer?

The direct buffer memory is the OS' native memory, which is used by the JVM process, not in the JVM heap. It is used by Java NIO to quickly write data to network or disk; no need to copy between JVM heap and native memory.

How can I get free ByteBuffer?

As the documentation of the BufferUtils in LWJGL also say: There is no way to explicitly free a ByteBuffer . The ByteBuffer objects that are allocated with the standard mechanism (namely, by directly or indirectly calling ByteBuffer#allocateDirect ) are subject to GC, and will be cleaned up eventually.


1 Answers

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.

like image 133
Stephen C Avatar answered Sep 18 '22 15:09

Stephen C