"Java.util.concurrent package source reading" 11 Thread pool series of Threadpoolexecutor first part

Source: Internet
Author: User

Let's take a look at the Execute method of Threadpoolexecutor, which shows what happens after a task is added to the thread pool:

     Public voidExecute (Runnable command) {if(Command = =NULL)            Throw NewNullPointerException (); /*If the number of worker threads running is less than the number of resident threads set, increase the worker thread and assign the task to the new worker thread*/        intc =Ctl.get (); if(Workercountof (c) <corepoolsize) {            if(Addworker (Command,true))                return; C=Ctl.get (); }

//If the task can be added to the task queue, that is, the number of waiting tasks is still within the allowable range,//check again if the thread pool is closed, remove the task and reject the task if it is closed if(IsRunning (c) &&workqueue.offer (command)) { intRecheck =Ctl.get (); if(! isrunning (Recheck) &&Remove (command)) reject (command); Else if(Workercountof (recheck) = = 0) Addworker (NULL,false); }//If the number of tasks exceeds the scope of the existing worker thread, try creating a new worker thread//If the new worker thread cannot be added, the task will be rejected Else if(!addworker (Command,false) ) reject (command); }

When performing a task, you need to check the status of the thread pool frequently, so let's talk about how the thread pool is state-controlled. The above code has a member variable called a ctl, which is used to mark the thread pool state and the number of worker threads, which is a Automaticinteger object.

    Private Final New Atomicinteger (Ctlof (RUNNING, 0));

CT is a 32-bit integer with the highest 3 bits representing the state:

111 for running,

000 for shutdown,

001 is Stop,

010 for tidying,

011 for ternimated.

So the status value is this three bit plus 29 0, so the value of running is a negative integer (the highest bit is 1), the other states are positive integers, and then the judgment state will compare the size of the value of this.

The remaining 29 bits represent the number of worker threads (so the maximum allowable number of threads is 2 of 29 parties minus 1).

Here is the meaning of these States, the order in which these states occur is exactly the order listed above:

Running indicates normal operating state

The shutdown status means that a shutdown signal is sent, similar to the one you clicked on the Windows Shutdown button

Stop means that the shutdown signal is received, which is equal to Windows responding to this signal, sending out the information that is shutting down

Tidying occurs after a stop response, indicating that some resources are being cleaned up at this time,

Ternimated occurs after the tidying completes, indicating that the shutdown is complete.

Then see what happens when you add a worker thread:

    Private BooleanAddworker (Runnable Firsttask,BooleanCore) {retry: for (;;) {            intc =Ctl.get (); intrs =runstateof (c); //return to false case://1. Rs>shutdown, i.e. states outside of shutdown and running//2. Status of the shutdown//1) Firsttask is not NULL, that is, there is a task assignment//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 there is no limit on the number of threads, the number of worker threads cannot be greater than the maximum (2 of 29 parties-1)//2. If it is a fixed-size thread pool, it cannot be larger than the fixed size//3. If the thread pool is extensible, it cannot be larger than the maximum number of threads specified                intWC =Workercountof (c); if(WC >= Capacity | |WC>= (core?corepoolsize:maximumpoolsize)) return false; //increase the number of threads with CAS operations, and if they fail, re-cycle                if(Compareandincrementworkercount (c)) Breakretry; C= Ctl.get ();//Re-read CTL                if(Runstateof (c)! =rs)Continueretry; Loop}}//New worker threadWorker W =NewWorker (Firsttask); Thread T=W.thread; FinalReentrantlock Mainlock = This. Mainlock;        Mainlock.lock (); Try {            intc =Ctl.get (); intrs =runstateof (c); //Check whether any of the following States appear://1. Failed to create thread//2. Rs>shutdown, i.e. states outside of shutdown and running//3. Rs==shutdown, with assignment            if(T = =NULL||(Rs>= SHUTDOWN &&! (rs = = SHUTDOWN &&Firsttask==NULL)) {decrementworkercount ();                Tryterminate (); return false;            } workers.add (W); ints =workers.size (); if(S >largestpoolsize) Largestpoolsize=s; } finally{mainlock.unlock ();        } t.start (); //here, consider a rare occurrence where the worker thread calls start without completing the//the thread pool enters the stop state, and this time calls Thread#interrupt interrupts each//worker thread, but interrupt does not necessarily work on threads that do not have a start, so//will miss the interrupt of this thread, so after the worker thread start//Check the following, if stop, and this thread has not been interrupt, fill in this missing out//the interrupt.         if(Runstateof (Ctl.get ()) = = STOP &&!t.isinterrupted ()) t.interrupt (); return true; }

This article focuses on how the thread pool handles tasks, and the next article will talk about how worker threads work.

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.