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
In your first example, subsequent tasks are rejected because the AbortPolicy
is the default RejectedExecutionHandler
. The ThreadPoolExecutor contains the following policies, which you can change via the setRejectedExecutionHandler
method:
CallerRunsPolicy
AbortPolicy
DiscardPolicy
DiscardOldestPolicy
It sounds like you want cached thread pool with a CallerRunsPolicy.