该文所涉及的netty源码版本为4.1.6。
Netty的对象池Recycler是什么
Recycler是Netty中基于ThreadLocal的轻量化的对象池实现。既然是基于ThreadLocal,那么就可以将其理解为当前线程在通过对象池Recycler得到一个对象之后,在回收对象的时候,不需要将其销毁,而是放回到该线程的对象池中即可,在该线程下一次用到该对象的时候,不需要重新申请空间创建,而是直接重新从对象池中获取。
Recycler在netty中被如何使用
Recycler对象池在netty中最重要的使用,就在于netty的池化ByteBuf的场景下。首先,何为池化?以PooledDirectByteBuf举例,每一个PooledDirectByteBuf在应用线程中使用完毕之后,并不会被释放,而是等待被重新利用,类比线程池每个线程在执行完毕之后不会被立即释放,而是等待下一次执行的时候被重新利用。所谓的对象池也是如此,池化减少了ByteBuf创建和销毁的开销,也是netty高性能表现的基石之一。
private static final Recycler<PooledDirectByteBuf> RECYCLER = new Recycler<PooledDirectByteBuf>() {
@Override
protected PooledDirectByteBuf newObject(Handle<PooledDirectByteBuf> handle) {
return new PooledDirectByteBuf(handle, 0);
}
};
static PooledDirectByteBuf newInstance(int maxCapacity) {
PooledDirectByteBuf buf = RECYCLER.get();
buf.reuse(maxCapacity);
return buf;
}
PooledDirectByteBuf在其类加载的过程中,初始化了