Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Java GC Does Direct Byte Buffer Clean Up, Because IBM Docs says, It Does.

I assumed, I understood how Bytebuffer and DirectByteBuffer differs until i read a artical on IBM documentation, metioning :

"Direct ByteBuffer objects clean up their native buffers automatically but can only do so as part of Java heap GC"

https://www.ibm.com/developerworks/library/j-nativememory-linux/

Now I am not able to understand this line, as it says DirectByteBuffer does cleaning as part of Java heap GC.

IFAIK, Java Heap GC only do clean up in java heap(where DirectByteBuffer is not allocated). It(GC) is no aware of native memory(where DirectByteBuffer is allocated).

Please help me understand this line, or if there is gap in my understanding

like image 538
Ankush G Avatar asked Oct 19 '16 04:10

Ankush G


People also ask

What is direct byte buffer in 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.

How do I clear a byte buffer?

The clear() method of java. nio. ByteBuffer Class is used to clear this buffer. The position is set to zero, the limit is set to the capacity, and the mark is discarded.

What is GC cycle?

A GC cycle is a repeatable process that involves a set of GC operations. These operations process all or parts of the Java heap. When operating on the whole of the Java heap, the cycle is referred to as a global GC cycle; When operating on part of the heap, the cycle is referred to as a partial GC cycle.


1 Answers

When you create an instance of java.nio.DirectByteBuffer you, essentially, have 2 parts:

  • Usual java object of type java.nio.DirectByteBuffer, which is allocated on the heap
  • The actual byte buffer that you wanted, which is allocated by the constructor of the aforementioned java object off the heap

In addition, the constructor of java.nio.DirectByteBuffer registers a runnable of type java.nio.DirectByteBuffer.Deallocator, which is a private static class. This runnable is executed when this instance of java.nio.DirectByteBuffer is cleaned up by the GC. And it is the task of this Deallocator to release the native byte buffer. RTFS! :)

like image 147
Nikem Avatar answered Oct 31 '22 20:10

Nikem