Are Java DirectByteBuffer wrappers garbage collected?

Viewed 7632

I understand that when a directbytebuffer is allocated, its not subject to garbage collection, but what I'm wondering is if the wrapping object is garbage collected.

For example, if I allocated a new DirectByteBuffer dbb, and then duplicated(shallow copied) it using dbb.duplicate(), I'd have two wrappers around the same chunk of memory.

Are those wrappers subject to garbage collection? If I did

while(true){
    DirectByteBuffer dbb2 = dbb.duplicate();
} 

Would I eventually OOM myself?

5 Answers

Both the Java object and the native memory are freed at the same time by the garbage collector.

However, note that because the garbage collector doesn’t work well at cleaning up direct buffers, it’s best to allocate and reuse long-lived direct buffers instead of creating and abandoning new ones.

Related