记一次netty ByteBuf内存泄漏

netty-server服务端在接收数据的时候会将数据转换为ByteBuf,然后对数据处理。今天程序跑了很久,突然发现日志打印内存泄漏,当时在想,这个程序功能很单一,为什么会内存泄漏呢,后来看代码,发现有ByteBuf,但还是很疑惑,我以为netty会自动回收,后来看了博客,有些人说业务中的ByteBuf需要我们自己去回收。

代码片段:
public void channelRead(ChannelHandlerContext ctx, Object msg){
ByteBuf buf = null;
try{
buf = (ByteBuf)msg;
//拿到数据

        byte[] barray = new byte[buf.readableBytes()];
        buf.getBytes(0,barray);
        String data = new String(barray);

}

日志:
[ioEventLoop-6-1] io.netty.util.ResourceLeakDetector : LEAK: ByteBuf.release() was not called before it’s garbage-collected. See http://netty.io/wiki/reference-counted-objects.html for more information.

解决办法:
buf.release();

猜你喜欢

转载自blog.csdn.net/qq_43504447/article/details/107583935