Search code examples
javajava.util.concurrentthreadpoolexecutor

Executor with limited thread count on demand


I am looking for an ExecutorService that creates threads on demand up to a predefined limit and destroys idle threads after a keep alive time.

The following constructor creates a ThreadPoolExecutor with fixed thread count:

// taken from Executors.newFixedThreadPool()
new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());

So I tried to create a ExecutorService this way:

// taken from Executors.newCachedThreadPool()
new ThreadPoolExecutor(0, nThreads,
    CACHED_POOL_SHUTDOWN_DELAY, TimeUnit.SECONDS,
    new SynchronousQueue<Runnable>());

But it doesn't work as expected, when nThreads are in use, the Executor does not enqueue new tasks but throws an RejectedExecutionException. I know I could implement a handler for that, but it didn't help me.

How can I create the Executor described ahead?


Solution

  • I found an approach on that post that does exactly what I need.
    @assylias I recognized your answer and changed the queue implementation.

    Now my code looks like this:

    parallelExecutor = new ThreadPoolExecutor(nThreads, nThreads,
        CACHED_POOL_SHUTDOWN_DELAY, TimeUnit.SECONDS,
        new LinkedBlockingQueue<Runnable>());
    
    parallelExecutor.allowCoreThreadTimeOut(true);   // this is the magic
    

    It works like a fixed thread pool but these core thats are allowed to time out.