In the threading model of the hotspot VM, Java threads are mapped one-to-one to local operating system threads. The Java thread creates a local operating system thread when it is started, and the operating system thread is reclaimed when the Java thread terminates, and in the JVM we can set the size of each thread by-XSS. The operating system schedules all threads and assigns them to the available CPUs.
on the top, Java multithreaded routines typically decompose applications into several tasks, and then use user-level schedulers (the executor framework) to map these tasks to a fixed number of threads, and at the bottom, the operating system kernel maps These threads to hardware processors. The schematic diagram of this two-stage scheduling model is shown in the following figure
The above diagram shows that the application controls the upper level scheduling through executor, and the operating system kernel controls the lower scheduling.
Note: The Oskernel operating system core includes operating system software and applications, only the most basic functions of the operating system, such as memory management, process management, hardware drivers, etc. executor structure
The
Executor structure consists primarily of tasks, the execution of tasks, and the calculation of asynchronous results.
Tasks
include the interfaces that are implemented by the tasks that are performed: the Runnable interface or the callable Interface
Task execution
includes the core interface of the task execution mechanism executor, And a Executorservice interface that inherits from executor. The executor framework has two key classes that implement the Executorservice interface (Threadpoolexecutor and Scheduledthreadpoolexecutor)
Results of asynchronous computations
Include the interface future and the Futuretask class that implements the future interface
Let's take a look at the Executor class diagram
during executor use, The main thread first creates a task object that implements the Runnable or callable interface. The tool class executors can encapsulate a Runnable object as a callable object (executors.callable (Runnable Task) or executors.callable (Runnable task, Object resule)).
If the Executorservice.submit (...) is executed. ), Executorservice returns an object (Futuretask) that implements the future interface. As Futuretask implements Runnable, we can also create futuretask, and then directly to Executorservice execution. Finally, the main thread can execute the Futuretask.get () method to wait for task execution to complete. The main thread can also perform Futuretask.cancel (Boolean mayinterruptifrunning) to cancel the execution of this task. Fixedthreadpool Initialize
public static Executorservice newfixedthreadpool (int nthreads) {return
new Threadpoolexecutor (Nthreads, Nthreads,
0L, Timeunit.milliseconds,
new linkedblockingqueue<runnable> ());
public static Executorservice newfixedthreadpool (int nthreads, threadfactory threadfactory) {return
new Threadpoolexecutor (Nthreads, Nthreads,
0L, Timeunit.milliseconds,
new linkedblockingqueue<runnable> (),
threadfactory);
}
The Corepoolsize and maximumpoolsize of Fixedthreadpool are set to the parameter nthreads specified when the Fixedthreadpool is created. When the number of threads in the thread pool is greater than corepoolsize, the maximum time KeepAliveTime waits for the new task for the extra idle thread, and the extra thread is terminated after that time. This sets the KeepAliveTime to 0L, meaning that extra idle threads will be terminated immediately.
The following is a schematic diagram of the fixedthreadpool running process
1. If the number of threads currently running is less than corepoolsize, a new thread is created to perform the task.
2. After the online pool finishes preheating (the number of threads currently running equals Corepoolsize), add the task to Linkedblockingqueue.
3, the thread after the completion of the task in 1, will be repeatedly in the loop from the Linkedblockingqueue to get the task to execute.
Fixedthreadpool uses a unbounded queue linkedblockingqueue a work queue as a thread pool (the capacity of the queue is Integer.max_value). Using a unbounded queue as a work queue can have the following effects on the thread pool
1. When the number of threads in the thread pool reaches corepoolsize, the new task waits in the unbounded queue, so the number of threads in the thread pool does not exceed corepoolsize.
2. Because of 1, maximumpoolsize will be an invalid parameter when using a unbounded queue.
3, because of 1 and 2, KeepAliveTime will be an invalid parameter when using a unbounded queue.
4. Due to the use of unbounded queues, the Fixedthreadpool (not executed method shutdown () or Shutdownnow () does not reject the task (the Rejectedexecutionhandler.rejectedexecution method is not invoked). Working with scenes
Fixedthreadpool applies to scenarios that need to limit the number of current threads in order to meet resource management requirements, and it applies to load-heavy servers singlethreadexecutor initialization
Create a singlethread-executor that uses a single thread
public static Executorservice Newsinglethreadexecutor () {return
new Finalizabledelegatedexecutorservice
( New Threadpoolexecutor (1, 1,
0L, Timeunit.milliseconds,
new Linkedblockingqueue<runnable> ()));
public static Executorservice Newsinglethreadexecutor (Threadfactory threadfactory) {return
new Finalizabledelegatedexecutorservice
(New Threadpoolexecutor (1, 1,
0L, Timeunit.milliseconds,
New) Linkedblockingqueue<runnable> (),
threadfactory));
The Singlethreadexecutor corepoolsize and Maximumpoolsize are set to 1. Other parameters are the same as Fixedthreadpool. Singlethreadexecutor uses a unbounded queue linkedblockingqueue a work queue as a thread pool (the capacity of the queue is Integer.max_value). Singlethreadexecutor use of unbounded queues as work queues affect the thread pool the same run process as Fixedthreadpool
The diagram below is a schematic diagram of the Singlethreadexecutor's operating process
1. If the number of currently running threads is less than corepoolsize (that is, threads that are not running in the thread pool), a new thread is created to perform the task.
2. After the online pool finishes preheating (there is a running thread in the current thread pool), add the task to Linkedblockingqueue.
3, the thread after the completion of the task in 1, will be in an infinite loop repeatedly from the linkedblockingqueue to get the task to execute. Working with scenes
Singlethreadexecutor applies to tasks that need to be guaranteed sequentially, and at any point in time, no more than one thread is an active application scenario. Cachedthreadpool Initialization of
public static Executorservice Newcachedthreadpool () {return new Threadpoolexecutor (0, I Nteger. Max_value, 60L, Timeunit.seconds, new Synchron
Ousqueue<runnable> ()); public static Executorservice Newcachedthreadpool (Threadfactory threadfactory) {return new Threadpoolexecutor (0 , Integer.max_value, 60L, Timeunit.seconds, NE
W synchronousqueue<runnable> (), threadfactory); }
The corepoolsize of the
Cachedthreadpool is set to 0, that is, the Corepool is empty, and the maximumpoolsize is set to Integer.max_value, that is, the maximumpool is unbounded. Setting the KeepAliveTime to 60L means that the idle thread in Cachedthreadpool waits for a new task for a maximum time of 60 seconds, and the idle thread is terminated after 60 seconds. The
Fixedthreadpool and Singlethreadexecutor use the unbounded queues Linkedblockingqueue as the thread pool's Task force columns. Cachedthreadpool uses synchronousqueue with no capacity as the work queue for the thread pool, but Cachedthreadpool Maximumpool is unbounded. This means that if the main thread commits the task faster than the Maximumpool thread processing task, Cachedthreadpool will keep creating new threads. In extreme cases, Cachedthreadpool will run out of CPU and memory resources because of the creation of multithreading. Run procedure
The following illustration is a schematic diagram of the cachedthreadpool running process
1, which first executes the Synchronousqueue.offer (Runnable Task). If an idle thread in the current maximumpool is executing synchronousqueue.poll (keepalivetime,timeunit.nanoseconds), then the main thread performs the offer operation paired with the poll operation performed by the idle thread, and the main thread The Execute () method completes the execution of the idle thread, otherwise follow step 2 below.
2, when the initial maximumpool is empty, or if there are currently no idle threads in Maximumpool, no thread executes Synchronousqueue.poll
(KeepAliveTime, Timeunit.nanoseconds). In this case, step 1 will fail. At this point cachedthreadpool creates a new thread to perform the task and the Execute () method completes.
3, in step 2, after the newly created thread finishes executing the task, executes Synchronousqueue.poll (KeepAliveTime,
Timeunit.nanoseconds). This poll operation will allow the idle thread to wait for up to 60 seconds in the Synchronousqueue. If the main thread commits a new task in 60 seconds (the main thread executes step 1), the idle thread will perform the new task of the main thread submission, otherwise the idle thread will terminate. Because idle threads that are idle for 60 seconds are terminated, cachedthreadpool that remain idle for a long time will not use any resources. As mentioned earlier in the
, Synchronousqueue is a blocking queue with no capacity. Each insert operation must wait for a corresponding removal from another thread, and vice versa. Cachedthreadpool uses Synchronousqueue to pass the task submitted by the main thread to the idle thread for execution. A schematic diagram of the task passing in Cachedthreadpool is shown in the following illustration:
using the scene
Look at the name. Cached cache, Cachedthreadpool can create a thread pool that can create new threads as needed, but they are reused when previously constructed threads are available, and these thread pools typically improve program performance for programs that perform many short asynchronous tasks. Calling execute reuses the previously constructed thread (if the thread is available). If an existing thread is not available, create a new thread and add it to the pool.
Cachedthreadpool is a large, unbounded thread pool for small programs that perform many short asynchronous tasks, or for lighter-load servers. Scheduledthreadpoolexecutor
Scheduledthreadpoolexecutor inherits from Threadpoolexecutor. It is primarily used to run tasks after a given delay, or to perform tasks on a regular basis. The Scheduledthreadpoolexecutor function is similar to a timer, but the Scheduledthreadpoolexecutor is more powerful and flexible. The timer corresponds to a single background thread, and scheduledthreadpoolexecutor can specify multiple background threads to initialize in the constructor
Scheduledthreadpoolexecutor are typically created using the factory class executors. Executors can create 2 types of
Scheduledthreadpoolexecutor, as follows.
Scheduledthreadpoolexecutor: A scheduledthreadpoolexecutor that contains several threads.
Singlethreadscheduledexecutor: Contains only one thread of scheduledthreadpoolexecutor.
These two kinds of scheduledthreadpoolexecutor are described below.
Public scheduledthreadpoolexecutor (int corepoolsize,
threadfactory threadfactory,
Rejectedexecutionhandler handler) {
super (corepoolsize, Integer.max_value, 0, Timeunit.nanoseconds,
new Delayedworkqueue (), threadfactory, handler);
Public scheduledthreadpoolexecutor (int corepoolsize) {
super (corepoolsize, Integer.max_value, 0, Timeunit.nanoseconds,
new Delayedworkqueue ());
Invoke the parent class Threadpoolexecutor constructor directly for initialization. Scheduledthreadpoolexecutor applies to scenarios that require multiple background threads to perform cycle tasks while limiting the number of background threads in order to meet resource management requirements.
Let's see how to create a Singlethreadscheduledexecutor
public static Scheduledexecutorservice Newsinglethreadscheduledexecutor () {return
new Delegatedscheduledexecutorservice
(New Scheduledthreadpoolexecutor (1));
}
public static Scheduledexecutorservice Newsinglethreadscheduledexecutor (Threadfactory threadfactory) {return
New Delegatedscheduledexecutorservice
(new Scheduledthreadpoolexecutor (1, threadfactory));
}
Run Process
The
Delayqueue is an unbounded queue, So Threadpoolexecutor's maximumpoolsize has no meaning in scheduledthreadpoolexecutor (setting the size of maximumpoolsize has no effect). The implementation of Scheduledthreadpoolexecutor is mainly divided into two parts.
1, when the Scheduledthreadpoolexecutor scheduleatfixedrate () method or Schedulewithfixeddelay () method is invoked, Adds a scheduledfuturetask that implements the Runnablescheduledfutur interface to the Scheduledthreadpoolexecutor delayqueue.
2, the thread in the thread pool gets scheduledfuturetask from the Delayqueue, and then executes the task.
Take a look at the scheduedthreadpoolexecutor running process diagram
Scheduledthreadpoolexecutor in order to perform periodic tasks, The following
modifications were made to the threadpoolexecutor.
1, using Delayqueue as the task queue.
2, the way to get the task is different (described later).
3, after the execution of the cycle task, additional processing is added (which is explained later). implementing process Profiling
The
Scheduledthreadpoolexecutor puts the task to be scheduled (Scheduledfuturetask) in a delayqueue. The Scheduledfuturetask consists primarily of 3 member variables, as follows.
1, long, indicating when the task will be executed.
2, long sequencenumber, indicating the number of the task being added to the scheduledthreadpoolexecutor.
3, long period, which represents the interval between the execution of a task. The
Delayqueue encapsulates a priorityqueue that priorityqueue the scheduledfuturetask in the queue. When sorting, time is small in front (the task will be executed first). If the time of the two scheduledfuturetask is the same, the smaller one is sequencenumber,sequencenumber (that is, if the two tasks have the same execution times, the first task will be executed first). First, let's look at the process of thread execution cycle tasks in Scheduledthreadpoolexecutor. The following illustration shows
1, thread 1 gets the expired Scheduledfuturetask (Delayqueue.take ()) from Delayqueue. The expiration task refers to scheduledfuturetask time greater than or equal to the current period.
2, Thread 1 executes this scheduledfuturetask.
3, Thread 1 modifies the time variable for the Scheduledfuturetask to the next period that will be executed.
4, Thread 1 puts the scheduledfuturetask after this modified time back into Delayqueue (Delayqueue.add ()).
Let's see how the source code for Delayqueue.take () is implemented
public E Take () throws Interruptedexception {final Reentrantlock lock = This.lock; Lock.lockinterruptibly (); 1 try {for (;;)
{E-A-q.peek (); if (A/= null) {available.await ();//2.1} else {long delay
= First.getdelay (timeunit.nanoseconds);
if (Delay > 0) {Long TL = Available.awaitnanos (delay);//2.2} else { E x = Q.poll ();
2.3.1 assert x!= null; if (q.size ()!= 0) Available.signalall ();
2.3.2 return x; finally {lock.unlock ();//3}}}}}}
We'll show you the code below with a flowchart.
1, get lock.
2, get the cycle task.
A, if the priorityqueue is empty, the current thread waits in the condition; otherwise executes the following 2.2.
b, if the time of the Priorityqueue header element is larger than the current time, wait until the time in the condition, otherwise execute the following 2.3.
C, gets the Priorityqueue header element (2.3.1), and wakes all threads (2.3.2) waiting in the condition if Priorityqueue is not empty.
3, Release lock.
Scheduledthreadpoolexecutor executes step 2 in a loop until the thread is fetched from Priorityqueue to an element (after executing 2.3.1) to exit the infinite loop (end Step 2).
Let me take a look at the Delayqueue.add () source code implementation
Public Boolean offer (E e) {
final reentrantlock lock = This.lock;
Lock.lock (); 1
try {
E-i = Q.peek ();
Q.offer (e); 2.1
if (a null | | E.compareto (a) < 0)
Available.signalall ();//2.2 return
true;
} finall y {
lock.unlock ();//3
}
}
We'll show you the code below with a flowchart.
1, get lock.
2, add the task.
A, add tasks to Priorityqueue.
b, if the task added in above 2.1 is the Priorityqueue header element, wake up all threads waiting in the condition.
3, Release lock. Working with scenes
Singlethreadscheduledexecutor applies to scenarios that require a single background thread to perform periodic tasks, and that require the sequential execution of tasks.