NioEventLoopGroup构造过程(Netty源码分析)
文章目录
概念:
NioEventLoopGroup: 事件循环组(EventLoop组)
NioEventLoop: 事件循环对象(一个线程在不断执行任务)
核心构造函数
// 多线程事件处理执行组
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) {
// 构造线程执行器
// 这个是直接new一个线程执行?
executor = new ThreadPerTaskExecutor(newDefaultThreadFactory());
}
// new一个数组
children = new EventExecutor[nThreads];
for (int i = 0; i < nThreads; i ++) {
boolean success = false;
try {
// 创建NioEventLoop(事件循环对象)
children[i] = newChild(executor, args);
success = true;
} catch (Exception e) {
// TODO: Think about if this is a good exception type
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) {
// Let the caller handle the interruption.
Thread.currentThread().interrupt();
break;
}
}
}
}
}
// 构造一个Loop选择器
// 事件执行器选择工厂
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);
}
构造EventLoop
protected EventLoop newChild(Executor executor, Object... args) throws Exception {
// 队列工厂
EventLoopTaskQueueFactory queueFactory = args.length == 4 ? (EventLoopTaskQueueFactory) args[3] : null;
// 构造NioEventLoop
return new NioEventLoop(this, executor, (SelectorProvider) args[0],
((SelectStrategyFactory) args[1]).newSelectStrategy(), (RejectedExecutionHandler) args[2], queueFactory);
}
总结:
主要是构造NioEventLoopGroup和NioEventLoop的过程
NioEventLoopGroup: 构造NioEventLoop
NioEventLoop: 绑定选择器,赋值执行器,队列等属性
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论