Java-"Juc thread pool" threading Status and Denial policy source code Analysis

Source: Internet
Author: User
Tags throw exception

Java Multithreading Series--"Juc thread pool" 04 thread pool principle (iii)

This chapter describes the life cycle of the thread pool. In the Java Multithreading Series-Basic concepts of 01, we've introduced threads in 5 states: New state, ready state, running state, blocking state, dead state. The thread pool also has 5 states; However, threads are different than threads, and the 5 states of the line pool are: Running, SHUTDOWN, STOP, tidying, TERMINATED.


The thread pool status definition code is as follows:

Private final Atomicinteger ctl = new Atomicinteger (Ctlof (RUNNING, 0));p rivate static final int count_bits = Integer.size -3;private static final int capacity = (1 << count_bits)-1;private static final int RUNNING = 1 << count_b its;private static final int SHUTDOWN = 0 << count_bits;private static final int STOP = 1 << count_bits;privat e static final int tidying = 2 << count_bits;private static final int TERMINATED = 3 << count_bits;private STA TIC int Ctlof (int rs, int wc) {return rs | wc;}

Description :
A CTL is an atomic object of type Atomicinteger. The CTL Records 2 information about the number of tasks in the thread pool and the thread pooling status.
The CTL consists of 32 bits in total. Where the high 3 bits represent the thread pool state, and the low 29 bits represent the number of tasks in the thread pool.

RUNNING    -the corresponding high 3-bit value is 111. SHUTDOWN   -the corresponding high 3-bit value is 000. STOP       -the corresponding high 3-bit value is 001. tidying    -the corresponding high 3-bit value is 010. TERMINATED -the corresponding high 3-bit value is 011.

The switch between the various states of the thread pool is as follows:

1. RUNNING

(01) Status Note: When the thread pool is in the running state, it is able to receive new tasks and process the added tasks.
(02) State Toggle: The initialization state of the thread pool is running. In other words, once the thread pool is created, it is in the running state!
The reason is simple, in the initialization code of the CTL (below), it is initialized to the running state, and "task number" is initialized to 0.

Private final Atomicinteger ctl = new Atomicinteger (Ctlof (RUNNING, 0));

2. SHUTDOWN

(01) Status Note: When the thread pool is in the shutdown state, it does not receive new tasks, but can handle the tasks that have been added.
(02) State Toggle: When invoking the SHUTDOWN () interface of the thread pool, the thread pool is running by SHUTDOWN.

3. STOP

(01) Status Description: When the thread pool is in the stop state, it does not receive new tasks, does not process the added tasks, and interrupts the task being processed.
(02) State toggle: When the Shutdownnow () interface of the thread pool is called, the thread pool is (RUNNING or SHUTDOWN), STOP.

4. Tidying
(01) Status Note: When all tasks are terminated, the number of tasks for the CTL record is 0, and the thread pool becomes tidying state. When the thread pool becomes tidying state, the hook function terminated () is executed. Terminated () is empty in the Threadpoolexecutor class and is handled appropriately if the user wants the online pool to be tidying, which can be implemented by overloading the terminated () function.
(02) State toggle: When the thread pool is in the SHUTDOWN state, the blocking queue is empty and the tasks performed in the thread pool are empty, it is SHUTDOWN-tidying.
When the thread pool is in the stop state, the task that is executed in the threads pools is empty, which is caused by stop---tidying.

5. TERMINATED
(01) Status Description: The thread pool is completely terminated and becomes terminated state.
(02) State toggle: When the thread pool is in tidying state, after executing TERMINATED (), it will be TERMINATED by tidying.

Introduction to Reject policies

The thread pool's deny policy refers to the actions taken when a task is added to the thread pool and is rejected.
When a task is added to the thread pool it is rejected, possibly because: first, the thread pool closes unexpectedly. Second, the number of tasks exceeds the maximum limit of the thread pool.

The thread pool consists of 4 rejection strategies, namely:abortpolicy, callerrunspolicy, discardoldestpolicy , and Discardpolicy.

AbortPolicy         --It throws a Rejectedexecutionexception exception when the task is added to the thread pool and is rejected. Callerrunspolicy     --When a task is added to the thread pool, the rejected task is processed in the thread pool that is currently running by the online pool.  --When the task is added to the thread pool for rejection, the thread pool discards the oldest unhandled task in the queue, and then adds the rejected task to the wait queue. Discardpolicy        --When a task is added to the thread pool and is rejected, the thread pool discards the rejected task.

