In layman Java Concurrency (33): Thread pool Part 6 thread pool implementation and principle (1) [Go]

Source: Internet
Author: User

Thread pool data structure and threading construction method

Since we have seen the Threadpoolexecutor source code, it is easy to see the data structure of the threadpoolexecutor thread pool. Figure 1 depicts this data structure.

Figure 1 Threadpoolexecutor data structure

In fact, even without the above figure describing the Threadpoolexecutor data structure, we are able to guess its data structures according to the requirements of the thread pool.

    • The thread pool needs to support concurrent execution of multiple threads, so there is a thread collection collection<thread> to perform thread tasks;
    • involves asynchronous execution of a task, so a collection is required to cache the task queue collection<runnable>;
    • Obviously coordinating multiple tasks across multiple threads requires a thread-safe set of tasks while supporting blocking and timeout operations, so blockingqueue is essential;
    • Since it is a thread pool, the starting point is to improve system performance and reduce resource consumption, then the size of the thread pool is limited, so there needs to be a core thread pool size (number of threads) and a maximum thread pool size (number of threads), there is a count to describe the current thread pool size;
    • If it is a finite thread pool size, then thread resources that are not used for a long time should be destroyed, which requires a count of the thread's idle time to describe when the thread was destroyed;
    • The previous description of the thread pool is also life-cycle, so a state is required to describe the current running state of the thread pool;
    • Thread Pool Task Queue If there is a boundary, then there is a task rejection policy to handle too many tasks, while the online pool destruction phase also requires a task rejection policy to handle the newly added tasks;
    • The size of the thread pool, the threads idle actual, the running state and so on are not thread-safe, so we need a global lock (mainlock) to coordinate these competing resources;
    • In addition to the above data structure, Threadpoolexecutor has some state to describe the run count of the thread pool, such as the number of tasks that the thread pool runs, the maximum number of threads ever reached, and is used primarily for debugging and profiling.

For Threadpoolexecutor, a thread is a worker object, which is bound to a thread, and when the worker finishes executing the thread, this discusses in detail how the thread pool threads run.

Since it is a thread pool, the method of constructing the thread is first studied.

Public interface Threadfactory {
Thread Newthread (Runnable R);
}

Threadpoolexecutor constructs a thread using a thread factory. The thread pool commits a task runnable, and then executes it in thread thread, Threadfactory is responsible for creating a new thread.

There is a generic thread factory java.util.concurrent.Executors.DefaultThreadFactory in J.u.c, which is constructed as follows:

Static Class Defaultthreadfactory implements Threadfactory {
Static final Atomicinteger Poolnumber = new Atomicinteger (1);
Final Threadgroup Group;
Final Atomicinteger threadnumber = new Atomicinteger (1);
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;
}
}

In this thread factory, all the threads of the same thread pool belong to the same group of threads, that is, the thread pool that created it, and the thread pool name is "pool-<poolnum>-thread-<threadnum>". Where Poolnum is the number of thread pool numbers, Threadnum is the number of threads in this thread pool. This makes it easy to see the number of thread pools in the system and the number of threads in the threading pool if you use Jstack. In addition, all threads in the thread pool are converted to non-background threads by default so that the main thread exits without directly exiting the JVM, but instead waits for the thread pool to end. Also, by default, all threads in the thread pool are tuned to the same level, so that all systems are fair at the operating system point of view and do not result in a competitive build-up.

Thread Pool threads life cycle

When a thread worker is constructed, it starts running. The following is a simple version of the logic that a thread executes.

Private Final class Worker implements Runnable {
Private final Reentrantlock Runlock = new Reentrantlock ();
Private Runnable Firsttask;
Thread thread;
Worker (Runnable firsttask) {
This.firsttask = Firsttask;
}
private void RunTask (Runnable task) {
Final Reentrantlock runlock = This.runlock;
Runlock.lock ();
try {
Task.run ();
} finally {
Runlock.unlock ();
}
}
public void Run () {
try {
Runnable task = Firsttask;
Firsttask = null;
while (task! = NULL | | (Task = Gettask ()) = null) {
RunTask (Task);
task = null;
}
} finally {
Workerdone (this);
}
}
}

When a task is submitted, if a thread needs to be created (when it needs to be explored in the next section), the thread factory is called to create a thread, and the thread is bound to the worker work queue. It is necessary to note that the worker queue is constructed with a task runnable, so the worker is always bound to a pending task when it is created. In other words, the premise of creating a thread is that it is necessary to create a thread (the number of tasks is already out of the thread or force a new thread to be created, and as to why forcing the creation of a new thread is analyzed later in the chapter), there is no reason to create a bunch of idle threads. This is a way to conserve resources.

Once the thread pool is started (calling the thread Run ()) method, the thread work queue worker starts execution from the 1th task (the benefit of passing a task when the worker is constructed), and once the 1th task is completed, the next task is taken from the thread pool's task queue. This loops until the thread pool is closed or the task throws a runtimeexception.

This shows that the basic principle of the thread pool is actually very simple, nothing more than pre-boot some threads, thread into the dead loop state, each time from the task queue to get a task to execute, until the thread pool is closed. If a thread terminates due to an exception executing a task, re-create a new thread. So repeated.

In fact, the thread pool principle looks simple, but the complex is a variety of strategies, such as when to start a thread, when to terminate, suspend, wake up a thread, task queue blocking and timeouts, the thread pool life cycle and the task rejection policy, and so on. These policy issues are examined in the next section.

Inside.java.concurrency 33.thread Pool.part6_threadfactory_workerView more documents from Xylz.

In layman Java Concurrency (33): Thread pool Part 6 thread pool implementation and principle (1) [Go]

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.