Java 8 threadPoolExecutor stucks after N tasks with return statement

I am using ThreadPoolExecutor as shown below:

 ThreadPoolExecutor pool = new ThreadPoolExecutor(cores, 50, 30L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10)); 

and:

 pool.execute(()->{ //code goes here if(some condition){ return; } //code goes here }) 

And when this block with the return statement is turned on, all these tasks get stuck in the TPE. TPE says it is fully loaded and always throws a RejectedExecutionException

I do not understand why this is happening. For example, if you have a pool of size 10, and you have 100 tasks, 10 of them will correspond to the section, you will not accept the 101st task, all subsequent tasks will be rejected. Why?

+5
source share
1 answer

You configured ThreadPoolExecutor incorrectly

 public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) 

Creates a new ThreadPoolExecutor with the given initial parameters and the factory default thread and rejected the handler. It might be more convenient to use one of the Executors factory methods instead of this generic constructor.

Options:

corePoolSize - the number of threads to store in the pool, even if they are inactive, if the allowCoreThreadTimeOut parameter is not set

maximumPoolSize - maximum number of threads allowed in the pool

keepAliveTime - when the number of threads is larger than the kernel, this is the maximum time during which excess wait threads will wait for new tasks to complete.

unit - the unit of time for the keepAliveTime argument

workQueue - a queue for storing tasks before they are completed. Only Runnable tasks represented by the execute method will be executed in this queue.

I have never seen a TPE with a workQueue size (10) less than maximumPoolSize (50). With your current configuration, the 11th work task will be rejected due to queue size 10 (queue size at this point in time).

Increase the size of the workQueue to get rid of the RejectedExecutionException . 50 threads can easily handle more than 1000 small work tasks. Adjust this queue size according to your requirement with a reasonable value.

+5
source

Source: https://habr.com/ru/post/1245422/


All Articles