The thread pool default processing policy is abortpolicy!

rejection policy comparisons and examples

The following example shows the 4 deny policies for the thread pool, respectively.
1. Discardpolicy Example
2. Discardoldestpolicy Example
3. AbortPolicy Example
4. Callerrunspolicy Example

1. Discardpolicy Example

 1 Import Java.lang.reflect.Field; 2 Import Java.util.concurrent.ArrayBlockingQueue; 3 Import Java.util.concurrent.ThreadPoolExecutor; 4 Import Java.util.concurrent.TimeUnit; 5 Import Java.util.concurrent.ThreadPoolExecutor.DiscardPolicy; 6 7 public class Discardpolicydemo {8 9 private static final int threads_size = 1;10 private static final int C apacity = 1;11 public static void Main (string[] args) throws Exception {13 14//Create thread pool. The maximum pool size and core pool size for the thread pool are 1 (threads_size), and the thread pool's blocking queue capacity is 1 (capacity).                 Threadpoolexecutor pool = new Threadpoolexecutor (threads_size, threads_size, 0, timeunit.seconds,16 New arrayblockingqueue<runnable> (capacity)); 17//Set the Deny policy for the thread pool to "discard" Pool.setrejectedexecutionha Ndler (New Threadpoolexecutor.discardpolicy ()); 19 20//Create a new 10 tasks and add them to the thread pool. for (int i = 0; i < i++) {Runnable myrun = new Myrunnable ("task-" +i);         Execute (myrun); 24}25//Close thread pool Pool.shutdown ();}28}29 class Myrunnable implements Runnable {+ Private stri ng name;32 Public myrunnable (String name) {this.name = name;34}35 @Override36 public void Run ( ) {PNs try {System.out.println (THIS.name + "is running"); Thread.Sleep (Exception e) {e.printstacktrace (); 42}43} 44}

Operation result :

Task-0 is Running.task-1 is running.

The result : The maximum pool size and core pool size for the thread pool pool are 1 (threads_size), which means that the maximum number of tasks that the thread pool can run concurrently is only 1.
The blocking queue for the thread pool pool is arrayblockingqueue,arrayblockingqueue is a bounded blocking queue with a capacity of 1 arrayblockingqueue. This also means that the thread pool's blocking queue can only have one thread pool blocking the wait.
According to the Execute () code analyzed in the, the thread pool runs 2 tasks. The 1th task is placed directly in the worker, executed through a thread, and the 2nd task is placed in the blocking queue. All the other tasks have been discarded!

2. Discardoldestpolicy Example

 1 Import Java.lang.reflect.Field; 2 Import Java.util.concurrent.ArrayBlockingQueue; 3 Import Java.util.concurrent.ThreadPoolExecutor; 4 Import Java.util.concurrent.TimeUnit; 5 Import Java.util.concurrent.ThreadPoolExecutor.DiscardOldestPolicy;  6 7 public class Discardoldestpolicydemo {8 9 private static final int threads_size = 1;10 private static final int capacity = 1;11 public static void Main (string[] args) throws Exception {13 14//Create thread pool. The maximum pool size and core pool size for the thread pool are 1 (threads_size), and the thread pool's blocking queue capacity is 1 (capacity).                 Threadpoolexecutor pool = new Threadpoolexecutor (threads_size, threads_size, 0, timeunit.seconds,16 New arrayblockingqueue<runnable> (capacity)); 17//Set the Deny policy for the thread pool to "Discardoldestpolicy" pool.setre Jectedexecutionhandler (New Threadpoolexecutor.discardoldestpolicy ()); 19 20//Create a new 10 tasks and add them to the thread pool.         for (int i = 0; i < i++) {Runnable myrun = new Myrunnable ("task-" +i); 23    Pool.execute (Myrun); 24}25//Close thread pool Pool.shutdown ();}28}29 class myrunnable imple     ments Runnable {$ private String name;32 public myrunnable (String name) {this.name = name;34}35 @Override36 public void Run () {PNs try {System.out.println (THIS.name + "is running."); Thread.Sleep (Exception e) {e.printstacktrace (); 42}43} 44}

Operation result :

Task-0 is running.task-9 is running.

result Note : After modifying the thread pool's deny policy from Discardpolicy to Discardoldestpolicy, when a task is added to the thread pool is rejected, the thread pool discards the task at the end of the blocking queue and then adds the rejected task to the end.

3. AbortPolicy Example

 1 Import Java.lang.reflect.Field; 2 Import Java.util.concurrent.ArrayBlockingQueue; 3 Import Java.util.concurrent.ThreadPoolExecutor; 4 Import Java.util.concurrent.TimeUnit; 5 Import Java.util.concurrent.ThreadPoolExecutor.AbortPolicy; 6 Import java.util.concurrent.RejectedExecutionException; 7 8 public class Abortpolicydemo {9 private static final int threads_size = 1;11 private static final int CAP acity = 1;12 public static void Main (string[] args) throws Exception {14 15//Create thread pool. The maximum pool size and core pool size for the thread pool are 1 (threads_size), and the thread pool's blocking queue capacity is 1 (capacity).                 Threadpoolexecutor pool = new Threadpoolexecutor (threads_size, threads_size, 0, timeunit.seconds,17 New arrayblockingqueue<runnable> (capacity)); 18//Set the Deny policy for the thread pool to "throw exception" pool.setrejectedexecution Handler (New Threadpoolexecutor.abortpolicy ()); try {22 23//Create a new 10 tasks and add them to the thread pool. (int i = 0; i < i++) {RunnAble Myrun = new myrunnable ("task-" +i); Pool.execute (Myrun);}28} catch (rejected         Executionexception e) {e.printstacktrace (); 30//Close thread pool Pool.shutdown (); 32  }33}34}35 class Myrunnable implements Runnable {Notoginseng private String name;38 public myrunnable (String name) {this.name = name;40}41 @Override42 public void Run () {# try {System.out. println (THIS.name + "is running."); Thread.Sleep (Exception e) {e.printstacktrace (); 48}49} 50}

Run results (one time) :

Java.util.concurrent.RejectedExecutionException at    java.util.concurrent.threadpoolexecutor$ Abortpolicy.rejectedexecution (threadpoolexecutor.java:1774) at    Java.util.concurrent.ThreadPoolExecutor.reject (threadpoolexecutor.java:768) at    Java.util.concurrent.ThreadPoolExecutor.execute (threadpoolexecutor.java:656) at    Abortpolicydemo.main ( ABORTPOLICYDEMO.JAVA:27) task-0 is running.task-1 is running.

result Description : After modifying the thread pool's deny policy from Discardpolicy to AbortPolicy, a rejectedexecutionexception is thrown when a task is added to the thread pool that is rejected.

4. Callerrunspolicy Example

 1 Import Java.lang.reflect.Field; 2 Import Java.util.concurrent.ArrayBlockingQueue; 3 Import Java.util.concurrent.ThreadPoolExecutor; 4 Import Java.util.concurrent.TimeUnit; 5 Import Java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy; 6 7 public class Callerrunspolicydemo {8 9 private static final int threads_size = 1;10 private static final in T capacity = 1;11 public static void Main (string[] args) throws Exception {13 14//Create thread pool. The maximum pool size and core pool size for the thread pool are 1 (threads_size), and the thread pool's blocking queue capacity is 1 (capacity).                 Threadpoolexecutor pool = new Threadpoolexecutor (threads_size, threads_size, 0, timeunit.seconds,16 New arrayblockingqueue<runnable> (capacity)); 17//Set the Deny policy for the thread pool to "Callerrunspolicy" Pool.setrejec Tedexecutionhandler (New Threadpoolexecutor.callerrunspolicy ()); 19 20//Create a new 10 tasks and add them to the thread pool. for (int i = 0; i < i++) {Runnable myrun = new Myrunnable ("task-" +i); ExeCute (myrun); 24}25 26//Close thread pool Pool.shutdown ();}29}30 class Myrunnable implements Run nable {name;33-myrunnable (string name) {this.name = name;35}36 @Overr Ide37 public void Run () {$ try {System.out.println (THIS.name + "is running."); Thread.Sleep (Exception e) {e.printstacktrace (); 43}44} 45}

Run results (one time) :

Task-2 is running.task-3 are running.task-4 is running.task-5 are running.task-6 is running.task-7 Ing.task-9 is running.task-0 are Running.task-1 is running.

result Note : After modifying the thread pool's deny policy from Discardpolicy to Callerrunspolicy, when a task is added to the thread pool is rejected, the thread pool adds the rejected task to the thread pool running threads to run.

Java-"Juc thread pool" threading Status and Denial policy source code Analysis

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.