• Post Reply Bookmark Topic Watch Topic
  • New Topic

NIO Direct Buffers

 
Spencer Lee
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please correct me if I'm wrong, but I understand that direct buffers may potentially lie outside of the garbage collected heap.

Does that mean that creating direct buffers leaves your program susceptible to memory leaks? Is the nio developer responsbile for freeing this memory? And if so, how is this memory freed.

I can't seem to find any information on it on the web or in any books...
 
Joe Ess
Bartender
Posts: 9362
11
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I haven't used JNI but I'm pretty certain that if you allocate memory for use as a direct buffer, let's say in a C DLL through JNI, it is your responsability to free that memory when you are finished. You would need to provide some facility in your java-jni interface to invoke the C free() method. This does not make direct buffers any more succeptable to memory leaks than any other code. With power comes responsability.
 
Vlado Zajac
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There seems to be no method to do it from code directly. So NIO probably uses finalization or java.lang.ref to call native deallocation before the direct buffer is garbage collected. So the memory is in fact cleaned by GC but not in the same way as java objects.

JDK source:
java.nio.DirectByteBuffer and java.nio.Bits sun.misc.Cleaner and sun.misc.Unsafe classes implement this, unfortunately sum.misc source and the native source is not included in JDK.
 
Spencer Lee
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good stuff.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Indeed you can test this yourself by creating a large direct buffer, then setting the reference to null and call System.gc(). Run with -verbose:gc to see detailed output. You should see the memory usage rise when the buffer is created, and fall when GC runs after the reference was set to null. You can also look at the overall memory usage of the process using Task Manager or the unix "top" command. It looks to me like direct buffers clean up after themselves just fine. I suppose it's always possible that some implementations are buggy. But I wouldn't worry about it unless you find specific evidence that there's a leak of some sort on your system.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!