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?