Solve Java.util.concurrent.RejectedExecutionException

Source: Internet
Author: User

Preface 12:00 last night when running the automation test script encountered java.util.concurrent.RejectedExecutionException this exception, from the exception name it is easy to parse out that the task is submitted by the thread pool rejected. View source discovery is in the activity, Asynctask is running in a custom thread pool, but the Ondestory function shows the shutdown method that called the thread pool first, and then the Asynctask cancel operation. This may cause the task to be rejected.
Threadpoolexecutor a executorservice, which performs each submitted task using one of several thread pools possible, usually using the Executors factory method configuration, but viewing the source code, Find Factory method is also unified call the Threadpoolexecutor class, for example, the source code is as follows:
public class Executors {public static executorservice newfixedthreadpool (int nthreads) {return new Threadpoolexecutor (Nthre Ads, Nthreads, 0L, Timeunit.milliseconds, new Li    Nkedblockingqueue<runnable> ()); } public static Executorservice newfixedthreadpool (int nthreads, threadfactory threadfactory) {return new Threa                                      Dpoolexecutor (Nthreads, Nthreads, 0L, Timeunit.milliseconds,    New Linkedblockingqueue<runnable> (), threadfactory); }}
Although I have always agreed that programmers should use the more convenient executors factory method Executors.newcachedthreadpool () (without the boundary pool, can be automated Process recovery), Executors.newfixedthreadpool ( int) (fixed size thread pool) and Executors.newsinglethreadexecutor () (single background thread), but through the source we can see that they all call the Threadpoolexecutor (int corepoolsize, int maximumpoolsize, long keepalivetime, timeunit unit, blockingqueue<runnable> workQueue) method, So before we analyze java.util.concurrent.RejectedExecutionException, we need to learn a bit more about the use of threadpoolexecutor. The size of the core pool and the maximum pool treadpoolexecutor automatically adjusts the pool size based on the boundaries set by Corepoolsize and Maximumpoolsize. When a new task is committed in method execute (java.lang.Runnable), if the running thread is less than corepoolsize, a new thread is created to process the request, even if the other worker threads are idle. If you run more threads than corepoolsize and less than maximumpoolsize, a new thread is created only when the queue is full. If you set the same corepoolsize and Maximumpoolsize, a fixed-size thread pool is created. If you set Maximumpoolsize to a basic unbounded value (such as Integer.max_value), the thread pool is allowed to accommodate any number of concurrent tasks. Keep active time if there are currently more than corepoolsize threads in the pool, these extra threads will be terminated when the idle time exceeds KeepAliveTime. Queued all blockingqueue can be used to transmit and keep committed tasks. You can use this queue to interact with the pool size:
    • If you run fewer threads than corepoolsize, executor always prefers to add new threads without queuing.
    • If you are running a thread that is equal to or more than corepoolsize, executor always prefers to join the request to the queue without adding a new thread.
    • If the request cannot be queued, a new thread is created unless the thread is created beyond maximumpoolsize, in which case the task is rejected (throwing rejectedexecutionexception).
There are three common strategies for queuing:
    1. Submit directly. The default option for the work queue is synchronousqueue, which will submit tasks directly to the thread without maintaining them. Here, if there is no thread available to run the task immediately, attempting to join the task to the queue will fail, and a new thread will be constructed. This policy avoids locking when processing a set of requests that may have internal dependencies. Direct submissions typically require unbounded maximumpoolsizes to avoid rejecting newly submitted tasks. This policy allows the possibility of an increase in the number of lines where the command is continuously arriving with an average of more than the queue can handle.
    2. unbounded queues. Using unbounded queues (for example, linkedblockingqueue that do not have a predefined capacity) will cause all corepoolsize threads to be busy while the newer tasks are waiting in the queue. In this way, the created thread will not exceed corepoolsize (therefore, the value of maximumpoolsize is not valid).
    3. bounded queues. When using limited maximumpoolsizes, bounded queues (such as arrayblockingqueue) help prevent resource exhaustion, but may be difficult to adjust and control. The queue size and maximum pool size may need to be compromised: using large queues and small pools minimizes CPU usage, operating system resources, and context switching overhead, but can result in artificially reduced throughput. If the task is frequently blocked, the system may schedule more threads than you permit, and using small queues typically requires a large pool size, high CPU usage, but may encounter unacceptable scheduling overhead, which can reduce throughput.
