关于线程池,池化和重用相对于简单地为每个任务都创建和销毁线程是一种进步,但它并不能消除由于上下文切换所带来的开销。下面我们来看看netty的线程模型,它是如何优化和简化多线程的操作。
netty常用时,配置NioEventLoopGroup,为每个channel绑定相应的EventLoop,EventLoop上绑定的Thread处理相应channel上的所有io操作和事件。
NioEventLoopGroup的构造方法具体逻辑实际上是在其超类MultithreadEventExecutorGroup上
protected MultithreadEventExecutorGroup(int nThreads, ThreadFactory threadFactory, Object... args) {
this.terminationFuture = new DefaultPromise(GlobalEventExecutor.INSTANCE);
if(nThreads <= 0) {
throw new IllegalArgumentException(String.format("nThreads: %d (expected: > 0)", new Object[]{Integer.valueOf(nThreads)}));
} else {
if(threadFactory == null) {
threadFactory = this.newDefaultThreadFactory();
}
this.children = new SingleThreadEventExecutor[nThreads];
int j;
for(int i = 0; i < nThreads; ++i) {
boolean success = false;
boolean var17 = false;
try {
var17 = true;
this.children[i] = this.newChild(threadFactory, args);
success = true;
var17 = false;
} catch (Exception var18) {
throw new IllegalStateException("failed to create a child event loop", var18);
} finally {
if(var17) {
if(!success) {
int j;
for(j = 0; j < i; ++j) {
this.children[j].shutdownGracefully();
}
for(j = 0; j < i; ++j) {
EventExecutor e = this.children[j];
try {
while(!e.isTerminated()) {
e.awaitTermination(2147483647L, TimeUnit.SECONDS);
}
} catch (InterruptedException var19) {
Thread.currentThread().interrupt();
break;
}
}
}
}
}
if(!success) {
for(j = 0; j < i; ++j) {
this.children[j].shutdownGracefully();
}
for(j = 0; j < i; ++j) {
EventExecutor e = this.children[j];
try {
while(!e.isTerminated()) {
e.awaitTermination(2147483647L, TimeUnit.SECONDS);
}
} catch (InterruptedException var21) {
Thread.currentThread().interrupt();
break;
}
}
}
}
FutureListener<Object> terminationListener = new FutureListener<Object>() {
public void operationComplete(Future<Object> future) throws Exception {
if(MultithreadEventExecutorGroup.this.terminatedChildren.incrementAndGet() == MultithreadEventExecutorGroup.this.children.length) {
MultithreadEventExecutorGroup.this.terminationFuture.setSuccess((Object)null);
}
}
};
EventExecutor[] arr$ = this.children;
j = arr$.length;
for(int i$ = 0; i$ < j; ++i$) {
EventExecutor e = arr$[i$];
e.terminationFuture().addListener(terminationListener);
}
}
}
在构造方法中,先保证nThread大于0,它就是Eve