Java. util. concurrent package source code reading 11 ThreadPoolExecutor, threadpoolexecutor

Source: Internet
Author: User

Java. util. concurrent package source code reading 11 ThreadPoolExecutor, threadpoolexecutor

First, let's look at the execute method of ThreadPoolExecutor. This method can reflect what happened after a Task is added to the thread pool:

Public void execute (Runnable command) {if (command = null) throw new NullPointerException ();/* if the number of running worker threads is less than the set number of resident threads, increase the number of worker threads, assign the task to the newly created worker thread */int c = ctl. get (); if (workerCountOf (c) <corePoolSize) {if (addWorker (command, true) return; c = ctl. get ();}

// If a task can be added to the task queue, that is, the number of waiting tasks is still within the permitted range, // check whether the thread pool is closed again. If yes, remove the task and reject the task if (isRunning (c) & workQueue. offer (command) {int recheck = ctl. get (); if (! IsRunning (recheck) & remove (command) reject (command); else if (workerCountOf (recheck) = 0) addWorker (null, false );} // if the number of tasks exceeds the threshold of the existing worker thread, try to create a new worker thread. // if a new worker thread cannot be added, the else if (! AddWorker (command, false) reject (command );}

When executing tasks, you need to check the status of the thread pool frequently. Next, let's talk about how the thread pool implements State control. The above code has a member variable called ctl, which is used to mark the thread pool status and the number of worker threads. It is an AutomaticInteger object.

 

    private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));

Ctl is a 32-bit integer. The highest three digits indicate the status:

111 is running,

000 is shutdown,

001 is stop,

010 is tidying,

011 is ternimated.

Therefore, the State value is the three digits plus 29 zeros, so the running value is a negative integer (the highest bit is 1), and the other states are positive integers, this will be used in later hours when the status will be compared.

The remaining 29 digits indicate the number of worker threads (so the maximum number of threads allowed is 1 minus 29 of 2 ).

 

Here is the meaning of these states. The order in which these states occur is exactly the order listed above:

Running indicates normal operation

The shutdown status indicates that a shutdown signal is sent, similar to the shutdown button you clicked on windows.

"Stop" indicates that the shutdown signal is received, which means that the windows system responds to this signal and sends the shutdown message.

Tidying responds after stopping, indicating that some resources are being cleared at this time,

Ternimated is disabled after tidying is completed.

 

Next, let's see what happened when a worker thread was added:

Private boolean addWorker (Runnable firstTask, boolean core) {retry: for (;) {int c = ctl. get (); int rs = runStateOf (c); // returns false: // 1. rs> shutdown, that is, status other than shutdown and running // 2. shutdown status // 1) firstTask is not null, that is, task allocation // 2) No task, but workQueue (waiting for task queue) is empty if (rs> = SHUTDOWN &&! (Rs = SHUTDOWN & firstTask = null &&! WorkQueue. isEmpty () return false; for (;) {// 1. if no thread limit is set, the number of worker threads cannot exceed the maximum value (power 29-1 of 2) // 2. if it is a fixed size thread pool, it cannot be larger than the fixed size // 3. if it is a scalable thread pool, it cannot exceed the maximum number of threads specified. int wc = workerCountOf (c); if (wc> = CAPACITY | wc> = (core? CorePoolSize: maximumPoolSize) return false; // use the CAS operation to increase the number of threads. if the thread fails, reloop if (compareAndIncrementWorkerCount (c) break retry; c = ctl. get (); // Re-read ctl if (runStateOf (c )! = Rs) continue retry; loop }}// create a worker Thread Worker w = new Worker (firstTask); Thread t = w. thread; final ReentrantLock mainLock = this. mainLock; mainLock. lock (); try {int c = ctl. get (); int rs = runStateOf (c); // check whether any of the following statuses appear: // 1. thread creation failed // 2. rs> shutdown, that is, status other than shutdown and running // 3. rs = shutdown, if (t = null | (rs> = SHUTDOWN &&! (Rs = SHUTDOWN & firstTask = null) {decrementWorkerCount (); tryTerminate (); return false;} workers. add (w); int s = workers. size (); if (s> largestPoolSize) largestPoolSize = s;} finally {mainLock. unlock ();} t. start (); // a rare case is considered here. If the worker thread fails to call start, // The thread pool enters the Stop state, at this time, Thread # interrupt will be called to interrupt every // worker thread, but interrupt does not necessarily work for threads without start, so // will miss the interrupt for this Thread, therefore, in the worker thread star T and then // check the following. If the thread is stopped, but the thread is not interrupt, add the missing/interrupt. If (runStateOf (ctl. get () = STOP &&! T. isInterrupted () t. interrupt (); return true ;}

This article focuses on how the thread pool processes tasks. The next article will talk about how the worker thread works.




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.