According to the book Netty in Action v10
, reference counting
is used to handle the pooling of ByteBuf
. But JVM is not aware of the netty reference counting, so JVM can still GC the ByteBuf
. If so, why do we still need to care about the reference counting and manually call release()
method?
I quoted some from the book < Netty in Action v10 > to add some context.
One of the tradeoffs of reference-counting is that the user have to be carefully when consume messages. While the JVM will still be able to GC such a message (as it is not aware of the reference-counting) this message will not be put back in the pool from which it may be obtained before. Thus chances are good that you will run out of resources at one point if you do not carefully release these messages.
And some related threads: Buffer ownership in Netty 4: How is buffer life-cycle managed?
https://blog.twitter.com/2013/netty-4-at-twitter-reduced-gc-overhead
ADD 1
(Below is some more of my understanding.)
A ByteBuf
can be categorized from 2 perspectives:
1. Pooled or Unpooled
2. Heap-based or Direct
So there can be 4 combinations:
(a) Pooled Heap-based
(b) Pooled Direct
(c) Unpooled Heap-based
(d) Unpooled Direct
Only (a) and (c) are affected by JVM GC mechanism because they are heap-based.
In the above quotation from < Netty in Action v10 >, I think the message means a Java object, which is in (a) category.
One ultimate rule is, if a Java object is GCed, it's totally gone. So below is what I think Netty does:
For (a), Netty allocator MUST trick JVM GC into believing the object should never be GCed. And then use ref counting to move the object out of/back into the pool. This is another form of life cycle.
For (b), JVM GC is not involved as it is not JVM Heap-based. And Netty allocator need to use ref counting to move the object out of/back into the pool.
For (c), JVM GC takes full responsibility to control the life of object. Netty allocator just provide API for allocating object.
For (d), JVM GC is not involved. And no pooling is needed. So Netty allocator only needs provide API for allocating/releasing the object.