Netty 4/5 does not actually detect resource leak o

2019-05-25 06:31发布

问题:

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:

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.



标签: netty