The terminating program no longer references the pool and no remaining threads are automatically shutdown. If you want to make sure that you recycle the dereferenced pool (even if the user forgets to call shutdown ()), you must schedule the unused thread to terminate eventually. Analysis by Threadpoolexecutor class analysis, there are two main causes of java.util.concurrent.RejectedExecutionException: 1. When the thread pool shows a call to shutdown () and then submits the task to the thread pool, the exception is thrown if you configure the Deny policy to be threadpoolexecutor.abortpolicy. 2. When your queuing strategy is a bounded queue, And the configured deny policy is Threadpoolexecutor.abortpolicy, and when the thread pool has reached maximumpoolsize, you will throw a Threadpoolexecutor.abortpolicy exception when you submit the task to it. Show off thread pool This is a good idea. For example, you go to a warehouse to store the goods, at the beginning, the warehouse manager opened the door to you, you put the first item into the warehouse, but when you put it out, someone put the warehouse door closed, then you next time to store items, you will be rejected. The sample code is as follows:
import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;public class TextExecutor {public Executorservice Fixedexecutorservice = Executors.newfixedthreadpool (5);p ublic executorservice CachedExecutorService = Executors.newcachedthreadpool ();p ublic executorservice singleexecutorservice = Executors.newsinglethreadexecutor ( );p ublic void Testexecutorexception () {for (int i = 0; i <; i + +) {Fixedexecutorservice.execute (new sayhellorunnable ()); Fixedexecutorservice.shutdown ();}} Private class Sayhellorunnable implements Runnable {@Overridepublic void run () {try {thread.sleep ()} catch (Interrup Tedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} finally {System.out.println ("Hello world!");}}} public static void Main (string[] args) {textexecutor testexecutor = new Textexecutor (); Testexecutor.testexecutorexception ();}} 
Solution 1. Do not show the call shutdown method, such as Android, only you cancel the Asynctask in the Destory method, then the line constructor no active thread will reclaim itself. 2. When invoking the thread pool, determine if it has been shutdown, using the API method IsShutDown method to determine the sample code:
Import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;public class TextExecutor {public Executorservice Fixedexecutorservice = Executors.newfixedthreadpool (5);p ublic executorservice CachedExecutorService = Executors.newcachedthreadpool ();p ublic executorservice singleexecutorservice = Executors.newsinglethreadexecutor ( );p ublic void Testexecutorexception () {for (int i = 0; i <; i + +) {//Add IsShutDown () to determine if (!fixedexecutorservice.issh Utdown ()) {Fixedexecutorservice.execute (New sayhellorunnable ());} Fixedexecutorservice.shutdown ();}} Private class Sayhellorunnable implements Runnable {@Overridepublic void run () {try {thread.sleep ()} catch (Interrup Tedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} finally {System.out.println ("Hello world!");}}} public static void Main (string[] args) {textexecutor testexecutor = new Textexecutor (); Testexecutor.testexecutorexception ();}}
The number of threads over the Maximumpoolsize sample code uses a custom executorservice that can reproduce the problem:
Import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Java.util.concurrent.synchronousqueue;import Java.util.concurrent.threadpoolexecutor;import Java.util.concurrent.timeunit;public class Textexecutor {public Executorservice Fixedexecutorservice = Executors.newfixedthreadpool (5);p ublic executorservice cachedexecutorservice = Executors.newcachedthreadpool (); Public Executorservice Singleexecutorservice = Executors.newsinglethreadexecutor ();p ublic Executorservice Customerexecutorservice = new Threadpoolexecutor (3, 5, 0, Timeunit.milliseconds, new synchronousqueue<runnable> ( ));p ublic void Testexecutorexception () {for (int i = 0; i <; i + +) {//Add IsShutDown () to determine if (!fixedexecutorservice.iss Hutdown ()) {Fixedexecutorservice.execute (New sayhellorunnable ());} Fixedexecutorservice.shutdown ();}} public void Testcustomerexecutorexception () {for (int i = 0; i <; i + +) {Customerexecutorservice.execute (new Sayhel Lorunnable ());}} Private Class SayhellOrunnable implements Runnable {@Overridepublic void run () {try {thread.sleep ()} catch (Interruptedexception e) {//To Do auto-generated catch Blocke.printstacktrace ();} finally {System.out.println ("Hello world!");}}} public static void Main (string[] args) {textexecutor testexecutor = new Textexecutor (); Testexecutor.testcustomerexecutorexception ();;}}
Solution 1. Adjust the maximumpoolsize as much as possible, for example set to Integer.max_value
Public Executorservice Customerexecutorservice = new Threadpoolexecutor (3, Integer.max_value, 0, Timeunit.milliseconds , new synchronousqueue<runnable> ());
2. Use other queueing policies, such as Linkedblockingqueue
<span style= "White-space:pre" ></span>public executorservice customerexecutorservice = new Threadpoolexecutor (3, 5, 0, Timeunit.milliseconds, New linkedblockingqueue<runnable> ());






Solve Java.util.concurrent.RejectedExecutionException

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.