Impossible to make a cached thread pool with a size limit?

前端 未结 13 871
日久生厌
日久生厌 2020-11-28 00:31

It seems to be impossible to make a cached thread pool with a limit to the number of threads that it can create.

Here is how static Executors.newCachedThreadPool is

13条回答
  •  时光说笑
    2020-11-28 01:22

    Doesn't look as though any of the answers actually answer the question - in fact I can't see a way of doing this - even if you subclass from PooledExecutorService since many of the methods/properties are private e.g. making addIfUnderMaximumPoolSize was protected you could do the following:

    class MyThreadPoolService extends ThreadPoolService {
        public void execute(Runnable run) {
            if (poolSize() == 0) {
                if (addIfUnderMaximumPoolSize(run) != null)
                    return;
            }
            super.execute(run);
        }
    }
    

    The closest I got was this - but even that isn't a very good solution

    new ThreadPoolExecutor(min, max, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue()) {
        public void execute(Runnable command) {
            if (getPoolSize() == 0 && getActiveCount() < getMaximumPoolSize()) {        
                super.setCorePoolSize(super.getCorePoolSize() + 1);
            }
            super.execute(command);
        }
    
        protected void afterExecute(Runnable r, Throwable t) {
             // nothing in the queue
             if (getQueue().isEmpty() && getPoolSize() > min) {
                 setCorePoolSize(getCorePoolSize() - 1);
             }
        };
     };
    

    p.s. not tested the above

提交回复
热议问题