Java Thread Pooling Technology

Source: Internet
Author: User

1. How is the thread pool implemented?
Summary: Multithreading technology mainly solves the problem of multiple threads in the processor unit, which can significantly reduce the idle time of the processor unit and increase the throughput capacity of the processor unit.
Suppose a server takes a task to complete: T1 creates a thread time, T2 the time to execute a task in the thread, T3 destroys the threading time.
if: T1 + T3 is much larger than T2, you can use a thread pool to improve server performance.


Thread pooling is a technique that focuses on how to shorten or adjust T1, T3 time, and thus improve the performance of server programs. It arranges T1, T3, respectively, in the start and end time of the server program, or some idle time period, so that when the server program handles customer requests, there is no T1, T3 overhead.
The thread pool not only adjusts the time period generated by T1, T3, but also significantly reduces the number of threads created, see an example:
Suppose a server handles 50,000 requests a day, and each request requires a separate thread to complete. The number of threads in a thread pool is generally fixed, so the total number of threads does not exceed the number of threads in the thread pool, and the total number of threads is 50000 if the server does not use the thread pool to process these requests. The general thread pool size is far less than 50000. Therefore, server programs that utilize the thread pool do not waste time processing requests in order to create 50000, thereby increasing efficiency.

Thread pool Threadpooltaskexecutor in 2.Spring
Threadpooltaskexecutor is a spring thread pooling technique that is implemented using the Java.util.concurrent.ThreadPoolExecutor in the JDK.
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: Used to reject the execution of a task, there are two situations where this happens:
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.
First, initialize
Way 1. Call Directly:
1.ThreadPoolTaskExecutor pooltaskexecutor = new Threadpooltaskexecutor ();
Buffer queue used by the 2.//thread pool
3.pooltaskexecutor.setqueuecapacity (200);
4.//thread Pool maintains minimum number of threads
5.pooltaskexecutor.setcorepoolsize (5);
6.//thread pool maintains the maximum number of threads
7.pooltaskexecutor.setmaxpoolsize (1000);
8.//thread pool to maintain idle time allowed by threads
9.pooltaskexecutor.setkeepaliveseconds (30000);
10.pooltaskexecutor.initialize ();
Mode 2. configuration file:

In the program, get:
ApplicationContext CTX = new Classpathxmlapplicationcontext ("Applicationcontext.xml");
Threadpooltaskexecutor pooltaskexecutor = (threadpooltaskexecutor) ctx.getbean ("ThreadPool");
Second, use the thread pool to start threads:
Thread udpthread = new Thread (UDP);//Create a thread
Pooltaskexecutor.execute (Udpthread);//Add threads to the thread pool
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 disposition explanation namely Threadpooltaskexecutor's processing flow:
When a task is added to the thread pool by the Execute (Runnable) method:
1. When the number of thread pools is less than corepoolsize, even if the threads in the thread pool are idle, a new thread is created to handle the task being added.
2, when the number in the thread pool equals corepoolsize, but the buffer queue Workqueue is not full, then the task is put into the buffer queue.
3. When the number of thread pools 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. When the number of thread pools is greater than corepoolsize, the buffer queue 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.
It prioritizes the creation of the corepoolsize thread, and when the thread continues to grow, it is placed in the queue, and when both the corepoolsize and the queue are full, a new thread is added, and when the thread reaches Maxpoolsize, an error is thrown Org.springframework.core.task.TaskRejectedException.
In addition, if the Maxpoolsize setting is larger than the number of threads supported by the system, the java.lang.OutOfMemoryError:unable to create new native thread exception is thrown.
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).

3.ThreadPoolExecutor policy configuration and application scenarios, design of thread pool parameters in different business scenarios
Three commonly used Threadpoolexecutor:executor are a set of factory methods for creating commonly used Executorservice, Fixedthreadpool, respectively, Singlethreadexecutor and Cachedthreadpool. These three types of threadpoolexecutor are created by calling the Threadpoolexecutor constructor, except that the parameters are different.
Fixedthreadpool-thread pool size fixed, task queue unbounded
1. Get the available threads from the thread pool to perform the task, and if no threads are available, create a new thread with Threadfactory until the number of threads reaches nthreads;
2. After the thread pool threads reach nthreads, new tasks are placed in the queue
Advantages: Ability to ensure that all tasks are executed and never reject new tasks
Cons: There is no limit to the number of queues, which can cause memory problems in extreme cases where the task execution time is extended indefinitely
Singlethreadexecutor---thread pool size fixed to 1, task queue unbounded
Pros: For scenarios where the logic requires single-threaded processing tasks, colleagues unbounded linkedblockingqueue ensure that new tasks are placed in the queue and are not rejected
Cons: Same as Fixedthreadpool, which can cause memory problems when the processing task waits indefinitely
Cachedthreadpool---thread pool infinite (integer.max_value), waiting queue Length is 1
The number of core threads is 0, which means that all tasks are queued first, the maximum number of threads is integer.max_value, and there is no limit to the number of threads. The keepalive time is set to 60 seconds, which means that the thread waits 60 seconds to exit without a task. Cachedthreadpool the task's processing strategy is that the submitted task is immediately assigned a thread to execute, the thread pool threads will automatically expand and shrink as the number of tasks changes, and in extreme cases where the task execution time is infinitely prolonged, too many threads will be created.

