Netty 4 uses reference counting to manage the life cycle of ByteBuf
. When a pooled buffer is released, the underlying memory region is returned to the pool, so that the memory region is not garbage collected. When an unpooled buffer is released, the underlying memory region is deallocated explicitly, or set to null so that JVM cleans it up later. It is recommended to use a pooled buffer of course.
Reference counting has an advantage over garbage collection:
- It is possible to implement a buffer pool or allocator.
- It is possible to deallocate off-heap buffers on time.
We hoped to implement a buffer pool or deallocate off-heap buffers on time without reference counting, but there's no way to get notified as soon as an object becomes unreachable in JVM.