Skip to main content

How do you use NewDirectByteBuffer?

3 replies [Last post]
swpalmer
Offline
Joined: 2003-06-10

When you allocate a DirectByteBuffer from the Java side, I assume the memory will be freed by the VM via a finalizer on the Java DirectByteBuffer object.

How is this supposed to work when using the JNI method NewDirectByteBuffer from native code to create the DirectByteBuffer object? What happens when the DirectByteBuffer object is collected? How do we handle freeing the memory block on the C heap?

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
briand
Offline
Joined: 2005-07-11

If the native resource is just block of memory from the C-Heap, consider creating the buffer from Java using ByteBuffer.allocateDirect() and passing the buffer to your native code. That way, you automatically get all the JDK infrastructure for handling the release of the resource.

If this won't work for you, then you will need to handle this yourself. The constructor called by NewDirectByteBuffer does not create the PhantomReference object used to guarantee release of the native resource. You could use finalizers, but you'd be better off using a PhantomReference.

Brian

swpalmer
Offline
Joined: 2003-06-10

Thanks Brian. Do you know of an example that uses a PhantomReference in the way you describe? I'll have to read over the docs on PhantomReference anyway, but I think an example will help. I remember reading about PhantomReferences a couple years ago but I've never had the need to use them... until now.

I'm basically looking at options for wrapping a native API that gives me a buffer of data that I would like to access from Java without making a copy. I have a version working that does the copy. The data is attached to a Win32 COM object so it is managed via the COM reference counting mechansim.

Scott

briand
Offline
Joined: 2005-07-11

You could check the Mustang sources at java.net, but you shouldn't follow those examples directly as they use a sun.misc class for implementation that you don't really want to be dependent upon. What's missing from that example is a application specific ReferenceQueue for processing the discovered references. For more information, see the following url:

http://java.sun.com/developer/technicalArticles/ALT/RefObj/

An internet search for "PhantomReference example" should turn up plenty of examples.

Brian