我正在尝试理解基于aTrack实现的https://github.com/traccar/traccar协议解码,他们使用Netty作为平台实现,但我不理解,也就是使用ByteBuf的对象的retain方法。他们用这种方法:
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);
}
}某人可以解释我是如何工作的-- ByteBuf retain()方法?
谢谢。
发布于 2018-10-19 02:06:24
来自Netty行动的书:
在编码器和解码器的情况下,一旦消息被编码或解码,它将通过调用
ReferenceCountUtil.release(message)自动释放。如果您需要保留一个引用以供以后使用,可以调用ReferenceCountUtil.retain(message)。这会增加引用计数,从而防止消息被释放。
作为对参考计数是什么的进一步说明,这将有助于:
引用计数是一种优化内存使用和性能的技术,当对象不再被其他对象引用时,释放对象所持有的资源。
ReferenceCounted实现实例通常从活动引用计数1开始。只要引用计数大于0,则保证不会释放对象。当活动引用的数量减少到0时,实例将被释放。请注意,已释放的对象不应再供使用。
https://stackoverflow.com/questions/52883044
复制相似问题