The principle of concurrent programming 14--thread pool

Source: Internet
Author: User

Java Concurrency Programming Practice Directory

Concurrent Programming 01--concurrenthashmap

Concurrent programming 02--blocking queues and producer-consumer patterns

Concurrent programming 03--latching countdownlatch and fence Cyclicbarrier

Concurrent programming 04--callable and future

Concurrent programming 05--completionservice:executor and Blockingqueue

Concurrent Programming 06--Task cancellation

Concurrent programming 07--interruption of task cancellation

Concurrent programming 08--task cancellation stop thread-based services

Concurrent programming 09--off of task cancellation Executorservice

Concurrent Programming 10--task cancellation "poison pill" object

Concurrent programming 11--Limitations of the shutdownnow of task cancellation and shutdown

Concurrent programming 12--use of the thread pool configuration threadpoolexecutor and Saturation policy

The overall architecture of the concurrent programming 13--thread pool

The principle of concurrent programming 14--thread pool

Overview Part 1th threadpoolexecutor Introduction 2nd part threadpoolexecutor data structure 3rd part thread pool Schedule 1th Part Threadpoolexecutor Introduction

Threadpoolexecutor is a thread pool class. For the thread pool, it can be popularly understood as "a collection of threads that hold a certain number of threads." The thread pool allows the number of threads that are allowed to run concurrently, which is the capacity of the thread pool, and some threads block waiting when the thread that is added to the thread pools exceeds its capacity. The thread pool manages the threads that are added to the thread pool through the appropriate scheduling policies and deny policies. "

Part 2nd Threadpoolexecutor data structure

The data structure of the Threadpoolexecutor is as follows:

The individual data is defined in Threadpoolexecutor.java as follows:

//blocks the queue. Private FinalBlockingqueue<runnable>WorkQueue;//Mutual exclusion LockPrivate FinalReentrantlock Mainlock =NewReentrantlock ();//The thread collection. A worker corresponds to a thread. Private FinalHashset<worker> workers =NewHashset<worker>();//"termination condition", bound to "Mainlock". Private FinalCondition termination =mainlock.newcondition ();//the maximum number of threads in a thread pool that has ever reached the limit. Private intlargestpoolsize;//number of completed tasksPrivate LongCompletedtaskcount;//the Threadfactory object that is used to create the thread. Private volatilethreadfactory threadfactory;//Handles the processing of the deny policy. Private volatileRejectedexecutionhandler handler;//keep the thread alive for a while. Private volatile LongKeepAliveTime;Private volatile Booleanallowcorethreadtimeout;//Core Pool SizePrivate volatile intcorepoolsize;//Max Pool SizePrivate volatile intMaximumpoolsize;

1. Workers
Workers is a hashset<work> type, that is, it is a worker collection. A worker corresponds to a thread, which means that the thread pool contains a "collection of threads" through workers. When the worker's thread pool is started, it executes the task in the thread pool, and when a task is completed, it takes a blocked task out of the blocking queue of the thread-pool to continue running.
The role of wokers is that the thread pool implements the "Allow multiple threads to run simultaneously" through it.

2. WorkQueue
Workqueue is a blockingqueue type, that is, it is a blocking queue. When the number of threads in the thread pool exceeds its capacity, the thread enters the blocking queue for blocking waits.
Through Workqueue, the thread pool implements the blocking function.

3. Mainlock
Mainlock is a mutex that enables mutually exclusive access to the thread pool through Mainlock.

4. Corepoolsize and Maximumpoolsize
Corepoolsize is the core pool size, and maximumpoolsize is the maximum pool size. Their role is to adjust the number of threads actually running in the thread pool.
For example, when a new task is submitted to the thread pool (via the Execute method).
--If at this point, the number of threads running in the thread pool < corepoolsize, a new thread is created to process the request.
--If at this point, the number of threads running in the thread pool > corepoolsize, but < maximumpoolsize, the new thread is created only when the blocking 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, values for the core pool size and the maximum pool size are set at the creation thread pool, but dynamic changes can also be made using setcorepoolsize (int) and setmaximumpoolsize (int).

5. Poolsize
Poolsize is the actual size of the current thread pool, which is the number of tasks in the thread pools.

6. Allowcorethreadtimeout and KeepAliveTime
Allowcorethreadtimeout indicates whether the thread is allowed to survive idle, while KeepAliveTime is the idle thread is terminated when the thread pool is idle for more than KeepAliveTime time.

7. Threadfactory
Threadfactory is the Threadfactory object. It is a thread factory class that "thread pool creates threads through Threadfactory".

8. Handler
Handler is the Rejectedexecutionhandler type. It is a handle to the thread pool rejection policy, which means that when a task is added to the thread pool and the thread pools reject the task, the thread pool is handled appropriately by handler.

In summary, the thread pool manages the threads collection through workers, and each thread executes the task in the thread pool after it is started, and when a task finishes executing, it pulls the task out of the blocking queue of the thread pool to continue running. The blocking queue is the queue that manages the thread pool task, which enters the blocking queue to wait when the task that is added to the thread pools exceeds the capacity of the line pool.

3rd part thread pool scheduling

The main workflow of the thread pool is as follows:

As we can see, when a new task is submitted to the thread pool, the thread pool processes the following:

    1. First, the thread pool determines if the base thread pool is full? Not full, create a worker thread to perform the task. Full, then go to the next process.
    2. Next the thread pool determines if the task queue is full? is not full, the newly submitted task is stored in the work queue. Full, then go to the next process.
    3. The last thread pool determines if the entire thread pool is full? is not full, a new worker thread is created to perform the task, and the saturation policy is assigned to handle the task.

Figure -01:

Figure -02:

Description :
In Figure 01, there are n tasks in the thread pool. "Task 1", "Task 2", "Task 3" the 3 tasks are executing, while "Task 4" to "Task N" waits in the blocking queue. The task being performed, in the workers collection, the Workers collection contains 3 workers, each worker corresponds to a thread, and the thread thread processes one task at a time.
When a task is processed in the workers collection, a task is removed from the blocking queue to continue execution, as shown in 02. Figure 02 means that when task 1 is processed, the thread pool takes task 4 out of the blocking queue and places it in workers for processing.

The principle of concurrent programming 14--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.