ThreadPoolExecutor : Tasks are getting queued up and not submitted

后端 未结 6 1735
醉酒成梦
醉酒成梦 2021-02-03 11:42

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

6条回答
  •  忘掉有多难
    2021-02-03 11:50

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

提交回复
热议问题