学习netty源码知识点整理,理解的地方注释,不理解的地方依然不理解。
创建工作线程:
EventLoopGroup workerGroup=new NioEventLoopGroup()
new NioEventLoopGroup()最底层源码MultithreadEventExecutorGroup
//nThreads如果不传默认是0 如果是0的话 就获取CPU核数的两倍
//executor默认为null
//chooserFactory事件执行策略工厂
//args包含:selectorProvider用来创建ServerSocketChannel
//args包含:SelectStrategyFactory默认选择策略工厂
//args包含:RejectedExecutionHandler丢弃任务并抛出RejectedExecutionException异常
protected MultithreadEventExecutorGroup(int nThreads, Executor executor,
EventExecutorChooserFactory chooserFactory, Object... args) {
if (nThreads <= 0) {
throw new IllegalArgumentException(String.format("nThreads: %d (expected: > 0)", nThreads));
}
if (executor == null) {
//DefaultThreadFactory()=线程工厂 专门创建线程的
//最终创建的是DefaultThreadFactory,实现自jdk的ThreadFactory接口
//ThreadPerTaskExecutor,实现Executor接口,进一步封装,调用execute就自动创建线程
executor = new ThreadPerTaskExecutor(newDefaultThreadFactory());
}
children = new EventExecutor[nThreads];
for (int i = 0; i < nThreads; i ++) {
//出现异常标识
boolean success = false;
try {
//创建nThreads个NioEventLoop保存到children数组中
children[i] = newChild(executor, args);
success = true;
} catch (Exception e) {
throw new IllegalStateException("failed to create a child event loop", e);
} finally {
//出现异常处理
if (!success) {
for (int j = 0; j < i; j ++) {
children[j].shutdownGracefully();
}
for (int j = 0; j < i; j ++) {
EventExecutor e = children[j];
try {
while (!e.isTerminated()) {
e.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS);
}
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
break;
}
}
}
}
}
// children是NioEventLoop() 的对象数组
// children偶数=PowerOfTwoEventExecutorChooser,奇数=GenericEventExecutorChooser
// 这理解是,后面选取NioEventLoop做了封装,里面有与运算,选取更快。
// 一个NioEventLoop对应一条线程,NioEventLoop内部用来管理selector选择器
chooser = chooserFactory.newChooser(children);
final FutureListener<Object> terminationListener = new FutureListener<Object>() {
@Override
public void operationComplete(Future<Object> future) throws Exception {
if (terminatedChildren.incrementAndGet() == children.length) {
terminationFuture.setSuccess(null);
}
}
};
for (EventExecutor e: children) {
e.terminationFuture().addListener(terminationListener);
}
//复制一份只读的children
Set<EventExecutor> childrenSet = new LinkedHashSet<EventExecutor>(children.length);
Collections.addAll(childrenSet, children);
readonlyChildren = Collections.unmodifiableSet(childrenSet);
}