The Threadpooltaskexecutor in spring

Source: Internet
Author: User
Tags java se

When observing the operation of the system on the line, it is found that there is such error message in the error log, org.springframework.core.task.TaskRejectedException, So the Threadpooltaskexecutor class to do the next comb.

1.ThreadPoolExecutor
The Threadpooltaskexecutor in spring is implemented with the help of the JDK and the java.util.concurrent.ThreadPoolExecutor in the contract. Learn about Threadpoolexecutor in the next section. thre The Adpoolexecutor constructor is as follows:

Java code
  1. Public threadpoolexecutor (int corepoolsize,
  2. int maximumpoolsize,
  3. Long KeepAliveTime,
  4. Timeunit Unit,
  5. Blockingqueue<runnable> WorkQueue,
  6. Threadfactory Threadfactory,
  7. Rejectedexecutionhandler handler) {


The following are the specific meanings of each representative:

int corepoolsize: The thread pool maintains the minimum number of threads.
int maximumpoolsize: The maximum number of threads that the thread pool maintains.
Long KeepAliveTime: The time of the idle thread's survival.
Timeunit Unit: Time unit, existing nanosecond, microsecond, millisecond, second enumeration value.
Blockingqueue<runnable> WorkQueue: Holds the queue of tasks awaiting execution.
Rejectedexecutionhandler handler:
To deny execution of a task, this happens in two cases.
One is in the Execute method if Addifundermaximumpoolsize (command) is false, that is, the thread pool is saturated;
The second is in the Execute method, discover Runstate!=running | | Poolsize = = 0, which is already shutdown, calls ensurequeuedtaskhandled (Runnable command), and it is possible to call reject in the method.

There are four predefined reject policies:
(1) The Threadpoolexecutor.abortpolicy policy is the default policy, and the handler is rejected to throw runtime rejectedexecutionexception.
(2) Threadpoolexecutor.callerrunspolicy policy, the caller's thread executes the task and discards if the executor is closed.
(3) Threadpoolexecutor.discardpolicy the policy, tasks that cannot be performed will be discarded.
(4) Threadpoolexecutor.discardoldestpolicy policy, if the execution program has not been closed, the task in the head of the work queue is deleted, and then the program is retried (repeat this process if it fails again).


2. Use of Threadpooltaskexecutor in spring
The most common way to do this is to inject the bean into the container with the following code:
Java code
    1. <bean id="Threadpooltaskexecutor"
    2. class="Org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor" >
    3. <property name="corepoolsize" value="ten"/>
    4. <property name="maxpoolsize" value="/> "
    5. <property name="queuecapacity" value="/> "
    6. </bean>


Threadpoolexecutor the process of the actuator:
(1) Create a new thread when the thread pool size is less than corepoolsize and process the request.
(2) When the thread pool size equals corepoolsize, the request is placed in the workqueue, and the idle thread in the pool is taken from the Workqueue to take the task and handle it.
(3) When Workqueue does not fit into the new task, the new thread joins the thread pool and processes the request, and if the pool size is propped up to maximumpoolsize, use Rejectedexecutionhandler to do the reject processing.
(4) Additionally, when the thread pool has more threads than corepoolsize, the extra thread waits for KeepAliveTime for a long time and destroys itself if no request can be processed.


Understand the implementation process of Threadpoolexecutor, The org.springframework.core.task.TaskRejectedException anomalies mentioned at the beginning are also well understood and solved. Used in the Threadpooltaskexecutor class
is the Threadpoolexecutor.abortpolicy () policy, which throws an exception directly.

Java SE 5.0 introduces Threadpoolexecutor, Scheduledthreadpoolexecutor. Spring 2.x enables the Concurrenttaskexecutor and threadpooltaskexecutor to customize the various properties they expose with the IOC configuration form.

Multithreading concurrency is often cumbersome, and if you use the spring container to manage business beans, it's a lot easier. Spring encapsulates the implementation of multithreaded implementations of Java, and you only need to focus on the processes of concurrency and some of the concurrency load, specifically how to use spring to handle concurrent transactions:

1. Understanding the Taskexecutor interface

Spring's Taskexecutor interface is equivalent to the Java.util.concurrent.Executor interface. In fact, the main reason it exists is to abstract the dependency on Java 5 when using the thread pool. This interface has only one method, execute (Runnable Task), which accepts an execution task based on the semantics and configuration of the thread pool. The Taskexecutor was originally created to provide an abstraction of a thread pool to other spring components when needed. For example, the Applicationeventmulticaster component, the JMS Abstractmessagelistenercontainer, and the integration of quartz use Taskexecutor abstraction to provide a thread pool. Of course, if your bean needs thread pool behavior, you can use this abstraction layer as well.

2. Implementation class for the Taskexecutor interface

(1) Simpleasynctaskexecutor class

This implementation does not reuse any threads, or it starts a new thread each time it is called. However, it also supports limiting the number of concurrent totals, blocking new calls until a location is freed when the total number of threads concurrently limits is exceeded. If you need a real pool, please keep looking down.

(2) Synctaskexecutor class

This implementation does not execute asynchronously. Instead, each call is executed in the thread that initiated the call. Its main use is when there is no need for multi-threading, such as a simple test case.

(3) Concurrenttaskexecutor class

This implementation is the wrapper for the Java 5 Java.util.concurrent.Executor class. There is another alternative, the Threadpooltaskexecutor class, which exposes the configuration parameters of executor as bean properties. It is seldom necessary to use concurrenttaskexecutor, but if the threadpooltaskexecutor is not sufficient, Concurrenttaskexecutor is another alternative.

<bean id= "Concurrenttaskexecutor" class= "Org.springframework.scheduling.concurrent.ConcurrentTaskExecutor"/ >

(4) Simplethreadpooltaskexecutor class

This implementation is actually a subclass of the Quartz Simplethreadpool class that listens for spring's lifecycle callbacks. This is typical use when you have a thread pool that needs to be quartz and non-quartz components.

(5) Threadpooltaskexecutor class

It does not support any substitution or downstream migration of the java.util.concurrent package. Both Doug Lea and Dawid Kurzyniec implemented different package structures for Java.util.concurrent implementations, which prevented them from running correctly. This implementation can only be used in a Java 5 environment, but it is the most commonly used in this environment. Its exposed bean properties can be used to configure a java.util.concurrent.ThreadPoolExecutor to wrap it in a taskexecutor. If you need more advanced classes, such as Scheduledthreadpoolexecutor, we recommend that you use Concurrenttaskexecutor instead.

Learn about the Threadpoolexecutor in the JDK below. The Threadpoolexecutor constructor is as follows:

Public threadpoolexecutor (int corepoolsize,                            int maximumpoolsize,                            long KeepAliveTime,                            timeunit Unit,                            blockingqueue<runnable> WorkQueue,                            Threadfactory Threadfactory,                            

The following are the specific meanings of each representative: &NBSP;
int corepoolsize: The minimum number of threads that the thread pool maintains.  
int maximumpoolsize: The maximum number of threads that the thread pool maintains.  
Long KeepAliveTime: The time the idle thread survives.  
Timeunit Unit: Time unit, existing nanosecond, microsecond, millisecond, second enumeration value.  
Blockingqueue<runnable > WorkQueue: Holds a queue of tasks waiting to be executed.  
Rejectedexecutionhandler handler:  is used to reject the execution of a task, which can happen in two cases:
One is in the Execute method if Addifundermaximumpoolsize (command) is false, that is, the thread pool is saturated;  
Two is found in the Execute method, runstate!=running | | Poolsize = = 0, which is already shutdown, calls ensurequeuedtaskhandled (Runnable command), and it is possible to call reject in the method.   the

reject policy is predefined in four ways:  
(1) threadpoolexecutor.abortpolicy policy, which is the default policy, the handler being rejected will throw the runtime Rejectedexecutionexception.  
(2) Threadpoolexecutor.callerrunspolicy policy, where the caller's thread executes the task and discards if the executor is closed.  
(3) Threadpoolexecutor.discardpolicy the policy, tasks that cannot be performed will be discarded.  
(4) Threadpoolexecutor.discardoldestpolicy policy, if the execution program has not been closed, the task in the head of the work queue is deleted, and then the program is retried (repeat this process if it fails again).  

Threadpoolexecutor the process of the actuator:
(1) Create a new thread when the thread pool size is less than corepoolsize and process the request.
(2) When the thread pool size equals corepoolsize, the request is placed in the workqueue, and the idle thread in the pool is taken from the Workqueue to take the task and handle it.
(3) When Workqueue does not fit into the new task, the new thread joins the thread pool and processes the request, and if the pool size is propped up to maximumpoolsize, use Rejectedexecutionhandler to do the reject processing.
(4) Additionally, when the thread pool has more threads than corepoolsize, the extra thread waits for KeepAliveTime for a long time and destroys itself if no request can be processed.


Understand the implementation process of Threadpoolexecutor, The org.springframework.core.task.TaskRejectedException anomalies mentioned at the beginning are also well understood and solved. Used in the Threadpooltaskexecutor class
is the Threadpoolexecutor.abortpolicy () policy, which throws an exception directly.

The most common way of threadpooltaskexecutor in spring is to inject beans into the container, and the exposed properties are actually threadpoolexecutor properties, and this represents the advantages of the DI container. The following code:

<bean id= "Threadpooltaskexecutor" class= "Org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor" >      <property name= "Corepoolsize" value= "2"/>      <property name= "keepaliveseconds" value= "/>"      <property name= "maxpoolsize" value= "ten"/> <property      name= "queuecapacity" value= "  />" </bean>

(6) Timertaskexecutor class

This implementation uses a timertask as the implementation behind it. It differs from synctaskexecutor in that the method invocation is performed in a separate thread, although it is synchronous in that thread.

(7) Workmanagertaskexecutor class

This implementation uses the COMMONJ Workmanager as its underlying implementation and is the most important class for configuring COMMONJ Workmanager applications in spring context. Similar to Simplethreadpooltaskexecutor, this class implements the Workmanager interface, so it can be used directly as a workmanager.

The Threadpooltaskexecutor in spring

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.