Chapter 2 Executors source code parsing and executors source code

Source: Internet
Author: User

Chapter 2 Executors source code parsing and executors source code

The first two chapters introduce the usage, working mechanism, parameters, and core source code analysis of ThreadPoolExecutor in the basic thread pool.

For details, refer:

Chapter 2 ThreadPoolExecutor usage and working mechanism

Chapter 3 ThreadPoolExecutor source code analysis

1. Executors and ThreadPoolExecutor

  • ThreadPoolExecutor
    • Flexible and customizable thread pool Creation
    • It is difficult to create a proper thread pool.
    • A little effort
    • Rarely used
  • Executors
    • Four thread pools can be created. These four thread pools basically cover all requirements. You can choose them based on business characteristics in the future.
    • Easy to use
    • Very common in practice

Usage:

Package com. collection. test; import java. util. concurrent. executor; import java. util. concurrent. executors; public class ThreadPoolExecutorTest {// private static ThreadPoolExecutor executor = new ThreadPoolExecutor (5, 10, 30, TimeUnit. SECONDS, new ArrayBlockingQueue <Runnable> (10); // private static Executor executor = Executors. newFixedThreadPool (5); // private static Executor executor = Executors. newSi NgleThreadExecutor (); // private static Executor executor = Executors. newCachedThreadPool (); private static Executor executor = Executors. newScheduledThreadPool (5); public void executeTask () {Task1 task1 = new Task1 (); // build Task 1 Task2 task2 = new Task2 (); // build Task 2 executor.exe cute (task1); // execute Task 1 executor.exe cute (task2 ); // execute Task 2}/** Basic Task 2 */class Task1 implements Runnable {public void run () {// job of a specific task For (int I = 0; I <1000; I ++) {System. out. println ("hello xxx !!! ") ;}}/ ** Basic Task 2 */class Task2 implements Runnable {public void run () {// business of a specific task for (int I = 0; I <5; I ++) {System. out. println ("hello world2 !!! ") ;}} Public static void main (String [] args) {ThreadPoolExecutorTest test = new ThreadPoolExecutorTest (); test.exe cuteTask ();}}View Code

 

2. Introduction to several thread pools that Executors can create

  • NewFixedThreadPool (int corePoolSize)
    • Create a thread pool with a fixed number of threads (corePoolSize = maximumPoolSize)
    • The core thread will always run
    • Unbounded queue blockingqueue
  • NewSingleThreadExecutor
    • Create a thread pool with a fixed number of threads (corePoolSize = maximumPoolSize = 1)
    • The core thread will always run
    • Unbounded queue blockingqueue
    • All tasks are executed in serial mode (that is, only one task is executed at the same time)
  • NewCachedThreadPool
    • CorePoolSize = 0
    • MaximumPoolSize = Integer. MAX_VALUE
    • Queue: SynchronousQueue
    • Create a thread pool: When all threads in the pool are busy, a new thread is created immediately to process new tasks.
    • This pool will improve program performance when executing many short asynchronous tasks.
    • Threads not used within 6 seconds will be aborted and removed from the thread pool, so there is almost no need to worry about resource consumption.
  • NewScheduledThreadPool (int corePoolSize)
    • A scheduled or delayed execution task. The most typical example is the time-out callback during asynchronous operations.

Note:: For the execution of scheduled tasksUse spring timer, Very convenient

 

3. newFixedThreadPool (int corePoolSize)

Source code:

/*** 1. Create a thread pool with a fixed number of threads (corePoolSize = maximumPoolSize, * 2. Core threads will always run * 3. Unbounded queues */public static ExecutorService newFixedThreadPool (int nThreads) {return new ThreadPoolExecutor (nThreads, nThreads, 0L, TimeUnit. MILLISECONDS, new LinkedBlockingQueue <Runnable> ());}View Code

(Execute () Source Code view chapter 13th ThreadPoolExecutor source code parsing)

 

4. newSingleThreadExecutor ()

Source code:

/*** 1. Create a thread pool with a fixed number of threads (corePoolSize = maximumPoolSize = 1). * 2. The core thread will always run. * 3. the unbounded queue contains blockingqueue *. Note: all tasks are executed serially */public static ExecutorService newSingleThreadExecutor () {return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor (1, 1, 0L, TimeUnit. MILLISECONDS, new LinkedBlockingQueue <Runnable> ()));}View Code

(Execute () Source Code view chapter 13th ThreadPoolExecutor source code parsing)

 

5. newCachedThreadPool ()

Source code:

/*** 1. Create a thread pool: When all threads in the pool are busy, A new thread will be created immediately to process new tasks * 2. This pool will improve program performance when executing many short asynchronous tasks. * Threads not used within 3 or 6 seconds will be aborted and removed from the thread pool, so there is almost no need to worry about resource consumption * 4. queue: SynchronousQueue * 5 and maximumPoolSize is Integer. MAX_VALUE */public static ExecutorService newCachedThreadPool () {return new ThreadPoolExecutor (0, Integer. MAX_VALUE, 60L, TimeUnit. SECONDS, new SynchronousQueue <Runnable> ());}View Code

(Execute () Source Code view chapter 13th ThreadPoolExecutor source code parsing)

 

6. newScheduledThreadPool (int corePoolSize)

Source code:

Executors: newScheduledThreadPool (int corePoolSize)

/*** Create a thread pool: This thread pool can be used to execute delayed tasks or scheduled tasks */public static ScheduledExecutorService newScheduledThreadPool (int corePoolSize) {return new ScheduledThreadPoolExecutor (corePoolSize );}View Code

ScheduledThreadPoolExecutor: ScheduledThreadPoolExecutor (int corePoolSize)

