1. Basic usage of thread pool
1.1. Why the thread pool is needed
In peacetime business, if you want to use multiple threads, then we will create a thread before the start of the business, the end of the business, destroy the thread. But for business, the creation and destruction of threads is not related to the business itself, but only the tasks performed by the thread. It is therefore desirable to use as many CPUs as possible on the execution of tasks, rather than creating and destroying them with a business-independent thread. And the thread pool solves this problem, the function of thread pool is to reuse threads.
What support does 1.2.JDK provide for us?
The related class diagrams in the JDK are shown in the previous illustration.
Some of the special classes to be mentioned.
The callable class is similar to the Runable class, but the difference is that callable has a return value.
Threadpoolexecutor is an important implementation of the thread pool.
And executors is a factory class.
1.3. Use of thread pool
1.3.1. Type of thread pool
- New Fixedthreadpool a fixed number of thread pools, the number of threads in the thread pool is fixed and does not change.
- The new singlethreadexecutor is a single thread pool with a thread pooling.
- The new Cachedthreadpool cache thread pool, the number of threads in thread pools is not fixed and will vary depending on the size of the requirement.
- New Scheduledthreadpool the thread pool for scheduled task scheduling, which is used to perform scheduled tasks, such as how often every 5 minutes,
public static Executorservice newfixedthreadpool (int nthreads) {return
new Threadpoolexecutor (Nthreads, Nthreads,
0L, Timeunit.milliseconds,
new linkedblockingqueue<runnable> ());
public static Executorservice Newsinglethreadexecutor () {return
new Finalizabledelegatedexecutorservice
( New Threadpoolexecutor (1, 1,
0L, Timeunit.milliseconds,
new Linkedblockingqueue<runnable> ()));
public static Executorservice Newcachedthreadpool () {return
new Threadpoolexecutor (0, Integer.max_value,
60L, Timeunit.seconds,
new synchronousqueue<runnable> ());
From the method point of view, obviously fixedthreadpool,singlethreadexecutor,cachedthreadpool are different instances of threadpoolexecutor, but the parameters are different.
Public threadpoolexecutor (int corepoolsize,
int maximumpoolsize,
long KeepAliveTime,
timeunit Unit,
blockingqueue<runnable> Workqueue) {This is
(Corepoolsize, maximumpoolsize, KeepAliveTime, Unit, Workqueue,
executors.defaultthreadfactory (), DefaultHandler);
}
The following describes the meaning of the parameters in the Threadpoolexecutor constructor.
- Number of core threads in the corepoolsize thread pool
- The maximum number of threads that can be accommodated in a maximumpoolsize thread pool
- KeepAliveTime when the number of threads is greater than corepoolsize, more than KeepAliveTime time, the number of corepoolsize threads will be terminated.
- Units of Unit KeepAliveTime
- Workqueue when the number of tasks is large and the thread pool threads are not satisfied, the committed task is placed in the blocked queue, and the thread is idle to fetch data from the blocking queue.
So looking at the fixedthreadpool above, its threads have the same core number and maximum number of seats, so that threads are not created and destroyed during work. When the number of tasks is large and the threads in the thread pool are not satisfied, the task is saved to the Linkedblockingqueue, and the linkedblockingqueue size is integer.max_value. This means that the task is continually being added, which can make memory consumption more and more large.
And Cachedthreadpool is different, its core thread number is 0, the maximum number is integer.max_value, its blocking queue is synchronousqueue, this is a special queue, its size is 0. Because the number of core threads is 0, it is necessary to add the task to Synchronousqueue, which only one thread is adding data from, and another thread can succeed when it obtains data from it. Adding data to this queue alone will return a failure. When the return fails, the thread pool begins to expand the threads, which is why the number of cachedthreadpool threads is not fixed. When the 60s thread is still unused, the thread is destroyed.
1.4. Small example of thread pool usage
1.4.1. Simple thread pool
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
public class ThreadPoolDemo {public
static class MyTask implements Runnable {
@Override public
void Run () {
system.out.println (System.currenttimemillis () + "Thread ID:"
+ Thread.CurrentThread (). GetId ());
try {
thread.sleep (1000);
} catch (Exception e) {
e.printstacktrace ();
}
}} public static void Main (string[] args) {
MyTask mytask = new MyTask ();
Executorservice es = Executors.newfixedthreadpool (5);
for (int i = 0; i < i++) {
es.submit (mytask);
}}
}
Because of the use of Newfixedthreadpool (5), but 10 threads are started, 5 are executed each time, and it is obvious that the threads are reused, and that the ThreadID is duplicated, that is, the first 5 tasks and the last 5 tasks are executed by the same thread.
It's used here.
Es.submit (MyTask);
There is also a way to submit:
Es.execute (MyTask);
The difference is that the submit will return a future object, which will be introduced later.
1.4.2.ScheduledThreadPool
Import java.util.concurrent.Executors;
Import Java.util.concurrent.ScheduledExecutorService;
Import Java.util.concurrent.TimeUnit;
public class ThreadPoolDemo {public
static void Main (string[] args) {
scheduledexecutorservice ses = EXECUTORS.N Ewscheduledthreadpool (ten);
If the previous task is not completed, the schedule does not start.
Ses.schedulewithfixeddelay (New Runnable () {
@Override public
void Run () {
try {
Thread.Sleep (1000);
System.out.println (System.currenttimemillis ()/1000);
catch (Exception e) {
//Todo:handle Exception
}
}
, 0, 2, timeunit.seconds);//Start 0 seconds later, then cycle 2 seconds to execute once
}
}
Output:
1454832514
1454832517
1454832520
1454832523
1454832526
...
Because task execution takes 1 seconds, task scheduling must wait for the previous task to complete. Which means that every 2 seconds here, a new task is opened 2 seconds after the previous task completes.
2. Expand and enhance the thread pool
2.1. Callback Interface
There are some callback APIs in the thread pool to provide us with extended operations.
Executorservice es = new Threadpoolexecutor (5, 5, 0L, Timeunit.seconds,
new linkedblockingqueue<runnable> ()) {
@Override
protected void BeforeExecute (Thread T, Runnable R) {
System.out.println ("Ready to execute");
}
@Override
protected void AfterExecute (Runnable R, Throwable t) {
System.out.println ("execution Complete");
}
@Override
protected void terminated () {
System.out.println ("Thread pool Exit");
}
;
We can implement the Threadpoolexecutor beforeexecute,afterexecute,terminated method by implementing the subclass of Threadpoolexecutor to realize the thread execution before and after the Log management or other actions when the thread pool exits.
2.2. Reject Policy
Sometimes the task is very heavy, causing the system to load too much. As mentioned above, when tasks are getting larger, tasks are put into fixedthreadpool blocking queues, resulting in too much memory consumption and eventually a memory overflow. Such a situation should be avoided. So when we find that the number of threads exceeds the maximum number of threads, we should give up some tasks. When discarded, we should write down the task instead of just throwing it away.
There is also another constructor in the Threadpoolexecutor.
Public threadpoolexecutor (int corepoolsize,
int maximumpoolsize,
long KeepAliveTime,
timeunit Unit,
blockingqueue<runnable> Workqueue,
Threadfactory threadfactory,
Rejectedexecutionhandler handler) {
if (Corepoolsize < 0 | |
Maximumpoolsize <= 0 | |
Maximumpoolsize < Corepoolsize | |
KeepAliveTime < 0)
throw new IllegalArgumentException ();
if (Workqueue = null | | threadfactory = NULL | | | | handler = NULL)
throw new NullPointerException ();
This.corepoolsize = corepoolsize;
This.maximumpoolsize = maximumpoolsize;
This.workqueue = Workqueue;
This.keepalivetime = Unit.tonanos (KeepAliveTime);
This.threadfactory = threadfactory;
This.handler = handler;
}
Threadfactory we'll introduce you later.
And handler is the implementation of the rejection policy, which tells us what to do if the task does not execute.
A total of 4 strategies are listed above.
AbortPolicy: Throws an exception if the task cannot be accepted.
Callerrunspolicy: If you can't accept the task, let the calling thread do it.
Discardoldestpolicy: If you can't accept a task, discard one of the oldest tasks and be maintained by a queue.
Discardpolicy: If the task cannot be accepted, the task is discarded.
Executorservice es = new Threadpoolexecutor (5, 5, 0L, Timeunit.seconds,
new linkedblockingqueue<runnable> (),
New Rejectedexecutionhandler () {
@Override public
void Rejectedexecution (Runnable R),
Threadpoolexecutor executor) {
System.out.println (r.tostring () + "is Discard");
}
);
Of course, we can also implement the Rejectedexecutionhandler interface ourselves to define the rejection policy.
2.3. Custom Threadfactory
As you've just seen, you can specify Threadfactory in the Threadpoolexecutor constructor.
Threads in the thread pool are created by the thread factory, and we can customize the thread factory.
Default Thread Factory:
Static Class Defaultthreadfactory implements Threadfactory {
private static final Atomicinteger Poolnumber = new Atomi Cinteger (1);
Private final Threadgroup group;
Private final Atomicinteger threadnumber = new Atomicinteger (1);
Private final String Nameprefix;
Defaultthreadfactory () {
SecurityManager s = System.getsecuritymanager ();
Group = (s!= null)? S.getthreadgroup ():
Thread.CurrentThread (). Getthreadgroup ();
Nameprefix = "pool-" +
poolnumber.getandincrement () +
"-thread-";
}
Public thread Newthread (Runnable r) {
thread t = new Thread (group, R,
Nameprefix + threadnumber.getandincrement (),
0);
if (T.isdaemon ())
T.setdaemon (false);
if (t.getpriority ()!= thread.norm_priority)
t.setpriority (thread.norm_priority);
return t;
}
}
3. Forkjoin
3.1. The idea
Is the thought of divide and conquer.
Fork/join similar to MapReduce algorithm, the difference is: Fork/join only when necessary, such as the task is very large to split into a small task, and MapReduce is always beginning to perform the first step to split. It seems that fork/join is better suited to a JVM's inner-level, while MapReduce is suitable for distributed systems.
4.2. Using the interface
Recursiveaction: no return value
Recursivetask: Has return value
4.3. Simple example
Import java.util.ArrayList;
Import Java.util.concurrent.ForkJoinPool;
Import Java.util.concurrent.ForkJoinTask;
Import Java.util.concurrent.RecursiveTask;
public class Counttask extends recursivetask<long>{private static final int THRESHOLD = 10000;
Private long start;
private long end;
Public Counttask (Long-start, long end) {super ();
This.start = start;
This.end = end;
@Override protected Long Compute () {long sum = 0;
Boolean cancompute = (End-start) < THRESHOLD;
if (Cancompute) {for (long i = start; I <= end; i++) {sum = sum + i;
}else {///divided into 100 small tasks long step = (start + end)/100;
arraylist<counttask> subtasks = new arraylist<counttask> ();
Long pos = start;
for (int i = 0; i < i++) {long LaStone = pos + step;
if (LaStone > End) {lastone = end;
} counttask SubTask = new Counttask (POS, LaStone);
POS + step + 1;
Subtasks.add (SubTask); Subtask.fork ()//push task to thread pool} for (Counttask t:subtasks) {sum+ = T.join ()//waiting for all subtasks to end} return sum;
public static void Main (string[] args) {Forkjoinpool forkjoinpool = new Forkjoinpool ();
Counttask task = new Counttask (0, 200000L);
forkjointask<long> result = Forkjoinpool.submit (Task);
try {Long res = result.get ();
System.out.println ("sum =" + res);
catch (Exception e) {//Todo:handle Exception e.printstacktrace ();
}
}
}
The above example describes an additive and a task. The cumulative task is divided into 100 tasks, each task only performs the sum of a number of numbers and, after the last join, calculates and accumulates each task.
4.4. Implementation elements
4.4.1.WorkQueue and CTL
Each thread will have a Task Force column
Static Final class Workqueue
In a work queue, there is a series of fields that are managed by the thread
volatile int eventcount; encoded inactivation count; < 0 if inactive
int nextwait; Encoded record of next event waiter
int nsteals; Number of steals
int hint; Steal index hint
Short Poolindex; Index of this queue in pool
Final short mode; 0:lifo, > 0:fifo, < 0:shared
volatile int qlock; 1:locked, -1:terminate; else 0
volatile int base; Index of next slot for poll
int top; Index of next slot for push
Forkjointask<?>[] Array; The elements (initially unallocated)
Final Forkjoinpool pool; The containing pool (May is null)
Final Forkjoinworkerthread owner; Owning thread or null if shared
Volatile Thread Parker; = = Owner during call to Park; else null
Volatile forkjointask<?> Currentjoin; Task being joined in Awaitjoin
Forkjointask<?> Currentsteal; Current non-local task being executed
It is important to note here that JDK7 and JDK8 have a great difference in the implementation of Forkjoin. We are here to introduce the JDK8. In the thread pool, sometimes not all threads are executing, some threads are suspended, and those suspended threads are stored in a stack. The interior is represented by a linked list.
Nextwait will point to the next waiting thread.
Poolindex the subscript index in the thread pool.
EventCount in initialization, EventCount is associated with Poolindex. A total of 32 digits, the first one indicates whether it is activated, and 15 bits indicate the number of times it was suspended
EventCount, the rest of the expression Poolindex. Use a field to represent multiple meanings.
The work queue Workqueue is represented by the forkjointask<?>[] array. And top,base to represent both ends of the queue, and the data is between the two.
CTL maintained in Forkjoinpool (64-bit long)
volatile long ctl;
* Field CTL is a long packed with:
* Ac:number of active running workers minus target parallelism (bits)
* Tc:number of total workers minus target parallelism (bits)
* St:true If Pool is terminating (1 bit)
* Ec:the wait count of top waiting thread (BITS)
* Id:poolindex of top of Treiber stack of waiters (bits)
AC indicates the number of active threads minus parallelism (probably the number of CPUs)
The TC represents the total number of threads minus the degree of parallelism
St Indicates whether the thread pool itself is active
The EC represents the number of pending threads at the top
ID represents the poolindex of the top waiting thread
Obviously St+ec+id is the eventcount we just talked about.
So why is it obvious that 5 variables have to be synthesized? In fact, using 5 variables to occupy the same capacity.
The readability of a variable code can be much worse.
So why use a variable? In fact this is the most ingenious place, because these 5 variables are a whole, in multiple threads, if you use 5 variables, then when modifying one of the variables, how to ensure the integrity of 5 variables. Then the problem is solved by using a variable. If resolved with a lock, performance is reduced.
Using a variable ensures the consistency and atomicity of the data.
The changes in the Forkjoin Squadron CTL are all based on CAs, and as already described in the previous series, CAS is a lock-free operation and performs well.
Because CAS operations can only be targeted at one variable, this design is optimal.
4.4.2. Job Theft
Next, we'll describe the workflow for the entire thread pool.
Each thread will call Runworker
final void Runworker (Workqueue w) {
w.growarray ();//Allocate queue for
(int r = w.hint; Scan (W, r) = = 0;) {
R ^= R << R ^= R >>> R ^= R << 5;//Xorshift
}
}
The scan () function is to scan for a task to do.
R is a relatively random number.
Private final int Scan (workqueue w, int r) {workqueue[] ws; int m; Long C = CTL; For consistency check if ((ws = workqueues)!= null && (M = ws.length-1) >= 0 && w!= null) {F or (int j = m + M + 1, ec = w.eventcount;;) {workqueue q; int B, E; Forkjointask<?>[] A;
Forkjointask<?> T; if (q = ws[(r-j) & M)!= null && (b = q.base)-q.top < 0 && (a = Q.array)!= null) {lon
G i = ((a.length-1) & B) << Ashift) + abase; if ((t = ((forkjointask<?>) U.getobjectvolatile (A, i))!= null) {if (EC < 0) Helprelease (c, WS, W, q
, b);
else if (q.base = = b && u.compareandswapobject (A, I, T, null)) {u.putorderedint (q, qbase, B + 1);
if ((b + 1)-q.top < 0) signalwork (WS, Q);
W.runtask (t);
}} break; else if (--j < 0) {if (EC | (e = (int) c))
< 0)//Inactive or terminating return Awaitwork (W, c, EC); else if (ctl = = C) {//try to inactivate and enqueue long NC = (long) EC | ((C-ac_unit) & (ac_mask|
Tc_mask));
W.nextwait = e; W.eventcount = EC |
Int_sign; if (!u.compareandswaplong (this, CTL, C, NC)) W.eventcount = EC;
Back out} break;
}} return 0;
}
Let's take a look at the scan method, one of the parameters of scan is Workqueue, which has already said that each thread will have a workqueue, then the workqueue of multiple threads will be stored in the Workqueues, R is a random number, Through R to find a Workqueue, in the Workqueue have to do the task.
The base offset is then obtained by Workqueue base.
b = Q.base
..
Long i = ((a.length-1) & B) << Ashift) + abase;
..
Then get the last task through the offset, run this task
T = ((forkjointask<?>) U.getobjectvolatile (A, i))
..
W.runtask (t);
..
Understanding the process through this approximate analysis, we find that the current thread calls the scan method and does not perform the tasks in the current workqueue, but rather through a random number R to other workqueue tasks. This is one of the main mechanisms of forkjoinpool.
The current thread does not focus only on its own tasks, but on other tasks as a priority. To do so, to prevent the occurrence of hunger phenomenon. This prevents some threads from being able to complete the task in time because of the card death or other reasons, or if a thread has a large number of tasks, and other threads have nothing to do.
And then look at the Runtask method.
final void Runtask (forkjointask<?> task) {
if (currentsteal = task)!= null) {
Forkjoinworkerthread thread ;
Task.doexec ();
Forkjointask<?>[] A = array;
int MD = mode;
++nsteals;
Currentsteal = null;
if (MD!= 0)
pollandexecall ();
else if (a!= null) {
int s, m = a.length-1;
Forkjointask<?> T;
while ((s = top-1)-base >= 0 &&
(t = (forkjointask<?>) u.getandsetobject
(A, ((M & S) &l t;< Ashift) + abase, NULL)!= null) {top
= s;
T.doexec ();
}
if (thread = owner)!= null)//No need to does in finally clause
thread.aftertoplevelexec ();
}
There is an interesting name: Currentsteal, the stolen task, is indeed just explained.
Task.doexec ();
This task will be completed.
When you have finished someone else's task, you will accomplish your task.
Get top for the first task of your task
while ((s = top-1)-base >= 0 && (t = (forkjointask<?>) U.getandsetobject (A, ((M & s) << Ashi FT) + abase, NULL)!= null)
{top
= s;
T.doexec ();
}
Next, a graph is used to summarize the process of the following just thread pool
For example, with a t1,t2 of two threads, T1 will get the last task of T2 through T2 base (which is, of course, a random number R to get the last task of a thread), and T1 will perform his first task through its top. Conversely, T2 will do the same.
The task of taking other threads is to start from base, take your own task is from top start to take. This will reduce conflict
If no other tasks are found
else if (--j < 0) {
if (EC | (e = (int) c)) < 0)//Inactive or terminating return
awaitwork (W, c, EC);
else if (ctl = c) { //try to inactivate and enqueue
long NC = (long) EC | ((C-ac_unit) & (ac_mask| Tc_mask));
w.nextwait = e;
W.eventcount = EC | Int_sign;
if (!u.compareandswaplong (this, CTL, C, NC))
w.eventcount = EC;
The first step is to change the value of the CTL through a series of runs, get the NC, and then assign the new value in CAs. The Awaitwork () is then invoked to enter the thread into the wait state (the unsafe park method referred to in the previous series of calls).
The point here is to change the CTL value here, first of all, the AC-1,AC in the CTL is the first 16 bits of the CTL, so it is not direct-1, but through Ac_unit (0x1000000000000) to the first 16-bit-1 effect of the CTL.
As mentioned earlier in the EventCount, there are save Poolindex, through Poolindex and nextwait in Workqueue, you can traverse all the waiting threads.