问题描述
我对Netty 5(或4)中的引用计数bytebuf有一些疑问.我发现当我不释放字节缓冲区超过生命周期时,什么也没发生,看来字节缓冲区所使用的内存可以被适当地GC.
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.
在此链接中 http://netty.io/wiki/reference-counted-objects .html ,它说设置JVM选项'-Dio.netty.leakDetectionLevel = advanced'或调用ResourceLeakDetector.setLevel()可以检测到资源泄漏,但是我无法使用下面的代码来重现它.
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;
}
}
那是什么问题?
推荐答案
Netty中的资源泄漏检测机制依赖于ReferenceQueue
和PhantomReference
.当对象(在本例中为ByteBuf
)变得不可访问时,垃圾收集器何时通知ReferenceQueue
并不确定.如果VM终止得太早或没有足够快地收集垃圾,则资源泄漏检测器将无法判断是否存在泄漏,因为垃圾收集器没有告诉我们任何事情.
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.
实际上,这不是一个问题,因为Netty应用程序实际上通常运行更长的时间,最终您会收到通知.只需运行一个应用程序大约30秒钟,然后让它完成一些繁琐的工作即可.您肯定应该看到泄漏错误消息.
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 4/5实际上没有检测到bytebuf的资源泄漏吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!