Java Concurrent Programming: Threadpoolexecutor class and method source code Analysis __JDK

Source: Internet
Author: User
Tags class definition

Threadpoolexecutor is the JDK's own thread pool implementation class, and the existing executors tool class implements several thread pooling cores that invoke the Threadpoolexecutor class. Threadpoolexecutor in jdk1.7 and later made a partial modification, this article to JDK1.8 as the subject . 1 Constructors

The Threadpoolexecutor class has 4 constructors, and the other three constructors are the most complete of the parameters under the call, and the following only describes one of the most complete parameters.

 The meaning of the public threadpoolexecutor (int corepoolsize,//parameter has been introduced in the previous article int maximumpoolsize, Long KeepAliveTime, Timeunit, block
                              Ingqueue<runnable> Workqueue, Threadfactory threadfactory,  Rejectedexecutionhandler handler) {if (Corepoolsize < 0 | | |
            Parameter check maximumpoolsize <= 0 | |
            Maximumpoolsize < Corepoolsize | |
        KeepAliveTime < 0) throw new IllegalArgumentException ();
        if (Workqueue = null | | threadfactory = NULL | | | | handler = NULL) throw new NullPointerException (); This.corepoolsize = corepoolsize; Set the base thread count this.maximumpoolsize = maximumpoolsize;  Set maximum number of threads this.workqueue = Workqueue; Set task Queue This.keepalivetime = Unit.tonanos (KeepAliveTime); Set survival time This.threadfactory = THREADFActory; Set up the thread factory This.handler = handler; Framing Deny Policy}
2 method of Threadpoolexecutor class

The main methods of the Threadpoolexecutor class are the Execute () method and the Submit () method for submitting the task, terminating the thread's shutdown () method and the Shutdowmnow method.
  The Execute method is used to submit the task, declared in the executor interface, and implemented in the Threadpoolexecutor class.
  The Submit method is used to submit the task and has the return result, declared in Executorservice and implemented in the Abstractexecutorservice class, and the Threadpoolexecutor class is not overridden.
  The shutdown method closes the thread pool, but allows the running task to run out and place the state as shutdown.
  the Shutdownnow method attempts to terminate the running task when the thread pool is closed, and the status is set to stop. 3 Threadpoolexecutor Class of important methods source code Analysis 3.1 Execute method source code Analysis

The Execute method has made significant changes in JDK1.7 and later implementation, and has enumerated some constants of the Threadpoolexecutor class definition before analyzing the Execute source code.

 private final Atomicinteger ctl = new Atomicinteger (Ctlof (RUNNING, 0))//atomic integer to record number and state of threads  private static final int count_bits = integer.size-3;

    Thread pool The number of threads has a low 29 bit, high 3 bit is the thread pool state private static final int CAPACITY = (1 << count_bits)-1; Runstate is stored in the High-order bits private static final int RUNNING =-1 << count_bits;
    private static final int SHUTDOWN = 0 << count_bits;
    private static final int STOP = 1 << count_bits;
    private static final int tidying = 2 << count_bits;

    private static final int terminated = 3 << count_bits;
    Packing and unpacking ctl private static int runstateof (int c) {return C & ~capacity;}
    private static int workercountof (int c) {return C & CAPACITY;} private static int Ctlof (int rs, int wc) {return rs | wc;} 

The five states of the

thread pool:
RUNNING This state when Threadpoolexecutor is instantiated. The
SHUTDOWN is typically a SHUTDOWN () method that has been executed, no longer accepting new tasks, waiting in the thread pool, and the task in the queue to complete. The
STOP is usually a shutdownnow () method that has been executed, does not accept new tasks, and the tasks in the queue no longer execute, and attempts to terminate threads in the thread pool. The
tidying thread pool is empty and will reach this state, executing the terminated () method. The
terminated terminated () is finished and will arrive in this state.
Directly below the code, and the Code analysis is placed in the comment:

