我们可以从官方文档中获取更加清晰的认识,总结如下:
-
Netty堆外内存回收算法是基于引用计数的;
-
如果一个发送组件(sending component)企图传递一个基于引用计数对象,通常发送组件不需要回收该对象,而是交给消费组件。
-
如果代码块组件(component)接收基于引用计数的内存对象,且不再使用,该组件应负责引用释放——引用计数会-1。如:
ChannelHandler
就是典型的引用对象接收组件。
官方提供了判断是否需要引用释放的案例:
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;
}
| 事件说明 | 什么对象应该释放? | 什么对象释放成功了? |
| — | — | — |
| 1.main()
createsbuf
| buf
→main()
| |
| 2.main()
callsa()
withbuf
| buf
→a()
| |
| 3.a()
returnsbuf
merely. | buf
→m