根据自己的理解来解答这个问题,有理解错误的地方还望多多指点。
首先说下答案吧,答案是否定的。
@sharable注释的channelHandler类只是说明该类的实现应该是线程安全的,且一个实例可以被添加到多个pipeline中, netty框架底层并没有根据该标识将channelHandler类声明为是单例模式的。
每个连接都有一个责任链,但责任链里的channelHandler对象是可以共享的,要看在实现initChannel时addLast函数里的对象是每次都new一个新的对象,还是共享的同一个对象。如下两个例子:
//生成责任链的工具对象
public class ThriftServerInitializer extends ChannelInitializer<SocketChannel> {
private ThriftEncoder thriftEncoder = new ThriftEncoder();
private ThriftDecoder thriftDecoder = new ThriftDecoder(4);
private ThriftServerHandler thriftServerHandler = new ThriftServerHandler();
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//这样所有的线程共享一个thriftServerHandler, thriftEncoder, thriftDecoder对象,减少了对象的创建次数, 否则的话一个连接会穿件一个责任对象链
//但当共享数据时要小心数据的同步