tags:

views:

201

answers:

1

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?

+3  A: 

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.

jpavel