眾所周知,netty是一款性能非常出色的nio框架,作為dubbo等眾多優(yōu)秀項(xiàng)目底層的數(shù)據(jù)傳輸框架,研究吃透它,對(duì)于我們今后的開(kāi)發(fā)是絕對(duì)有益無(wú)害的,所以從今天開(kāi)始我們就研究netty。本次分析基于netty4,請(qǐng)諸位看官自行下載jar包及源碼。好了,我們今天說(shuō)一下netty的線程池。
我們經(jīng)常會(huì)看到netty的代碼中有下面這一句。
EventLoopGroup workerGroup = new NioEventLoopGroup();
簡(jiǎn)單的new了一個(gè)事件的處理組(也沒(méi)看官方怎么解釋這個(gè)概念的,自己定義了一下吧,勿噴)。但他里面所作的事情卻遠(yuǎn)不止看到的這么簡(jiǎn)單。這也是我們閱讀源碼的一個(gè)準(zhǔn)則,不要忽略每一個(gè)你認(rèn)為的不起眼的代碼,也許他的作用是舉足輕重的。他的具體實(shí)現(xiàn)
### io.netty.channel.nio.NioEventLoopGroup#NioEventLoopGroup()
/**
* Create a new instance using the default number of threads, the default {@link ThreadFactory} and
* the {@link SelectorProvider} which is returned by {@link SelectorProvider#provider()}.
*/
public NioEventLoopGroup() {
this(0);
}
### io.netty.channel.MultithreadEventLoopGroup#MultithreadEventLoopGroup(int, java.util.concurrent.Executor, java.lang.Object...)
/**
* @see MultithreadEventExecutorGroup#MultithreadEventExecutorGroup(int, Executor, Object...)
*/
protected MultithreadEventLoopGroup(int nThreads, Executor executor, Object... args) {
super(nThreads == 0 ? DEFAULT_EVENT_LOOP_THREADS : nThreads, executor, args);
}
### MultithreadEventLoopGroup.java:39
static {
DEFAULT_EVENT_LOOP_THREADS = Math.max(1, SystemPropertyUtil.getInt(
"io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2));
if (logger.isDebugEnabled()) {
logger.debug("-Dio.netty.eventLoopThreads: {}", DEFAULT_EVENT_LOOP_THREADS);
}
}
### 表示代碼出自的類及方法名,因?yàn)樗麄兊南嚓P(guān)性很大,所以我就放到同一個(gè)代碼塊中,防止思維跳躍太大,大家跟不上節(jié)奏。雖然現(xiàn)在初始化的時(shí)候設(shè)置了線程數(shù)為0,但是并不是最后的結(jié)果,經(jīng)過(guò)了諸多的構(gòu)造函數(shù)的調(diào)用及父類構(gòu)造函數(shù)的引用,在這里做了一個(gè)轉(zhuǎn)化,當(dāng)為0時(shí),會(huì)取DEFAULT_EVENT_LOOP_THREADS的值,而他的值,他取的是,如果設(shè)置io.netty.eventLoopThreads的值就取這個(gè)值,沒(méi)有設(shè)置的話,會(huì)取默認(rèn)值可用核數(shù)的兩倍,同1比較去一個(gè)最大的進(jìn)行賦值。最后我們到達(dá)了最好的構(gòu)造函數(shù)
### io.netty.util.concurrent.MultithreadEventExecutorGroup#MultithreadEventExecutorGroup(int, java.util.concurrent.Executor, io.netty.util.concurrent.EventExecutorChooserFactory, java.lang.Object...)
/**
* Create a new instance.
*
* @param nThreads the number of threads that will be used by this instance.
* @param executor the Executor to use, or {@code null} if the default should be used.
* @param chooserFactory the {@link EventExecutorChooserFactory} to use.
* @param args arguments which will passed to each {@link #newChild(Executor, Object...)} call
*/
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) { //如何executor為空,那么設(shè)置默認(rèn)執(zhí)行器為ThreadPerTaskExecutor
executor = new ThreadPerTaskExecutor(newDefaultThreadFactory());
}
children = new EventExecutor[nThreads]; //MultithreadEventExecutorGroup是一個(gè)總的管理的類,具體和線程相關(guān)的都交給他的children進(jìn)行處理,是一個(gè)EventExecutor的數(shù)組
for (int i = 0; i < nThreads; i ++) {
boolean success = false;
try {
children[i] = newChild(executor, args); //初始化每一個(gè)EventExecutor的實(shí)例,下面會(huì)有詳細(xì)解釋
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;
}
}
}
}
}
chooser = chooserFactory.newChooser(children); //創(chuàng)建線程的選擇器,選擇是有哪個(gè)線程來(lái)處理
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);
}
Set<EventExecutor> childrenSet = new LinkedHashSet<EventExecutor>(children.length);
Collections.addAll(childrenSet, children);
readonlyChildren = Collections.unmodifiableSet(childrenSet); //將這些子處理器設(shè)置為只讀,不能添加
}
在上面的代碼中都有關(guān)鍵步驟的注釋,總的來(lái)說(shuō)就是最后的臟活累活都不是這個(gè)Group干的,都交給自己內(nèi)部的children來(lái)干,都交給EventExecutor來(lái)干,我們看一下這個(gè)EventExecutor是如何實(shí)例化的
### io.netty.channel.nio.NioEventLoopGroup#newChild
@Override
protected EventLoop newChild(Executor executor, Object... args) throws Exception {
return new NioEventLoop(this, executor, (SelectorProvider) args[0],
((SelectStrategyFactory) args[1]).newSelectStrategy(), (RejectedExecutionHandler) args[2]);
}
### io.netty.channel.nio.NioEventLoop#NioEventLoop
NioEventLoop(NioEventLoopGroup parent, Executor executor, SelectorProvider selectorProvider,
SelectStrategy strategy, RejectedExecutionHandler rejectedExecutionHandler) {
super(parent, executor, false, DEFAULT_MAX_PENDING_TASKS, rejectedExecutionHandler);
if (selectorProvider == null) {
throw new NullPointerException("selectorProvider");
}
if (strategy == null) {
throw new NullPointerException("selectStrategy");
}
provider = selectorProvider;
final SelectorTuple selectorTuple = openSelector();
selector = selectorTuple.selector;
unwrappedSelector = selectorTuple.unwrappedSelector;
selectStrategy = strategy;
}
EventExecutor是使用NioEventLoop進(jìn)行初始化的,這個(gè)NioEventLoop是SingleThreadEventLoop的子類,所以super調(diào)用的是SingleThreadEventLoop的構(gòu)造方法
/**
* Create a new instance
*
* @param parent the {@link EventExecutorGroup} which is the parent of this instance and belongs to it
* @param executor the {@link Executor} which will be used for executing
* @param addTaskWakesUp {@code true} if and only if invocation of {@link #addTask(Runnable)} will wake up the
* executor thread
* @param maxPendingTasks the maximum number of pending tasks before new tasks will be rejected.
* @param rejectedHandler the {@link RejectedExecutionHandler} to use.
*/
protected SingleThreadEventExecutor(EventExecutorGroup parent, Executor executor,
boolean addTaskWakesUp, int maxPendingTasks,
RejectedExecutionHandler rejectedHandler) {
super(parent);
this.addTaskWakesUp = addTaskWakesUp;
this.maxPendingTasks = Math.max(16, maxPendingTasks);
this.executor = ObjectUtil.checkNotNull(executor, "executor");
taskQueue = newTaskQueue(this.maxPendingTasks); //設(shè)置任務(wù)的處理隊(duì)列,后續(xù)任務(wù)會(huì)添加到這里面
rejectedExecutionHandler = ObjectUtil.checkNotNull(rejectedHandler, "rejectedHandler");
}
OK,每一個(gè)處理子事件處理器都會(huì)有一個(gè)任務(wù)的隊(duì)列。目前為止線程池的初始化就告一段落了,感覺(jué)沒(méi)過(guò)癮,咱們就下一篇見(jiàn)。