public void Execute (Runnable command) {if (command = = NULL)//parameter check throw new NullPointerException (); int c = Ctl.get (); Gets the variable if (Workercountof (c) < corepoolsize) of the current record thread pool state and the number of pool threads {//If the current thread pool is less than the number of base threads if (Addworker  (Command, True)
            A new thread processing task, and return the task as the first task of this thread; c = Ctl.get (); Increase the thread failure and get the variable again. (Other threads may change the thread pool number of threads, threads may also die)} if (IsRunning (c) && workqueue.offer (command)) {//If the thread pool or running state Add a task to work queue int recheck = Ctl.get (); Double check is primarily a matter of time difference, in the previous sentence and in the middle of this sentence other threads may have changed the thread pool status if (! isrunning (Recheck) && Remove (command))//If the thread If the pool state is no longer running, remove the task from the Work Queue reject (command);
                Remove task succeeded, use reject policy for this task else if (workercountof (recheck) = = 0)//If the thread pool state is running and the number of threads is 0, the base thread count is 0 Addworker (null, FALSE); The thread pool starts with the threads, does not directly process the task after startup, and the judgment bounds become maximumpoolsize} else if (!addworker (command, FALSE))///If the work queue has beenFull, the threading is increased, and the thread judgment condition becomes maximumpoolsize reject (command); }

The general logic after ignoring the details is as follows:
first, the thread pool is less than the number of basic threads (corepoolsize), then start a new thread to handle the new task.
Second, the thread pool threads are not less than the number of base threads, and the task is joined to the Task Force column.
Third, if the work queue is full and the number of threads is less than the maximum number of threads (maximumpoolsize), the new thread is started to handle the current task. The most central method of the
Execute method is the Addworker method, which is responsible for creating the thread, and the following focuses on the Addworker source code.

   Private Boolean Addworker (Runnable Firsttask, Boolean core) {retry:for (;;)
            {int c = ctl.get (); int rs = runstateof (c);
            Gets the thread pool state//Check if queue empty only if necessary. if (rs >= SHUTDOWN &&!) (rs = = SHUTDOWN &&//queue does not have a task and does not commit new tasks will not create a new thread Firsttask = = NULL &&!

            Workqueue.isempty ()) return false; for (;;)
                {int WC = Workercountof (c);
                    if (WC >= CAPACITY | |
                WC >= (Core corepoolsize:maximumpoolsize))//The number of threads is greater than the thread pool capacity or the maximum number of pools passed in will not create a new thread return false; 
                if (Compareandincrementworkercount (c))//If the thread pool state and the number of threads have not changed, the number of threads will be +1 and start the thread break retry;  c = Ctl.get (); Re-read CTL, number of threads, or thread pool state change retrieve thread state if (runstateof (c)!= RS)/thread pool state change to determine whether to create a new thread C OntinUE retry; Else CAS failed due to workercount;
        Retry Inner Loop}} Boolean workerstarted = false;
        Boolean workeradded = false;
        Private Final class Worker extends Abstractqueuedsynchronizer implements Runnable worker w = null;
            try {w = new Worker (firsttask);
            Final Thread t = w.thread;
                if (t!= null) {final Reentrantlock mainlock = This.mainlock; Mainlock.lock ();
                    Lock to prevent other thread colleagues from manipulating try {//recheck while holding lock.
                    Threadfactory failure or if//Shut down before lock acquired.
                        int rs = runstateof (Ctl.get ());//Get Thread status if (rs < SHUTDOWN | | (rs = = SHUTDOWN && firsttask = null))
         {//Check thread pool status if (T.isalive ())//PreCheck that T-startable                   throw new Illegalthreadstateexception ();  Workers.add (w);
                        Add create a good worker object int s = workers.size ();
                        if (S > Largestpoolsize)//update thread pool maximum number record largestpoolsize = s;
                    Workeradded = true;
                finally {Mainlock.unlock ();  } if (workeradded) {T.start ();
                Start thread workerstarted = true;
        finally {if (! workerstarted)//thread did not start successfully, failed to process addworkerfailed (W);
    return workerstarted; }
3.2 Shutdown method source Analysis

  when the shutdown method closes the thread pool, the thread pool status is set to shutdown, the new task is no longer accepted, and the task execution in the queue is completed.

public void shutdown () {
        final reentrantlock mainlock = This.mainlock;
        Mainlock.lock ();
        try {
            checkshutdownaccess ();//Check whether the current thread has permission to all threads in the terminal thread pool
            advancerunstate (SHUTDOWN);//Change the thread pool status to SHUTDOWN
            Interruptidleworkers (); Interrupt Idle thread
            onshutdown ();//hook for Scheduledthreadpoolexecutor
        } finally {
            mainlock.unlock ();
        }
        Tryterminate (); Set thread pool state to terminated
    }
3.3 Shutdownnow method source Analysis

  The Shutdownnow method closes the thread pool to stop and stops the task in progress in the queue.

public list<runnable> Shutdownnow () {list<runnable> tasks;
        Final Reentrantlock mainlock = This.mainlock;
        Mainlock.lock ();
            try {checkshutdownaccess (); Advancerunstate (STOP);
            Change the thread pool status to stop interruptworkers (); tasks = Drainqueue ();
        The difference from the shutdown method is that Shutdownnow will stop the task being processed} finally {Mainlock.unlock ();
        } tryterminate ();
    return tasks; }

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.