Reputation: 154
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);
}
}
thanks.
Upvotes: 0
Views: 2563
Reputation: 7983
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 callReferenceCountUtil.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.
Upvotes: 2