JAVA-ThreadPoolExecutor 为什么recheck过程中需要在execute函数中判断worker个数?
JAVA-ThreadPoolExecutor why we need to judge the worker count in the execute function during the recheck procedure?
我理解在添加新任务时需要重新检查TPE是否为运行,但我的问题是为什么需要判断workerCountOf(recheck)是否等于0?我的理解是,如果recheck的时候TPE是运行,那么task一定会被TPE执行。所以我认为检查是否有剩余线程执行任务是TPE的责任,而不是提交者!
我说得对吗?
代码如下:
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0) // ????
addWorker(null, false);
}
else if (!addWorker(command, false))
reject(command);
}
举个例子,
假设corePoolSize = 1,第一次检查时,只有一个worker。
在if (workerCountOf(c) < corePoolSize)
和workQueue.offer(command)
之间,唯一的worker完成了它的工作,在block queue中找不到工作,所以它存在。重新检查时,workerCountOf(recheck) == 0
发生。我们需要启动一个新的 worker。
CorePoolSize 并不总是等于实际的 worker 数量。每个工人都可能在完成工作后死亡,并且在有限的时间内在阻塞队列中找不到工作。
但是核心线程在完成工作后永远不会退出,即使队列中没有任务
我理解在添加新任务时需要重新检查TPE是否为运行,但我的问题是为什么需要判断workerCountOf(recheck)是否等于0?我的理解是,如果recheck的时候TPE是运行,那么task一定会被TPE执行。所以我认为检查是否有剩余线程执行任务是TPE的责任,而不是提交者!
我说得对吗?
代码如下:
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0) // ????
addWorker(null, false);
}
else if (!addWorker(command, false))
reject(command);
}
举个例子,
假设corePoolSize = 1,第一次检查时,只有一个worker。
在if (workerCountOf(c) < corePoolSize)
和workQueue.offer(command)
之间,唯一的worker完成了它的工作,在block queue中找不到工作,所以它存在。重新检查时,workerCountOf(recheck) == 0
发生。我们需要启动一个新的 worker。
CorePoolSize 并不总是等于实际的 worker 数量。每个工人都可能在完成工作后死亡,并且在有限的时间内在阻塞队列中找不到工作。
但是核心线程在完成工作后永远不会退出,即使队列中没有任务