Reference article: http://www.cnblogs.com/dolphin0520/p/3932921.html
Deep analysis of thread pooling implementation principles
will be explained in the following ways:
1. Thread pool Status
2. Implementation of the mandate
3. Thread initialization in a thread pool
4. Task cache queue and queuing policy
5. Task Rejection Policy
6. Shutdown of the thread pool
7. Dynamic adjustment of thread pool capacity
1. Thread pool Status
A volatile variable is defined in Threadpoolexcutor, and several static final variables are defined to represent each state of the thread pool:
intint RUNNING = 0int SHUTDOWN = 1int STOP = 2 int TERMINATED = 3;
Runstate represents the state of the current thread pool, which is a vlolatile variable to ensure the visibility of the threads;
The following static final variables represent several possible values for runstate.
When the thread pool is created, it is initially in the running state;
If the shutdown () method is called, then the thread pool is in the shutdown state, and when the wire pool is unable to accept the new task, he waits for all tasks to complete;
If the Shutdownnow () method is called, the thread pool is in the stop state, and this time, the thread pooling cannot accept the new task and will attempt to terminate the task being performed;
When the thread pool is in the shutdown or stop state, and all worker threads have been destroyed, the task cache queue has been emptied or the execution finishes, the thread pools are set to the terminated state.
2. Implementation of the mandate
Before we get to the whole process of handing a task to the thread pool to complete the task, let's take a look at some of the other more important member variables in the Threadpoolexecutor class:
1 Private FinalBlockingqueue<runnable> WorkQueue;//task Cache queue, which is used to hold tasks awaiting execution2 Private FinalReentrantlock Mainlock =NewReentrantlock ();//The primary state lock of the thread pool, to the thread pool state (such as the thread pool size3 //, runstate, etc.), use this lock.4 Private FinalHashset<worker> workers =NewHashset<worker> ();//used to store working sets5 6 Private volatile LongKeepAliveTime;//Thread Inventory Time7 Private volatile BooleanAllowcorethreadtimeout;//whether to allow time to live for core threads8 Private volatile intCorepoolsize;//The size of the core pool (that is, when the number of threads in the thread pool is greater than this parameter, the submitted task is put into the task cache queue)9 Private volatile intMaximumpoolsize;//the maximum number of threads the thread pool can tolerateTen One Private volatile intPoolsize;//current number of threads in the thread pool A - Private volatileRejectedexecutionhandler handler;//Task rejection Policy - the Private volatileThreadfactory threadfactory;//thread Factory, used to create threads - - Private intLargestpoolsize;//used to record the maximum number of threads that have ever occurred in a thread pool - + Private LongCompletedtaskcount;//to record the number of tasks that have been performed
The role of each variable has been marked out, here to focus on explaining the Corepoolsize, Maximumpoolsize, largestpoolsize three variables.
Corepoolsize in many places is translated into the core pool size, in fact, I understand this is the size of the thread pool. To give a simple example:
If there is a factory, there are 10 workers in the factory, each worker can only do one task at the same time.
So as long as 10 workers are idle, the task is assigned to the idle workers;
When 10 workers have a task to do, if the task is still in the queue to wait for the task;
If the number of new tasks is growing much faster than the workers do, then the factory supervisor may want to remedy the situation, such as re-recruit 4 temporary workers to come in;
The task is then assigned to the 4 temporary workers;
If it is not enough to say that 14 workers are doing the task, the factory supervisor may want to consider no longer accepting new tasks or abandoning some of the previous tasks.
When one of the 14 workers is free, and the new task grows at a slower pace, the factory manager may consider quitting 4 temporary workers, keeping the original 10, after all, to ask for extra workers to spend money.
The corepoolsize in this example is 10, and Maximumpoolsize is 14 (10+4).
That is, Corepoolsize is the size of the thread pool, and maximumpoolsize, in my opinion, is a remedial measure of the thread pool, that is, when the task volume is suddenly too large.
However, to facilitate understanding, Corepoolsize is translated into core pool size later in this article.
Largestpoolsize is just a variable used to record the maximum number of threads that have ever been in a thread pool, with no relation to the capacity of the thread pools.
Let's take a look at the process that the task went through from submission to final execution.
In the Threadpoolexecutor class, the most core task-submission method is the Execute () method, although it is possible to submit a task by submitting it, but actually the execute () method is ultimately called in the Submit method, So we just need to study the implementation principle of the Execute () method:
public void Execute (Runnable command) { if (command = = null) throw new NullPointerException (); if (poolsize >= corepoolsize | |!addifundercorepoolsize (command)) { if (runstate = = RUNNING && workqueue.o Ffer (command)) { if (runstate! = RUNNING | | poolsize = = 0) ensurequeuedtaskhandled (command); } else if (!addifundermaximumpoolsize command) reject (command);//is shutdown or saturated }}
The above code may not seem so easy to understand, let's say one sentence:
First, determine whether the committed task command is NULL, if NULL, throws a null pointer exception;
Then this sentence, this sentence should be well understood:
1 if (poolSize >= corePoolSize || !addIfUnderCorePoolSize(command))
Because of the or conditional operator, the value of the first half is evaluated first, and if the current number of threads in the thread pool is not less than the core pool size, then the following if statement block is entered directly.
If the current number of threads in the thread pool is less than the core pool size, then the second half is executed
1 addifundercorepoolsize (command)
If this method returns False when the addifundercorepoolsize is executed, the following block of if statements is executed, otherwise the entire method is executed directly.
If you finish Addifundercorepoolsize, this method returns False, and then it then determines:
if (Runstate = = RUNNING && workqueue.offer (command))
If the current thread pool is in the running state, the task is placed in the task cache queue, if the current thread pool is not in the running state, or if the task fails to put in the cache queue:
Addifundermaximumpoolsize (command)
If the Execute Addifundermaximumpoolsize method fails, The Reject () method is executed to perform the task reject processing.
Back to Front:
if (Runstate = = RUNNING && workqueue.offer (command))
The execution of this sentence, if the current thread pool is in the running state and the task is placed in the task cache queue succeeds, continue to judge:
if (runstate! = RUNNING | | poolsize = 0)
Java concurrent Programming-use of the thread pool