We have a scenario where tasks submitted to ThreadPoolExecutor are long running. When the thread pool is started we start it with core pool size = 5, max pool size = 20 and queue size of 10. In our application around 10 tasks get submitted. Most of the time these tasks run for few mins/hrs and then complete. However there was a situation when all of the 5 tasks got hanged on I/O. As a result my core pool size reached it max, but my Threadpoolexecutor queue was not full. So the additional 5 tasks never got a chance to run. Please do suggest how we can handle such scenario? Is having a smaller queue better option in such situation? What would be an optimum queue size while initializing threadPool?
Also regarding the hanged tasks, is there any way we can pull out the threads out of the Threadpool? In that case at least other tasks would get a chance to run.
The overall situation is like this:
core pool size = 5,
max pool size = 20 and
queue size of 10
10 tasks are submitted. Out of which
Hence, Your Program is hanged .
To know more about dynamics of ThreadPoolExecutor
watch here . The notable points of this doc is as follows:
EDIT
If you wish to increase core pool size then you can use setCorePoolSize(int corePoolSize) . If you increase the corepoolsize
then new threads will, if needed, be started to execute any queued tasks.
The Javadocs for ThreadPoolExecutor states:
Any BlockingQueue may be used to transfer and hold submitted tasks. The use of this queue interacts with pool sizing:
Unless you exceed your queue size after 5 threads are "hanging", you're not going to get more threads.
The real answer is: fix the problem that's causing your threads to hang. Otherwise you're going to have to implement some scheme that uses the Future
s returned by submit()
to cancel threads if they are running too long.
I think another approach would be to set the corePoolSize based on the the number of tasks waiting in the queue. One can control the corePoolSize by using setCorePoolSize. A sample monitor thread can control you threadPoolExecutor. You can also improve this monitor to adjust the degree of parallelism.
public class ExecutorMonitor extends Thread{
ThreadPoolExecutor executor = null;
int initialCorePoolSize;
public ExecutorMonitor(ThreadPoolExecutor executor)
{
this.executor = executor;
this.initialCorePoolSize = executor.getCorePoolSize();
}
@Override
public void run()
{
while (true)
{
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (executor.getQueue().size() > 0)
{
if(executor.getActiveCount() < executor.getMaximumPoolSize())
executor.setCorePoolSize(executor.getCorePoolSize() + 1);
}
if (executor.getQueue().size() == 0)
{
if(executor.getCorePoolSize() > initialCorePoolSize)
executor.setCorePoolSize(executor.getCorePoolSize() -1);
}
}
}
}
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