简体   繁体   中英

Netty 4.0 ByteBuf retain() use

I'm trying understand decode aTrack protocol based on https://github.com/traccar/traccar implementation, they use Netty for their platform implementation, but I don't underestand which is the use of the retain method of ByteBuf's object. They used it in this method:

protected Object decode(
        Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

    ByteBuf buf = (ByteBuf) msg;

    if (buf.getUnsignedShort(buf.readerIndex()) == 0xfe02) {
        if (channel != null) {
            channel.writeAndFlush(new NetworkMessage(buf.retain(), remoteAddress)); // keep-alive message
        }
        return null;
    } else if (buf.getByte(buf.readerIndex()) == '$') {
        return decodeInfo(channel, remoteAddress, buf.toString(StandardCharsets.US_ASCII).trim());
    } else if (buf.getByte(buf.readerIndex() + 2) == ',') {
        return decodeText(channel, remoteAddress, buf.toString(StandardCharsets.US_ASCII).trim());
    } else {
        return decodeBinary(channel, remoteAddress, buf);
    }
}

Someone could explain me how works ByteBuf retain() method?

thanks.

From the Netty in action book:

In the case of encoders and decoders,once a message has been encoded or decoded, it will automatically be released by a call to ReferenceCountUtil.release(message) . If you need to keep a reference for later use you can call ReferenceCountUtil.retain(message) . This increments the reference count, preventing the message from being released.

As a further note on what reference counting is, this will be of help:

Reference counting is a technique for optimizing memory use and performance by releasing the resources held by an object when it is no longer referenced by other objects. A ReferenceCounted implementation instance will normally start out with an active reference count of 1. As long as the reference count is greater than 0, the object is guaranteed not to be released. When the number of active references decreases to 0, the instance will be released. Note that an object that has been released should no longer be available for use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM