【问题标题】:Netty 4/5 does not actually detect resource leak of bytebuf?Netty 4/5 实际上并没有检测到 bytebuf 的资源泄漏?
【发布时间】:2015-03-04 11:12:38
【问题描述】:

我对 Netty 5(或 4)中的引用计数 bytebuf 有一些疑问。我发现当一个bytebuf超出生命周期时我不释放它什么都没有发生,看来bytebuf使用的内存可以被正确GCed。

在此链接 http://netty.io/wiki/reference-counted-objects.html 中,它说设置 JVM 选项 '-Dio.netty.leakDetectionLevel=advanced' 或调用 ResourceLeakDetector.setLevel() 可以检测资源泄漏,但我无法使用下面的代码重现它。

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;
    }
}

那么问题出在哪里?

【问题讨论】:

    标签: netty


    【解决方案1】:

    Netty 中的资源泄漏检测机制依赖于ReferenceQueuePhantomReference。当一个对象(在我们的例子中是ByteBuf)变得无法访问时,垃圾收集器何时通知ReferenceQueue并不是很确定。如果 VM 过早终止或垃圾没有及时收集,资源泄漏检测器无法判断是否存在泄漏,因为垃圾收集器没有告诉我们任何信息。

    实际上,这不是问题,因为 Netty 应用程序在现实中通常会运行更长的时间,最终您会收到通知。只需运行一个应用程序大约 30 秒,让它完成一些繁忙的工作。您肯定会看到泄漏错误消息。

    【讨论】:

    • 感谢您的回答。我怀疑我可以不释放 bytebuf 而只依靠 gc 来收集内存吗?如果我这样做,池化的 bytebuf 就失去了优势,并且不会影响非池化的 bytebuf。
    猜你喜欢
    • 2016-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多