Summarize
For situations where it is necessary to ensure that all submitted tasks are executed, use the Fixedthreadpool
If only one thread can be used for task processing, use Singlethreadexecutor
If the task you want to submit is assigned thread execution as soon as possible, use Cachedthreadpool
If the business allows task execution to fail, or if the execution of the task may occur too long to affect other business scenarios, fault tolerance can be handled by using a thread pool that qualifies the number of threads and a queue of limited length.
High concurrency, low consumption, consider using Newcachedthreadpool, lower concurrency, high time-consuming, consider using Newfixedthreadpool or newsinglethreadpool. They realize the idea just like you. High concurrency and high time-consuming can be considered asynchronous execution.
There are three common strategies for queuing:
1. Direct commit: The Work queue default option is Synchronousqueue, which submits the task directly to the thread without maintaining it. 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, i.e. maxpoolsize to integer.max_value, to avoid rejecting newly submitted tasks.
2. Unbounded queues: Using unbounded queues (such as Linkedblockingqueue) will cause new tasks to wait in the queue when all corepoolsize threads are busy. This way, the created thread will not exceed corepoolsize. (therefore, the value of maxpoolsize is not valid) when each task is completely independent of other tasks, that is, when task execution does not affect each other, it applies to the use of unbounded queues.
3. Bounded queues: When using wired maxpoolsize, 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 can minimize 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.
Here, the understanding of the theory is enough, can be adjusted is corepoolsize and maximumpoolsizes This parameter is also the choice of blockingqueue.
Example one: Use the direct commit policy, also known as Synchronousqueue.
First, the synchronousqueue is unbounded, that is, his ability to store tasks is unrestricted, but because of the nature of the queue itself, it must wait for other threads to be added after the element has been added. Not the core thread here is the newly created thread, but let's just imagine the next scenario.
We use the parameters to construct the Threadpoolexecutor:
1.new Threadpoolexecutor (
2.2, 3, Timeunit.seconds,
3. New <span style= "White-space:normal;" >SynchronousQueue</span><Runnable> (),
4. New Recorderthreadfactory ("Cookierecorderpool"),
5. New Threadpoolexecutor.callerrunspolicy ());

When a core thread already has 2 running.
1. A task continues at this point (a), according to the previous "if the thread running is equal to or more than corepoolsize, then Executor always prefers to join the request to the queue without adding a new thread." ", so a is added to the queue.
2. Another task (B), and the Core 2 threads are not finished, OK, the next first try to describe the 1, but because of the use of synchronousqueue, it must not be added.
3. The above mentioned "if the request cannot be queued, create a new thread, unless this thread is created beyond maximumpoolsize, in which case the task will be rejected." , so a new thread must be created to run the task.
4. For the time being, but if these three tasks have not yet been completed, there are two tasks in a row, the first one added to the queue, the latter one? The queue cannot be inserted, and the number of threads reaches Maximumpoolsize, so you have to execute the exception policy.
Therefore, the use of synchronousqueue usually requires maximumpoolsize to be unbounded, so that this can be avoided (if you want to limit the direct use of bounded queues). It is well written in the JDK that uses synchronousqueue: This policy avoids locking when processing a set of requests that may have internal dependencies.
What do you mean? If your task A1, A2 have internal association, A1 need to run first, then submit A1, and then submit A2, when using synchronousqueue we can guarantee that A1 must first be executed, A1 can not be added to the queue before A2 is executed.
Example two: Using the unbounded queue policy, i.e. Linkedblockingqueue
This takes Newfixedthreadpool, according to the rules mentioned earlier:
If you run fewer threads than Corepoolsize, Executor always prefers to add new threads without queuing.
So what happens when the task continues to increase?
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.
OK, now that the task is in the queue, when will the new thread be added?
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.
It's interesting here, could it be impossible to join the queue? Unlike Synchronousqueue, which has its own characteristics, for unbounded queues, it is always possible to join (resource exhaustion, of course, another). In other words, there will never be a trigger to create a new thread! The number of threads in the corepoolsize will run all the time, running out of the queue to get the task started. So to prevent the task of soaring, such as the implementation of the task is relatively long, and the speed of adding tasks far more than the time of processing tasks, but also continue to increase, if the task memory is larger, and soon burst, hehe.
Example three: bounded queues, using Arrayblockingqueue.
This is the most complex use, so the JDK does not recommend the use of some reason. Compared with the above, the most important feature is to prevent the depletion of the situation occurs.
1.new Threadpoolexecutor (
2.2, 4, Timeunit.seconds,
3. New Arrayblockingqueue<runnable> (2),
4. New Recorderthreadfactory ("Cookierecorderpool"),
5. New Threadpoolexecutor.callerrunspolicy ());
Assume that all tasks are never done.
For the first, a, b to run directly, then, if the c,d, they will be put into the Queu, if the next e,f, then increase the thread run e,f. However, if you come back to the task, the queue is no longer acceptable, and the number of threads reaches the maximum limit, so a deny policy is used to handle it.
Summarize:
The use of 1.ThreadPoolExecutor is still very skillful.
2. Using a unbounded queue may deplete system resources.
3. Using a bounded queue may not perform well enough to adjust the number of threads and queue size
4. The number of threads has a natural overhead, so it needs to be adjusted for different applications.
KeepAliveTime:
The explanation in the JDK is that when the number of threads is greater than the core, this is the maximum amount of time that the extra idle thread waits for a new task before terminating.
What do you mean? Then the above explanation, and then sent to the boss of the workers are always "borrowed", as the saying goes, "There is still", but the problem here is when, if the borrowed workers just completed a task to return, and later found that the task is still, it is not to borrow? This one, the boss must have died.
Reasonable strategy: Since borrowed, then borrow more for a while. It was not until after "a certain period" that the workers could not be used again, and they could return. Some time here is the meaning of KeepAliveTime, Timeunit is the measure of KeepAliveTime value.
Rejectedexecutionhandler
In another case, even if the boss borrowed the workers, but the task continued to come, or not busy, then the whole team had to refuse to accept.
The Rejectedexecutionhandler interface provides the opportunity for a custom method to reject the processing of a task. The 4 policy is already included by default in Threadpoolexecutor because the source code is very simple and is posted directly here.
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.
1.public void Rejectedexecution (Runnable R, Threadpoolexecutor e) {
2. if (!e.isshutdown ()) {
3. R.run ();
4.}
5.}
This strategy obviously does not want to abandon the task. However, since there are no resources in the pool, it is executed directly using the execute thread that called it.
AbortPolicy: Handler rejection will throw runtime rejectedexecutionexception
1.public void Rejectedexecution (Runnable R, Threadpoolexecutor e) {
2. Throw new Rejectedexecutionexception ();
3.}
This strategy throws an exception directly, discarding the task.
Discardpolicy: The task that cannot be performed will be deleted
1.public void Rejectedexecution (Runnable R, Threadpoolexecutor e) {
2.}
This strategy is almost as much a abortpolicy as a drop-off task, except that he does not throw an exception.
Discardoldestpolicy: If the execution program has not been closed, the task in the head of the work queue is deleted, and then the execution of the program is retried (repeat this process if it fails again)
1.public void Rejectedexecution (Runnable R, Threadpoolexecutor e) {
2. if (!e.isshutdown ()) {
3. E.getqueue (). poll ();
4. E.execute (R);
5.}
6.}
The strategy is a little more complicated, with the pool not shutting down and first losing the oldest task cached in the queue, and then trying to run the task again. This strategy requires proper care.
Imagine: If other threads are still running, then the new task kicks off the old task, slows down the queue, and a task kicks off the oldest task in the queue.
Summarize:
KeepAliveTime are related to the types of maximumpoolsize and Blockingqueue. If the blockingqueue is unbounded, then the maximumpoolsize will never be triggered, and the natural keepalivetime will have no meaning.
Conversely, if the number of cores is small, bounded blockingqueue values are smaller, and the KeepAliveTime is small, if the task is frequent, then the system will frequently apply for recycling threads.

Java Thread Pooling Technology

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.