I understand that we need to recheck if the TPE is running when we add a new task, but my question is why we need to judge if the workerCountOf(recheck) is equal to 0? My understanding is that if the TPE is running during the recheck, the task will guaranteed to be executed by the TPE. So I think it is the TPE's responsibility to check if there is any thread left to execute the task, not the submitter!
so am i right ?
the code as below:
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);
}
Here is an example,
Suppose corePoolSize = 1. When check first time, there is only one worker.
Between if (workerCountOf(c) < corePoolSize)
and workQueue.offer(command)
, the only worker finished its job and find no job in the block queue, so it exists. When recheck, workerCountOf(recheck) == 0
happens. We need to start a new worker.
CorePoolSize not always equals the real count of worker. Every workercould die after they finish their job and find no job in the block queue within a limited time.