GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||
GeezerVison is showing netty.io — Netty.docs: Reference counted objects
Skip navigation
Reference counted objects
Did you know this page is automatically generated from
a Github Wiki page?
You can improve it by yourself
here!
Since Netty version 4, the life cycle of certain objects are managed by their reference counts, so that Netty can return them (or their shared resources) to an object pool (or an object allocator) as soon as it is not used anymore. Garbage collection and reference queues do not provide efficient real-time guarantee of unreachability, while reference-counting provides an alternative mechanism at the cost of slight inconvenience.
The initial reference count of a reference-counted object is 1: ByteBuf buf = ctx.alloc().directBuffer(); assert buf.refCnt() == 1; When you release the reference-counted object, its reference count is decreased by 1. If the reference count reaches 0, the reference-counted object is deallocated or returned to the object pool it came from: assert buf.refCnt() == 1; // release() returns true only if the reference count becomes 0. boolean destroyed = buf.release(); assert destroyed; assert buf.refCnt() == 0; Attempting to access the reference-counted object, whose reference count is 0, will trigger an assert buf.refCnt() == 0; try { buf.writeLong(0xdeadbeef); throw new Error("should not reach here"); } catch (IllegalReferenceCountExeception e) { // Expected } A reference count can also be incremented via the ByteBuf buf = ctx.alloc().directBuffer(); assert buf.refCnt() == 1; buf.retain(); assert buf.refCnt() == 2; boolean destroyed = buf.release(); assert !destroyed; assert buf.refCnt() == 1; The general rule of thumb is that the party that accesses a reference-counted object last is also responsible for the destruction of that reference-counted object. Specifically:
Here is a simple example: public ByteBuf a(ByteBuf input) { input.writeByte(42); return input; } public ByteBuf b(ByteBuf input) { try { output = input.alloc().directBuffer(input.readableBytes() + 1); output.writeBytes(input); output.writeByte(42); return output; } finally { input.release(); } } public void c(ByteBuf input) { System.out.println(input); input.release(); } public void main() { ... ByteBuf buf = ...; // This will print buf to System.out and destroy it. c(b(a(buf))); assert buf.refCnt() == 0; }
ByteBuf parent = ctx.alloc().directBuffer(); ByteBuf derived = parent.duplicate(); // Creating a derived buffer does not increase the reference count. assert parent.refCnt() == 1; assert derived.refCnt() == 1; In contrast, Note that a parent buffer and its derived buffers share the same reference count, and the reference count does not increase when a derived buffer is created. Therefore, if you are going to pass a derived buffer to an other component of your application, you will have to call ByteBuf parent = ctx.alloc().directBuffer(512); parent.writeBytes(...); try { while (parent.isReadable(16)) { ByteBuf derived = parent.readSlice(16); derived.retain(); process(derived); } } finally { parent.release(); } ... public void process(ByteBuf buf) { ... buf.release(); } Sometimes, a A buffer holder shares the reference count of the buffer it contains, just like a derived buffer. When an event loop reads data into a public void channelRead(ChannelHandlerContext ctx, Object msg) { ByteBuf buf = (ByteBuf) msg; try { ... } finally { buf.release(); } } As explained in the 'Who destroys?' section of this document, if your handler passes the buffer (or any reference-counted object) to the next handler, you don't need to release it: public void channelRead(ChannelHandlerContext ctx, Object msg) { ByteBuf buf = (ByteBuf) msg; ... ctx.fireChannelRead(buf); } Note that // Assuming your handler is placed next to `HttpRequestDecoder` public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; ... } if (msg instanceof HttpContent) { HttpContent content = (HttpContent) msg; try { ... } finally { content.release(); } } } If you are in doubt or you want to simplify releasing the messages, you can use public void channelRead(ChannelHandlerContext ctx, Object msg) { try { ... } finally { ReferenceCountUtil.release(msg); } } Alternatively, you could consider extending Unlike inbound messages, outbound messages are created by your application, and it is the responsibility of Netty to release these after writing them out to the wire. However, the handlers that intercept your write requests should make sure to release any intermediary objects properly. (e.g. encoders) // Simple-pass through public void write(ChannelHandlerContext ctx, Object message, ChannelPromise promise) { System.err.println("Writing: " + message); ctx.write(message, promise); } // Transformation public void write(ChannelHandlerContext ctx, Object message, ChannelPromise promise) { if (message instanceof HttpContent) { // Transform HttpContent to ByteBuf. HttpContent content = (HttpContent) message; try { ByteBuf transformed = ctx.alloc().buffer(); .... ctx.write(transformed, promise); } finally { content.release(); } } else { // Pass non-HttpContent through. ctx.write(message, promise); } } The disadvantage of reference counting is that it is easy to leak the reference-counted objects. Because the JVM is not aware of the reference counting Netty implements, it will automatically garbage collect them once they become unreachable, even if their reference counts are not zero. An object cannot be resurrected once garbage collected, and thus cannot be returned to the pool it came from and thus will produce a memory leak. Fortunately, despite the difficulty of finding leaks, Netty will by default sample about 1% of buffer allocations to check if there is a leak in your application. In case of leak, you will find the following log message:
Relaunch your application with the JVM option mentioned above and you will see the recent locations of your application where the leaked buffer was accessed. The following output shows a leak from our unit test ( If you use Netty 5 or above, an additional information is provided to help you find which handler handled the leaked buffer lastly. The following example shows that the leaked buffer was handled by the handler whose name is There are currently 4 levels of leak detection:
You can specify the leak detection level as a JVM option NOTE: This property used to be called
It is very easy to forget to release a buffer or a message in a unit test. It will generate a leak warning, but it does not necessarily mean that your application has a leak. Instead of wrapping your unit tests with import static io.netty.util.ReferenceCountUtil.*; @Test public void testSomething() throws Exception { // ReferenceCountUtil.releaseLater() will keep the reference of buf, // and then release it when the test thread is terminated. ByteBuf buf = releaseLater(Unpooled.directBuffer(512)); ... } External Links: Why do we need to manually handle reference counting for Netty ByteBuf if JVM GC is still in place? Buffer ownership in Netty 4: How is buffer life-cycle managed?
Last retrieved on 16-Nov-2026
| ||||||||||||||||||||||||
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |