Principle and implementation of "thread pool principle" thread pool

Source: Internet
Author: User

Objective

Threads are scarce resources, if created without restriction, will not only consume system resources, but also reduce the stability of the system, reasonable use of thread pool to uniform distribution, tuning and monitoring, there are the following benefits

1. Reduce resource consumption

2. Improve response speed

3, improve the manageability of threads

The executor framework, introduced in java1.5, decouples the submission and execution of tasks by defining tasks and then submitting them to the thread pool, regardless of how the task executes, which thread executes it, and when it executes.

First, Threadpoolexecutor

Threadpoolexecutor is the factory class of the thread pool, which allows you to quickly initialize a thread pool that meets your business needs. such as the Executors.newfixedthreadpool method can generate a thread pool that has a fixed thread pool.

1    PublicThreadpoolexecutor (intCorepoolsize,2                               intMaximumpoolsize,3                               LongKeepAliveTime,4 timeunit Unit,5Blockingqueue<runnable>workQueue) {6          This(Corepoolsize, maximumpoolsize, KeepAliveTime, Unit, WorkQueue,7 executors.defaultthreadfactory (), defaulthandler);8}

The essence is to initialize a Threadexecutor object with different parameters, the specific parameters are described as follows:

Corepoolsise:

The number of core threads in the thread pool, when a task is submitted, the thread pool creates a new thread to perform the task until the current number of threads equals corepoolsize, and if the current number of threads is corepoolsize, the task that continues to commit is saved to the blocking queue, waiting to be executed If the Prestartallcorethreads () method of the thread pool is executed, the thread pool creates and starts all core threads in advance. Maximumpoolsize: The maximum number of threads allowed in the thread pool. If the current blocking queue is full and the task continues to be committed, a new thread is created to perform the task, provided that the current number of threads is less than maximumpoolsize; KeepAliveTime: The time that the thread is idle, that is, when the thread does not have a task to execute, the time to survive; This parameter is only used when the number of threads is greater than corepoolsize, unit:keepalivetime units, WorkQueue: The blocking queue used to hold tasks waiting to be executed, and the task must implement the Runable interface, which provides the following blocking queues in the JDK:
1. Arrayblockingqueue: Bounded blocking queue based on array structure, sorting tasks by FIFO;
2, Linkedblockingquene: Based on the chain list structure of the blocking queue, according to FIFO sorting tasks, throughput is usually higher than arrayblockingquene;
3, Synchronousquene: A blocking queue that does not store elements, each insert operation must wait for another thread to invoke the remove operation, otherwise the insert operation is always in a blocked state, and throughput is usually higher than linkedblockingquene;
4, Priorityblockingquene: a priority of the unbounded blocking queue;
Threadfactory: The factory that creates the thread, through a custom thread factory, can set a name for each new thread that has a recognized thread. Handler: The saturation policy of the thread pool, when the blocking queue is full and there are no idle worker threads, if you continue to submit the task, you must take a policy to handle the task, and the thread pool provides 4 strategies:
1, AbortPolicy: Directly throws the exception, the default policy;
2. Callerrunspolicy: Perform the task with the caller's thread;
3, Discardoldestpolicy: Discard the first task in the blocking queue, and perform the current task;
4, Discardpolicy: direct discard task;
It is also possible to implement the Rejectedexecutionhandler interface based on the application scenario, customizing the saturation strategy, such as logging or persisting the task that the storage cannot handle. The Executors:exectors factory class provides the initialization interface for the thread pool, mainly in the following ways: Newfixedthreadpool Initializes a thread pool with a specified number of threads, corepoolsize = = Maximumpoolsize, Use Linkedblockingquene as a blocking queue, but it does not release threads when the thread pool is not able to perform tasks. Newcachedthreadpool:1, initialize a thread pool that can cache threads, default cache 60s, thread pool threads can reach Integer.max_value, or 2147483647, Internal use of Synchronousqueue as a blocking queue;
2. Unlike the thread pool created by Newfixedthreadpool, Newcachedthreadpool automatically frees thread resources when there is no task execution, when the thread is idle for more than KeepAliveTime, and when a new task is submitted, if there are no idle threads, Creating a new thread can cause a certain amount of overhead, and when you use the thread pool, be sure to control the number of concurrent tasks or create a large number of threads that can cause serious performance problems. Newsinglethreadexecutor: There is only one thread in the initialized thread pool, and if the thread ends abnormally, a new thread is recreated to continue the task, and the only thread can guarantee the order in which the submitted tasks are executed. Use Linkedblockingqueue internally as a blocking queue. Newscheduledthreadpool: The initialized thread pool can periodically perform the submitted tasks within a specified time, and in the actual business scenario, the thread pool can be used to synchronize data periodically. Second, the implementation of the principle in addition to newscheduledthreadpool internal implementation of a special point, several other thread pools are based on the Threadpoolexecutor class implementation. 1. Thread pool Internal state
1 ######## #ThreadPoolExecutor ############2  PrivateFinal Atomicinteger ctl =NewAtomicinteger (Ctlof (RUNNING,0));3     Private StaticFinalintCount_bits = Integer.size-3;4     Private StaticFinalintCapacity = (1<< count_bits)-1;5 6     //runstate is stored in the High-order bits7     Private StaticFinalintRUNNING =-1<<count_bits;8     Private StaticFinalintSHUTDOWN =0<<count_bits;9     Private StaticFinalintSTOP =1<<count_bits;Ten     Private StaticFinalinttidying =2<<count_bits; One     Private StaticFinalintTERMINATED =3<<count_bits; A  -     //Packing and Unpacking ctl -     Private Static intRunstateof (intc) {returnC & ~capacity;} the     Private Static intWorkercountof (intc) {returnC &capacity;} -     Private Static intCtlof (intRsintWC) {returnRS | wc }
The Atomicinteger variable ctl is very powerful: it uses a low 29-bit representation of thread pool threads, and a high 3-bit to represent the running state of the thread pools:
1, RUNNING: -1 << COUNT_BITS, which is 3 bits high 111, the thread pool of that State receives new tasks and handles tasks in the blocking queue;
2, SHUTDOWN: 0 << COUNT_BITS, where the high 3 bits are 000, the thread pool for that State does not receive new tasks, but it handles the tasks in the blocking queue;
3. STOP: 1 << COUNT_BITS, where a high 3 bit is 001, the thread of that State does not receive new tasks, does not handle the tasks in the blocking queue, and interrupts the running tasks;
4, Tidying: 2 << COUNT_BITS, i.e. high 3 bits are 010;
5, TERMINATED: 3 << COUNT_BITS, i.e. high 3 bits are 011;

Principle and implementation of "thread pool principle" thread pool

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.