Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When and how are NIO direct buffers freed?

I have a C library that wants a temporary buffer for scratch space. I'm considering passing the address of a direct byte buffer to it.

  • Is the VM ever allowed to relocate the buffer before it is ultimately freed? The native library will be holding on to the pointer after the JNI frame goes away. My understanding is that JNI local object references cannot be cached because the VM may relocate them during GC. Does this apply to the buffer address?

  • I understand that the VM will free buffer memory if I allocate a buffer in Java and then let the buffer object go out of scope. If I create a new buffer in native code using NewDirectByteBuffer, whose responsibility is it to free the backing memory?

  • What happens if I create a new buffer in native code using NewDirectByteBuffer and an address already in use by a direct buffer? Will the memory be doubly-freed? Will the VM reference count the memory block and attempt to free it when the last buffer referencing it is garbage collected?

like image 984
gibbss Avatar asked Aug 07 '09 20:08

gibbss


People also ask

What are direct buffers?

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.

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.

What is Java buffer space?

A Java buffer pool memory space is a non-managed memory space that is situated separately from the garbage collector-managed memory.


1 Answers

Is the VM ever allowed to relocate the buffer before it is ultimately freed?

It won't relocate it, because the direct buffer is not part of the GC heap.

If I create a new buffer in native code using NewDirectByteBuffer, whose responsibility is it to free the backing memory?

It's your (native code) responsibility to free it. The JVM could not know what method was used to allocate that backing store (could be malloc'd, could be a static buffer, etc.)

What happens if I create a new buffer in native code using NewDirectByteBuffer and an address already in use by a direct buffer?

Given that the VM won't attempt to free the memory whose address is passed to NewDirectByteBuffer, nothing will happen if you pass the same address twice.

like image 117
jpavel Avatar answered Oct 14 '22 01:10

jpavel