Netty4的NioEventLoopGroup继承结构很复杂,为了理解它如何工作,我画了一张类似UML的图。但是这张图也很巨大,所以我做了以下处理:
首先从EventExecutorGroup开始,EventExecutorGroup是NioEventLoopGroup最上层的接口,再往上就是Java的地盘了:
从上面的图可以看出3点:
想象一下,EventExecutorGroup就像一个BOSS,每当有活儿的时候,就派一个小弟(EventExecutor)去干:
AbstractEventExecutorGroup抽象类实现了ScheduledExecutorService接口,但大部分实现都只是调用next()拿到一个EventExecutor,然后调用EventExecutor的相应方法,例如submit()方法:
public abstract class AbstractEventExecutorGroup implements EventExecutorGroup { @Override public Future<?> submit(Runnable task) { return next().submit(task); } ... }
从类名来看,MultithreadEventExecutorGroup有并行(多线程)分配小弟去干活的能力,换句话说,每个小弟都工作在自己的线程中。从代码中也能看出这一点:
public abstract class MultithreadEventExecutorGroup extends AbstractEventExecutorGroup { private final EventExecutor[] children; private final AtomicInteger childIndex = new AtomicInteger(); private final AtomicInteger terminatedChildren = new AtomicInteger(); private final Promise<?> terminationFuture = new DefaultPromise(GlobalEventExecutor.INSTANCE); protected MultithreadEventExecutorGroup(int nThreads, ThreadFactory threadFactory, Object... args) { ... children = new SingleThreadEventExecutor[nThreads]; ... } ... }可以看出,MultithreadEventExecutorGroup的每一个小弟都是一个SingleThreadEventExecutor,而且小弟的数量在构造的时候就确定了,如下图所示:
从MultithreadEventExecutorGroup的next()方法可以看到,这个BOSS的小弟分配逻辑相当简单,无非就是轮流使唤:
@Override public EventExecutor next() { return children[Math.abs(childIndex.getAndIncrement() % children.length)]; }注:这里调用了Math.abs()方法以防止childIndex溢出
MultithreadEventLoopGroup类实现了EventLoopGroup接口和register()方法:
public abstract class MultithreadEventLoopGroup extends MultithreadEventExecutorGroup implements EventLoopGroup { ... @Override public ChannelFuture register(Channel channel) { return next().register(channel); } @Override public ChannelFuture register(Channel channel, ChannelPromise promise) { return next().register(channel, promise); } }
最后是NioEventLoopGroup,这个BOSS的每一个小弟都是一个NioEventLoop。下面是完整的继承层次结构图: