I create a ThreadPoolExecutor with this line of code :
private ExecutorService executor = new ThreadPoolExecutor(5, 10, 120, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(20, true));
Then, I run 25 tasks (T01 to T25) so the situation is :
When I put 1 more task (T26), as the queue is full, I expected that the older task (T06) is removed to be launched (because MaxPoolSize is not reached) and the new task (T26) is placed at the end of the queue.
But in real life, if Queue is full and MaxPoolSize is not reached, the newest task is started.
So, I have ...
... instead of ...
Can I configure the ThreadPoolExecutor to get the expected result ? Should I use another classes ?
For information, part of ThreadPoolExecutor source code
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
}
}
private boolean addIfUnderMaximumPoolSize(Runnable firstTask) {
Thread t = null;
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
if (poolSize < maximumPoolSize && runState == RUNNING)
t = addThread(firstTask);
} finally {
mainLock.unlock();
}
if (t == null)
return false;
t.start();
return true;
}
Thanks
I would make the core size equal the maximum. This is how most of the pools are used and I am not sure when would be the downside in your case, but you would get the tasks executed in order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With