The thread pool provided by spring

Source: Internet
Author: User

thread pool threadpooltaskexecutor in springCategory: JAVA Spring2013-07-12 10:36 14896 people read reviews (9) favorite reports Spring Thread pool Multithreading

First, initialize

1, call directly

[Java]View Plaincopyprint? < param name= "wmode" value= "Transparent" >
    1. Threadpooltaskexecutor pooltaskexecutor = new Threadpooltaskexecutor ();
    2. Buffer queue used by the thread pool
    3. Pooltaskexecutor.setqueuecapacity (200);
    4. The thread pool maintains a minimum number of threads
    5. Pooltaskexecutor.setcorepoolsize (5);
    6. Maximum number of threads maintained by the thread pool
    7. Pooltaskexecutor.setmaxpoolsize (1000);
    8. The thread pool maintains idle time allowed by threads
    9. Pooltaskexecutor.setkeepaliveseconds (30000);
    10. Pooltaskexecutor.initialize ();
2. Configuration files

[Plain]View Plaincopyprint?
  1. <!--Configuring the thread pool--
  2. <bean id = "Taskexecutor" class = "Org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor" >
  3. <!--thread pool maintains a minimum number of threads--
  4. <span style= "White-space:pre" > </span><property name = "Corepoolsize" value = "5"/>
  5. <!--thread pool to maintain idle time allowed by threads--
  6. <span style= "White-space:pre" > </span><property name = "Keepaliveseconds" value = "30000"/>
  7. <!--thread pool maintains the maximum number of threads--
  8. <span style= "White-space:pre" > </span><property name = "Maxpoolsize" value = "$"/>
  9. <!--the buffer queue used by the thread pool--
  10. <span style= "White-space:pre" > </span><property name = "Queuecapacity" value = "$"/>
  11. </bean>

Inside the program gets:

ApplicationContext CTX = new Classpathxmlapplicationcontext ("Applicationcontext.xml");
Threadpooltaskexecutor pooltaskexecutor = (threadpooltaskexecutor) ctx.getbean ("Taskexecutor");


Second, using thread pool to start threads
Thread udpthread = new Thread (UDP);
Pooltaskexecutor.execute (Udpthread);
Gets the number of threads active for the current thread pool:
int count = Pooltaskexecutor.getactivecount ();
Logger.debug ("[x]-now ThreadPool active threads totalnum:" +count);




Third, the configuration explanation
When a task is added to the thread pool by the Execute (Runnable) method:
1. If the number in the thread pool is less than corepoolsize at this point, even if the threads in the thread pool are idle, create a new thread to handle the task being added.
2. If the number in the thread pool is equal to corepoolsize, but the buffer queue Workqueue is not full, then the task is placed in the buffer queue.
3. If the number of threads in the thread pool is greater than corepoolsize, the buffer queue Workqueue full, and the number of thread pools is less than maximumpoolsize, a new thread is built to handle the task being added.
4. If the number of threads in the thread pool is greater than corepoolsize, the buffer queue is workqueue full, and the number in the thread pool equals maximumpoolsize, the task is handled by handler the policy specified. That is: the priority of the processing task is: Core thread corepoolsize, Task queue workqueue, maximum thread maximumpoolsize, if all three are full, use handler to handle the rejected task.
5. When the number of threads in the thread pool is greater than corepoolsize, the thread will be terminated if a thread has more than KeepAliveTime idle time. This allows the thread pool to dynamically adjust the number of threads in the pool.


