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

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

    Had same issue. Since no other answer puts all issues together, I'm adding mine:

    It is now clearly written in docs: If you use a queue that does not blocks (LinkedBlockingQueue) max threads setting has no effect, only core threads are used.

    so:

    public class MyExecutor extends ThreadPoolExecutor {
    
        public MyExecutor() {
            super(4, 4, 5,TimeUnit.SECONDS, new LinkedBlockingQueue());
            allowCoreThreadTimeOut(true);
        }
    
        public void setThreads(int n){
            setMaximumPoolSize(Math.max(1, n));
            setCorePoolSize(Math.max(1, n));
        }
    
    }
    

    This executor has:

    1. No concept of max threads as we are using an unbounded queue. This is a good thing because such queue may cause executor to create massive number of non-core, extra threads if it follows its usual policy.

    2. A queue of max size Integer.MAX_VALUE. Submit() will throw RejectedExecutionException if number of pending tasks exceeds Integer.MAX_VALUE. Not sure we will run out of memory first or this will happen.

    3. Has 4 core threads possible. Idle core threads automatically exit if idle for 5 seconds.So, yes, strictly on demand threads.Number can be varied using setThreads() method.

    4. Makes sure min number of core threads is never less than one, or else submit() will reject every task. Since core threads need to be >= max threads the method setThreads() sets max threads as well, though max thread setting is useless for an unbounded queue.

提交回复
热议问题