Are Java DirectByteBuffer wrappers garbage collected?

后端 未结 4 714
灰色年华
灰色年华 2020-12-08 05:52

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 collecte

4条回答
  •  天命终不由人
    2020-12-08 06:31

    A direct ByteBuffer object is just like any other object: it can be garbage-collected.

    The memory used by a direct buffer will be released when the ByteBuffer object is GC'd (this is not explicitly stated for ByteBuffer, but is implied by the documentation of MappedByteBuffer).

    Where things get interesting is when you've filled your virtual memory space with direct buffers, but still have lots of room in the heap. It turns out that (at least on the Sun JVM), running out of virtual space when allocating a direct buffer will trigger a GC of the Java heap. Which may collect unreferenced direct buffers and free their virtual memory commitment.

    If you're running on a 64-bit machine, you should use -XX:MaxDirectMemorySize, which puts an upper limit on the number of buffers that you can allocate (and also triggers GC when you hit that limit).

提交回复
热议问题