在netty中,ByteBuf是对字节的封装,对nio的ByteBuffer的增强,用于从socket缓冲区读取和写入数据的。
ByteBuf有基于堆内存和直接内存的,若是堆内存的,应用程序无需考虑什么时候去释放,因为GC会帮助做了;若是直接内存的,那么应用程序不用的时候,需要主动释放。
在netty中,是通过引用计数来实现的,接口形式表现为ReferenceCounted,ByteBuf会继承这个接口,每个ByteBuf对象都会有一个引用计数,当这个数值为0时,那么这个对象的方法便无法使用了,新创建的ByteBuf对象引用计数值为1,可通过对象retain和release对这个值进行增加和减少。所以应用程序中,将ByteBuf的引用计数减为0后,netty就会完成内存释放
如果ByteBuf的引用计数变为0了,调用该对象的相关方法都会抛出异常。
ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
System.out.println(buffer.refCnt());//初始值为1
buffer.release();//将引用计数-1
System.out.println(buffer.refCnt());//此时引用计数变为0
//buffer.writeBytes("hello world".getBytes());//这行代码会抛异常
buffer.retain();//将引用计数+1
System.out.println(buffer.refCnt());
buffer.writeByte(0);//可以对ByteBuf对象进行正常的操作
在应用程序中一般如何使用呢,我们看如下这个例子
new ServerBootstrap()
.group(new NioEventLoopGroup(), new NioEventLoopGroup())
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new LoggingHandler(LogLevel.DEBUG));
pipeline.addLast("inboundHandler1", new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf buf = (ByteBuf) msg;
buf.release();
log.info("inboundHandler1 referenceCount {}", buf.refCnt());
ctx.fireChannelRead(msg);
}
});
pipeline.addLast("outboundHandler1", new ChannelOutboundHandlerAdapter() {
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
ByteBuf buf = (ByteBuf) msg;
log.info("outboundHandler1 referenceCount {}", buf.refCnt());
super.write(ctx, msg, promise);
}
});
pipeline.addLast("inboundHandler2", new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf buf = (ByteBuf) msg;
log.info("inboundHandler2 referenceCount {}", buf.refCnt());
byte readByte = buf.readByte();
System.out.println(readByte);
ctx.writeAndFlush("hello world");
}
});
pipeline.addLast("outboundHandler2", new ChannelOutboundHandlerAdapter() {
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
ByteBuf buf = (ByteBuf) msg;
log.info("outboundHandler2 referenceCount {}", buf.refCnt());
super.write(ctx, msg, promise);
}
});
}
})
.bind(8899);
在这个例子中,创建了两个入站处理器和两个出站处理器。在inboundHandler1中接收到msg后,调用release方法,将其引用计数变为0,然后就传递给下一个inboundHandler,这样在inboundHandler2中要使用这个byteBuf对象的方法时就会抛异常。
因此,若是ByteBuf对象不会再传递给下一个handler了,才可以release,或者是每个handler不对引用计数做变化,每个方法调用后将其传递给下一个handler,这样pipeline的TailContext最终也会帮助我们进行release
写入数据也一样,出站处理器尽量不对ByteBuf的引用计数做变化,只需一直往后传递即可,pipeline的HeadContext最终也会确保ByteBuf对象释放。若是HeadContext在接收到ByteBuf对象时,引用计数已经是0了,那么无法将数据传输出去。
//TailContext的channelRead方法逻辑
protected void onUnhandledInboundMessage(Object msg) {
try {
logger.debug(
"Discarded inbound message {} that reached at the tail of the pipeline. " +
"Please check your pipeline configuration.", msg);
} finally {
ReferenceCountUtil.release(msg);
}
}
//HeadContext的channelRead方法逻辑
public final void write(Object msg, ChannelPromise promise) {
assertEventLoop();
ChannelOutboundBuffer outboundBuffer = this.outboundBuffer;
if (outboundBuffer == null) {
// If the outboundBuffer is null we know the channel was closed and so
// need to fail the future right away. If it is not null the handling of the rest
// will be done in flush0()
// See https://github.com/netty/netty/issues/2362
safeSetFailure(promise, newClosedChannelException(initialCloseCause, "write(Object, ChannelPromise)"));
// release message now to prevent resource-leak
ReferenceCountUtil.release(msg);
return;
}
int size;
try {
msg = filterOutboundMessage(msg);
size = pipeline.estimatorHandle().size(msg);
if (size < 0) {
size = 0;
}
} catch (Throwable t) {
safeSetFailure(promise, t);
ReferenceCountUtil.release(msg);
return;
}
outboundBuffer.addMessage(msg, size, promise);
}
如果在一个handler中,对ByteBuf处理完了,并转换为其他对象传递给下一个handler,那么这个handler的方法中就可以将ByteBuf释放掉。
当然了,具体的情况要具体分析,总之一句话,确保在使用ByteBuf对象时,其引用计数值不能为0,不再使用ByteBuf时,引用计数要改为0
网友评论