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 queu
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);
}
}
}
}