Netty 4中的缓冲区所有权:如何管理缓冲区生命周期? [英] Buffer ownership in Netty 4: How is buffer life-cycle managed?

查看:161
本文介绍了Netty 4中的缓冲区所有权:如何管理缓冲区生命周期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试编写一个HTTP客户端以同时获取多个提要(最多1k),这也是学习Netty 4的练习.

I've been trying to write an HTTP client to fetch multiple feeds concurrently (up to 1k), also as an exercise to learn Netty 4.

我的问题是,是否有很好的解释说明新的ByteBuf基础结构如何工作?谁拥有"它们,如何共享它们(是吗?)? ChannelPipeline中的每个ChannelHandler是否都有自己的ByteBuf?

My question is, if there is a good explanation somewhere how the new ByteBuf infrastructure works? Who "owns" them, how are they shared (are they?) ? Does every ChannelHandler in a ChannelPipeline has it's own ByteBuf?

这是一个让我感到困惑的例子:

Here is an example that left me puzzled:

我将以下类的实例添加到HTTP客户端管道中:

I added an instance of the following class to a HTTP client pipeline:

public class MyFilter extends MessageToMessageDecoder<HttpObject> {

    @Override
    protected Object decode(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        // do some work, but leave msg unchanged
        BufUtil.retain(msg); // Why do I need to call BufUtil.retain(msg) ???
        return msg;
}

如果我没有在msg上调用BufUtil.retain,它似乎会得到GCd,并且会出现各种各样的虚假错误.

If I don't call BufUtil.retain on msg, it seems to get GCd and I get all sorts of spurious errors.

推荐答案

HttpContent扩展了ReferenceCounted,以跟踪其保存的缓冲区的生命周期.实例化ReferenceCounted时,其开始于1refCnt.如果在其上调用retain(),则会增加refCnt. refCntrelease()上减小,并且一旦refCnt变为0,基础资源(在本例中为ByteBuf)被破坏.

HttpContent extends ReferenceCounted to keep track of the life cycle of the buffer it holds. When a ReferenceCounted is instantiated, it starts its life with refCnt of 1. If you call retain() on it, refCnt is increased. refCnt is decreased on release(), and the underlying resource (ByteBuf in this case) is destroyed once refCnt becomes 0.

通常,处理程序不需要保留对其已完成处理的消息的引用,因为一旦处理完该消息后,该消息通常会被丢弃或转换为其他内容.因此,处理程序完成后,必须在消息上调用release()方法.这通常容易出错,并且很容易导致资源泄漏.

Usually, a handler does not need to keep a reference to the message it finished handling, because the message is usually thrown away or transformed into something else once handled. Therefore, release() method must be called on the message once your handler is done with it. This is often error-prone and will lead to resource leak very easily.

为避免很难跟踪的泄漏,请扩展SimpleChannelInboundHandler,一旦处理后,将自动对消息调用release().

To avoid the leak that is very hard to track down, extend SimpleChannelInboundHandler which calls release() automatically on the messages once they are handled.

有关Netty中引用计数的更多信息,请阅读此Wiki页面 .它还为您提供了有关如何利用Netty的缓冲区泄漏检测机制对缓冲区泄漏进行故障排除的详细信息.

For more information about reference counting in Netty, please read this wiki page. It also gives you the detailed information about how to troubleshooting the buffer leaks by making use of Netty's buffer leak detection mechanism.

这篇关于Netty 4中的缓冲区所有权:如何管理缓冲区生命周期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