2

I have some doubts about the reference counting bytebuf in Netty 5(or 4). I find that nothing happen when I do not release a bytebuf when it goes out of life cycle, it seems that the memory used by bytebuf can be GCed properly.

In this link http://netty.io/wiki/reference-counted-objects.html , it say that setting JVM option '-Dio.netty.leakDetectionLevel=advanced' or call ResourceLeakDetector.setLevel() can detect resource leak, but I can not reproduce it with the code below.

public class App {
    public static ByteBuf a(ByteBuf input) {
        input.writeByte(42);
        return input;
    }

    public static ByteBuf b(ByteBuf input) {
        try {
            ByteBuf output;
            output = input.alloc().directBuffer(input.readableBytes() + 1);
            output.writeBytes(input);
            output.writeByte(42);
            return output;
        } finally {
            // input.release();
        }
    }

    public static void c(ByteBuf input) {
        //System.out.println(input);
        // input.release();
    }

    static class Task implements Runnable {
        ByteBuf bbBuf;

        public Task(ByteBuf buf) {
            bbBuf = buf;
        }

        public void run() {
            c(b(a(bbBuf)));
        }
    }

    public static void main(String[] args) {
        ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.PARANOID);     
        AbstractByteBufAllocator allocator = new PooledByteBufAllocator();

        ByteBuf buf = allocator.buffer(10, 100);

        // buf.release();
        new Thread(new Task(buf)).start();
        System.out.println(buf.refCnt());
        assert buf.refCnt() == 0;
    }
}

So what's the problem?

1 Answer 1

3

The resource leak detection mechanism in Netty relies on ReferenceQueue and PhantomReference. The garbage collector is not very deterministic about when it notifies the ReferenceQueue when an object (ByteBuf in our case) becomes unreachable. If the VM terminates too early or garbage is not collected soon enough, the resource leak detector cannot tell if there was a leak or not, because the garbage collector didn't tell us anything.

Practically, this is not a concern, because a Netty application usually runs for a much longer period in reality and you'll get notified eventually. Just run an application for about 30 seconds and let it do some busy job. You should definitely see the leak error message.

1
  • Thank you for your answer. I doubt that can I just don't release the bytebuf and only rely on the gc to collect the memory ? If I do that way the pooled bytebuf just lost its advantage and it does not affect the unpooled bytebuf.
    – Jun Wang
    Mar 4, 2015 at 6:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.