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
This works for Java8+ (and other, for now..)
Executor executor = new ThreadPoolExecutor(3, 3, 5, TimeUnit.SECONDS,
new LinkedBlockingQueue<>()){{allowCoreThreadTimeOut(true);}};
where 3 is the limit of threads count, and 5 is timeout for idle threads.
If you want to check if it works yourself, here is the code to do the job:
public static void main(String[] args) throws InterruptedException {
final int DESIRED_NUMBER_OF_THREADS=3; // limit of number of Threads for the task at a time
final int DESIRED_THREAD_IDLE_DEATH_TIMEOUT=5; //any idle Thread ends if it remains idle for X seconds
System.out.println( java.lang.Thread.activeCount() + " threads");
Executor executor = new ThreadPoolExecutor(DESIRED_NUMBER_OF_THREADS, DESIRED_NUMBER_OF_THREADS, DESIRED_THREAD_IDLE_DEATH_TIMEOUT, TimeUnit.SECONDS,
new LinkedBlockingQueue<>()) {{allowCoreThreadTimeOut(true);}};
System.out.println(java.lang.Thread.activeCount() + " threads");
for (int i = 0; i < 5; i++) {
final int fi = i;
executor.execute(() -> waitsout("starting hard thread computation " + fi, "hard thread computation done " + fi,2000));
}
System.out.println("If this is UP, it works");
while (true) {
System.out.println(
java.lang.Thread.activeCount() + " threads");
Thread.sleep(700);
}
}
static void waitsout(String pre, String post, int timeout) {
try {
System.out.println(pre);
Thread.sleep(timeout);
System.out.println(post);
} catch (Exception e) {
}
}
output of the code above for me is
1 threads
1 threads
If this is UP, it works
starting hard thread computation 0
4 threads
starting hard thread computation 2
starting hard thread computation 1
4 threads
4 threads
hard thread computation done 2
hard thread computation done 0
hard thread computation done 1
starting hard thread computation 3
starting hard thread computation 4
4 threads
4 threads
4 threads
hard thread computation done 3
hard thread computation done 4
4 threads
4 threads
4 threads
4 threads
3 threads
3 threads
3 threads
1 threads
1 threads