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

前端 未结 13 821
日久生厌
日久生厌 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:20

    Here is another solution. I think this solution behaves as you want it to (though not proud of this solution):

    final LinkedBlockingQueue queue = new LinkedBlockingQueue() {
        public boolean offer(Runnable o) {
            if (size() > 1)
                return false;
            return super.offer(o);
        };
    
        public boolean add(Runnable o) {
            if (super.offer(o))
                return true;
            else
                throw new IllegalStateException("Queue full");
        }
    };
    
    RejectedExecutionHandler handler = new RejectedExecutionHandler() {         
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            queue.add(r);
        }
    };
    
    dbThreadExecutor =
            new ThreadPoolExecutor(min, max, 60L, TimeUnit.SECONDS, queue, handler);
    

提交回复
热议问题