/*** Create a thread pool: * corePoolSize = We specify * maximumPoolSize = Integer. MAX_VALUE * keepAliveTime = 0 nanoseconds (that is, do not recycle Idle threads) * queue: DelayedWorkQueue */public ScheduledThreadPoolExecutor (int corePoolSize) {super (corePoolSize, Integer. MAX_VALUE, 0, TimeUnit. NANOSECONDS, new DelayedWorkQueue ());}View Code

Note: ScheduledThreadPoolExecutor is a subclass of ThreadPoolExecutor. The super constructor called is the constructor of ThreadPoolExecutor.

ScheduledThreadPoolExecutor: execute (Runnable command)

Public void execute (Runnable command) {if (command = null) throw new NullPointerException (); schedule (command, 0, TimeUnit. NANOSECONDS );}View Code

ScheduledThreadPoolExecutor: schedule (Runnable command, long delay, TimeUnit unit)

/*** This method: encapsulate the task and add it to DelayedWorkQueue. * 1. DelayedWorkQueue is actually a DelayQueue. * 2. When a new task is added, delayQueue will add it to the internal array object and sort it. Here, the sorting rule is the execution time, the execution time is closer to the top * 3. When a thread in the thread pool executes a task, it gets the most recent task to be executed, then wake up all threads waiting for the available condition to execute this task */public ScheduledFuture <?> Schedule (Runnable command, long delay, TimeUnit unit) {if (command = null | unit = null) throw new NullPointerException (); RunnableScheduledFuture <?> T = decorateTask (command, new ScheduledFutureTask <Void> (command, null, triggerTime (delay, unit); delayedExecute (t); return t ;}View Code

Note: The comment here is the execution mechanism of the entire ScheduledThreadPoolExecutor.

 

The following describes some methods called.

Part 1: encapsulate ScheduledFutureTask

ScheduledThreadPoolExecutor: triggerTime (long delay, TimeUnit unit)

/*** Return the trigger time of a delayed action (delayed task) */private long triggerTime (long delay, TimeUnit unit) {return triggerTime (unit. toNanos (delay <0 )? 0: delay);}/*** Returns the trigger time of a delayed action. */long triggerTime (long delay) {return now () + (delay <(Long. MAX_VALUE> 1 ))? Delay: overflowFree (delay ));}View Code

Description: used to calculate the trigger time of a delayed task.

Note: The delay passed in the execute () method above is 0. According to the code above, the trigger time is now ().

ScheduledThreadPoolExecutor: internal class ScheduledFutureTask

Private class ScheduledFutureTask <V> extends FutureTask <V> implements RunnableScheduledFuture <V> {private final long sequenceNumber; // The serial number used to break the FIFO relationship. private long time; // trigger time of task execution/*** the time period of a task for repeated execution (unit: nanoseconds) * 0 --> tasks not repeated * positive value: fixed-rate execution * negative value: fixed-delay execution */private final long period;/*** create a one-time action and specify the trigger time */ScheduledFutureTask (Runnable r, V result, long ns) {super (r, result); this. time = ns; this. period = 0; this. sequenceNumber = sequencer. getAndIncrement ();}View Code

Note: ScheduledFutureTask is a subclass of FutureTask. The super (r, result) code in the constructor above is as follows:

FutureTask: FutureTask (Runnable runnable, V result)

Private final Sync sync; // control the synchronization of FutureTask public FutureTask (Runnable runnable, V result) {sync = new Sync (Executors. callable (runnable, result ));}View Code

Executors: callable (Runnable task, T result)

Public static <T> Callable <T> callable (Runnable task, T result) {if (task = null) throw new NullPointerException (); return new RunnableAdapter <T> (task, result );}View Code

Executors: internal class RunnableAdapter

Static final class RunnableAdapter <T> implements Callable <T> {final Runnable task; final T result; RunnableAdapter (Runnable task, T result) {this. task = task; this. result = result;} public T call () {task. run (); // return result where the real task runs ;}}View Code

Note: This is where the task actually runs. --> Task. run ()

So far, the ScheduledFutureTask is encapsulated.

 

Part 2: modify a task

ScheduledThreadPoolExecutor: RunnableScheduledFuture

Protected <V> RunnableScheduledFuture <V> decorateTask (Runnable runnable, RunnableScheduledFuture <V> task) {return task ;}View Code

Note: The encapsulated task is returned directly.

 

Part 3: Add delayed tasks to the blocked queue

ScheduledThreadPoolExecutor: delayedExecute (Runnable command)

Private void delayedExecute (Runnable command) {if (isShutdown () {// return runState! = RUNNING; the thread pool status is not RUNNING reject (command); // return;} if (getPoolSize () <getCorePoolSize ()) // The number of current thread pools is less than the number of core threads prestartCoreThread (); // create and start a Core Thread super. getQueue (). add (command); // get the blocking queue and add the command to the queue}View Code

Note: after this, the encapsulated task is added to the delayed queue DelayQueue (a subclass of the blocking Queue)

DelayQueue: add (E e)

Public boolean add (E e) {return offer (e);} public boolean offer (E e) {final ReentrantLock = this. lock; lock. lock (); try {E first = q. peek (); // get the queue header node but do not delete q. offer (e); // put e to the end of q. // if only e or e in the queue has a trigger time less than the header node if (first = null | e. compareTo (first) <0) available. signalAll (); return true;} finally {lock. unlock ();}}View Code

Note: In this method, the encapsulated task is added to the DelayQueue, and the task is placed in the queue header. Then, all threads waiting for the available condition are awakened to execute the task.

 

Summary:

  • The four most common thread pools are newCachedThreadPool and newFixedThreadPool (int corePoolSize)
  • NewScheduledThreadPool (int corePoolSize) is rarely used, because in modern development, it is very easy to use spring timer if it is used to develop scheduled task programs.

 

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.