Netty中ByteBuf的回收机制ReferenceCounted

本文介绍Netty中的ByteBuf如何通过引用计数机制管理内存资源。当ByteBuf实例化时,其引用计数从1开始,通过retain()方法增加引用计数,release()方法减少引用计数。当引用计数降至0时,对象会被显式回收,进一步访问将导致访问违规。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Netty中ByteBuf采用引用计数的方式进行资源的回收,当ByteBuf中的引用计数值为0时,Netty则不允许应用程序采用任何的方式对这个资源进行访问。它通过实现ReferenceCounted维护引用计数。

package io.netty.util;

/**
 * A reference-counted object that requires explicit deallocation.
 * 一个需要显式进行资源回收的引用计数的对象
 * <p>
 * When a new {@link ReferenceCounted} is instantiated, it starts with the reference count of {@code 1}.
 * {@link #retain()} increases the reference count, and {@link #release()} decreases the reference count.
 * If the reference count is decreased to {@code 0}, the object will be deallocated explicitly, and accessing
 * the deallocated object will usually result in an access violation.
 * 当一个新的引用计数被实例化时,它的引用计数是从1开始的。通过retain()来增加引用计数,以及release()方法减少引用计数。
 * 当这个引用计数减少到0时,这个对象将会被显式的回收,并且访问这个被回收的对象通常会导致一个访问违背。
 * </p>
 * <p>
 * If an object that implements {@link ReferenceCounted} is a container of other objects that implement
 * {@link ReferenceCounted}, the contained objects will also be released via {@link #release()} when the container's
 * reference count becomes 0.
 * 如果一个实现了ReferenceCounted接口的对象是一个其他实现了ReferenceCounted对象的容器,
 * 当这个容器的引用计数变成0的话,那么这些被包含的对象也会通过通过调用release()方法被释放掉,
 * </p>
 */
public interface ReferenceCounted {
    /**
     * Returns the reference count of this object.  If {@code 0}, it means this object has been deallocated.
     * 返回这个对象的引用计数,当为0的时候,它以为着这个对象已经被回收了
     */
    int refCnt();

    /**
     * Increases the reference count by {@code 1}.
     * 增加引用计数,增加幅度为1
     */
    ReferenceCounted retain();

    /**
     * Increases the reference count by the specified {@code increment}.
     * 增加引用计数,增加幅度为特定的increment参数值。
     */
    ReferenceCounted retain(int increment);



    /**
     * Decreases the reference count by {@code 1} and deallocates this object if the reference count reaches at
     * {@code 0}.
     * 减少引用计数,减少1,如果引用计数达到0的话,则回收这个对象
     * @return {@code true} if and only if the reference count became {@code 0} and this object has been deallocated
     */
    boolean release();

    /**
     * Decreases the reference count by the specified {@code decrement} and deallocates this object if the reference
     * count reaches at {@code 0}.
     * 减少引用计数,减少指定的decrement值,如果引用计数达到0的话,则回收这个对象
     * @return {@code true} if and only if the reference count became {@code 0} and this object has been deallocated
     */
    boolean release(int decrement);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值