Iv. Other thread pools
Threadpoolexecutor of the JDK
A executorservice that uses a number of possible pool threads to perform each submitted task, typically using the Executors factory method configuration.
The thread pool resolves two different issues: because of the reduced overhead of each task invocation, they typically provide enhanced performance when performing a large number of asynchronous tasks, and can also provide methods for binding and managing resources, including the threads that are used to perform collection tasks. Each threadpoolexecutor also maintains some basic statistical data, such as the number of completed tasks.
For ease of use across a large number of contexts, this class provides a number of adjustable parameters and extension hooks. However, programmers are strongly advised to use the more convenient executors factory method Executors.newcachedthreadpool () (without a boundary pool, which can be used for automatic thread recycling), Executors.newfixedthreadpool ( int) (fixed-size thread pool) and Executors.newsinglethreadexecutor () (single background thread), which have predefined settings for most usage scenarios. Otherwise, when you manually configure and adjust this class, use the following guidelines:
1. Core and maximum pool size
The threadpoolexecutor will automatically adjust the pool size based on the boundaries set by Corepoolsize (see Getcorepoolsize ()) and maximumpoolsize (see Getmaximumpoolsize ()). 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 pool is allowed to accommodate any number of concurrent tasks. In most cases, the core and maximum pool sizes are only set on a construction basis, but they can also be changed dynamically using setcorepoolsize (int) and setmaximumpoolsize (int).
2, on-demand construction
By default, the core thread can be dynamically overridden with method Prestartcorethread () or prestartallcorethreads (), even if it was originally created and started only when a new task is needed.
3. Create a new thread
Create a new thread using Threadfactory. If not otherwise stated, threads are created in the same threadgroup using Executors.defaultthreadfactory (), and these threads have the same norm_priority priority and non-daemon status. By providing different threadfactory, you can change the name of the thread, the thread group, the priority, the daemon state, and so on. If threadfactory fails to create a thread when returning null from Newthread, the executor continues to run, but cannot perform any tasks.
4. Keep Active Time
If there are currently more than corepoolsize threads in the pool, these extra threads will terminate when the idle time exceeds KeepAliveTime (see Getkeepalivetime (Java.util.concurrent.TimeUnit)). This provides a way to reduce resource consumption when the pool is inactive. If the pool becomes more active later, you can create a new thread. You can also use Method Setkeepalivetime (long, java.util.concurrent.TimeUnit) to dynamically change this parameter. Use the value of Long.MAX_VALUETimeUnit.NANOSECONDS to effectively disable idle threads from the previous termination state before closing.
5. Queuing
All blockingqueue can be used to transfer and maintain submitted 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.
There are three common strategies for queuing:
A, 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 collection 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 that are allowed to continue when the command arrives in a row that exceeds the average that the queue can handle.
b, unbounded queue. Using unbounded queues (for example, linkedblockingqueue that do not have a predefined capacity) causes new tasks to be queued when all corepoolsize threads are busy. This way, the created thread will not exceed corepoolsize. (therefore, the value of the maximumpoolsize is not valid.) When each task is completely independent of other tasks, that is, when task execution does not affect each other, it is appropriate to use a unbounded queue, for example, in a Web page server. This queueing can be used to handle transient burst requests, which allow the possibility of an increase in the number of lines that are allowed to occur when the command reaches an average of more than the queue can handle.
C, bounded queue. 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 tasks are frequently blocked (for example, if they are I/O boundaries), the system may schedule more threads than you permit. Using small queues typically requires a large pool size, high CPU utilization, but may encounter unacceptable scheduling overhead, which also reduces throughput.
6. Rejected Tasks
New tasks submitted in method execute (java.lang.Runnable) are rejected when Executor is closed and Executor uses a limited boundary for the maximum thread and work queue capacity and is already saturated. In both of these cases, the Execute method calls its Rejectedexecutionhandler rejectedexecutionhandler.rejectedexecution (java.lang.Runnable, Java.util.concurrent.ThreadPoolExecutor) method. The following four predefined handler policies are available:
In the default Threadpoolexecutor.abortpolicy, the handler is rejected and the runtime Rejectedexecutionexception is thrown.
In Threadpoolexecutor.callerrunspolicy, the thread invokes the execute itself that runs the task. This strategy provides a simple feedback control mechanism that can slow down the submission of new tasks.
In Threadpoolexecutor.discardpolicy, the tasks that cannot be performed are deleted.
In Threadpoolexecutor.discardoldestpolicy, 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 (repeating the process if it fails again).
It is also possible to define and use other kinds of rejectedexecutionhandler classes, but doing so requires great care, especially when the policy is used only for specific capacity or queueing policies.
7. Hook method
This class provides protected overridable BeforeExecute (Java.lang.Thread, java.lang.Runnable) and AfterExecute (Java.lang.Runnable, Java.lang.Throwable) method, which is called before and after each task is executed. They can be used to manipulate the execution environment, for example, reinitialize ThreadLocal, collect statistics, or add log entries. In addition, you can override method terminated () to perform all special processing that needs to be done after the Executor is completely terminated.
If the hook or callback method throws an exception, the internal worker thread fails sequentially and terminates abruptly.
8. Queue Maintenance
Method Getqueue () allows access to the work queue for monitoring and debugging purposes. Strongly oppose the use of this method for any other purpose. Both the Remove (java.lang.Runnable) and Purge () methods can be used to help with storage reclamation when a large number of queued tasks are canceled.

The thread pool provided by spring

Related Article

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.