Reputation: 3731
I glanced at execute
method of ThreadPoolExecutor
class. This seems to be very short and simple:
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
if (poolSize >= corePoolSize || !addIfUnderCorePoolSize(command)) {
if (runState == RUNNING && workQueue.offer(command)) {
if (runState != RUNNING || poolSize == 0)
ensureQueuedTaskHandled(command);
}
else if (!addIfUnderMaximumPoolSize(command))
reject(command); // is shutdown or saturated
}
}
But nothing seems to be happening if the the condition poolSize >= corePoolSize
is satisfied!
Because of if the first part of a OR
condition is true, the second won't be executed:
if (true || anyMethodWillNotBeExecuted()) { ... }
According to the rules for thread creation, here also is maximumPoolSize
. And in case if the number of threads is equal (or greater than) the corePoolSize
and less than maxPoolSize
the new thread should be created for task or task should be added to queue.
So why in case when poolSize
greater than or equals to corePoolSize
nothing should happen?..
Upvotes: 1
Views: 108
Reputation: 4641
addIfUnderCorePoolSize
will create a new "core" thread for this executor.
If number of threads in the executor (poolSize
) is already greater than or equal to number of "core" threads (corePoolSize
), then obviously there is no need to create more "core" threads.
Maybe expanding OR
condition will be a bit clearer:
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
if (poolSize >= corePoolSize) {
// there are enough core threads
// let's try to put task on the queue
if (runState == RUNNING && workQueue.offer(command)) {
if (runState != RUNNING || poolSize == 0)
ensureQueuedTaskHandled(command);
} else if (!addIfUnderMaximumPoolSize(command))
reject(command); // is shutdown or saturated
} else if (addIfUnderCorePoolSize(command)) {
// there was not enough core threads, so we started one
// the task is being executed on a new thread, so there's nothing else to be done here
return;
} else {
// there are enough core threads
// but we could not start a new thread
// so let's try to add it to the queue
if (runState == RUNNING && workQueue.offer(command)) {
if (runState != RUNNING || poolSize == 0)
ensureQueuedTaskHandled(command);
} else if (!addIfUnderMaximumPoolSize(command))
reject(command); // is shutdown or saturated
}
}
Upvotes: 1