在DefaultChannelPipeline中使用双向链表实现addFirst和addLast逻辑
final class DefaultChannelPipeline implements ChannelPipeline { static final InternalLogger logger = InternalLoggerFactory.getInstance(DefaultChannelPipeline.class); @SuppressWarnings("unchecked") private static final WeakHashMap<Class<?>, String>[] nameCaches = new WeakHashMap[Runtime.getRuntime().availableProcessors()]; static { for (int i = 0; i < nameCaches.length; i ++) { nameCaches[i] = new WeakHashMap<Class<?>, String>(); } } final AbstractChannel channel; final AbstractChannelHandlerContext head; final AbstractChannelHandlerContext tail; private final Map<String, AbstractChannelHandlerContext> name2ctx = new HashMap<String, AbstractChannelHandlerContext>(4);
。。。。
}
可以看到AbstractChannelHandlerContext head和tail
进入看AbstractChannelHandlerContext :
abstract class AbstractChannelHandlerContext extends DefaultAttributeMap implements ChannelHandlerContext { volatile AbstractChannelHandlerContext next; volatile AbstractChannelHandlerContext prev; private final boolean inbound; private final boolean outbound; private final AbstractChannel channel; private final DefaultChannelPipeline pipeline; private final String name;
。。。。}
可以看到是双向链表结构,并有ChannelHandler的类型标示:boolean inbound, outbound
具体看addFirst和addLast方法源码:
在addFirst中最终调用了addFirst0方法:
private void addFirst0(String name, AbstractChannelHandlerContext newCtx) { checkMultiplicity(newCtx); AbstractChannelHandlerContext nextCtx = head.next; newCtx.prev = head; newCtx.next = nextCtx; head.next = newCtx; nextCtx.prev = newCtx; name2ctx.put(name, newCtx); callHandlerAdded(newCtx); }在addLast中最终调用了addLast0方法:
private void addLast0(final String name, AbstractChannelHandlerContext newCtx) { checkMultiplicity(newCtx); AbstractChannelHandlerContext prev = tail.prev; newCtx.prev = prev; newCtx.next = tail; prev.next = newCtx; tail.prev = newCtx; name2ctx.put(name, newCtx); callHandlerAdded(newCtx); }