当前位置:网站首页>Seven parameters of thread pool and reject policy

Seven parameters of thread pool and reject policy

2022-06-11 14:22:00 Jinqingze

Thread pool

summary

Why do you need to use thread pools ?

Review the database connection pool we have known before , When the database connection pool is not used , The connection object needs to be destroyed after each use , The next time you use it, you need to create , It takes time .

After using the database connection pool , Some connection objects will be created in advance , Put it in the pool , Remove from the connection pool when necessary , Put it back in the pool .

The same is true of thread pools , If there are a lot of threads , Frequent thread creation and destruction can take a lot of time . stay jdk5 Before that, the thread pool was implemented manually ,jdk5 after ,java Built in thread pool support .

jdk5 Added ThreadPoolExecutor Implement thread pool , Use at the same time Executors Create different types of thread pools :

newSingleThreadExecutor: Create a single thread pool , Because the abnormal end will create a new .

newFixedThreadPool: Create a fixed-size thread pool . Add threads one by one according to the submitted tasks , The guidance maximum remains unchanged . If it ends because of an exception , A new thread supplement will be created .

newCachedThreadPool: Create a cacheable thread pool . Automatically add or recycle threads according to the task .

But it is not generally provided Executors Class to create .

Advantages of thread pool :

Reuse threads , Reduce the resource consumption caused by thread creation and destruction .

Unified management thread , The creation and destruction of threads are managed by the thread pool .

Improve response time , Thread creation is complete , When the task comes, it can be handled directly , Saves creation time .

ThreadPoolExecutor class

Four construction methods are provided , But the other three constructor methods end up calling 7 The construction of parameters .

7 The meaning of parameters

corePoolSize: Core thread pool size , After creating the object , There are no threads in the pool by default , When a task arrives, a thread will be created to execute , After the execution , The thread will not be destroyed . Know to create an equal number of threads out of the core pool size .

Unless you use prestartAllCoreThreads() perhaps prestartCoreThread() Method , The thread pool will create a thread before the task arrives .

maximumPoolSize: Next time you hang Chi maximum thread out , Indicates how many threads can be created in the thread pool .

keepAliveTime: Indicates how long the thread will be destroyed after no task is executed . By default, only when the number of threads is greater than the core pool , It works , Until the number of threads in the thread pool does not exceed corePoolSize.

unit: Parameters KeepAliveTime Time unit of , Yes 7 The value of , stay TimeUnit There are 7 Static properties in ( God 、 Hours 、 minute 、 second 、 millisecond 、 subtle 、 nanosecond )

workQueue: A blocking queue , Used to store tasks waiting to be executed , The choice of this parameter is very important , Can have a significant impact on how the thread pool is run .

threadFactory: Create factories to create threads .

handler: Indicates the rejection policy of the thread pool , There are four kinds. .

Execution of thread pool

After creating the thread pool , Every time you submit a task , Will use execute Method , The flow chart is as follows :

 Insert picture description here

  1. If the number of threads in the thread pool is less than the number in the core pool , Threads will be created to execute tasks in the core pool .
  2. If the number of threads in the thread pool is greater than the number in the core pool , Will determine whether the queue is full , If not, add the task to the queue .
  3. If the number of threads in the queue is full , Determine whether the number of threads is greater than the maximum number of threads , If less than the maximum quantity , Will create non core threads to perform tasks .
  4. If the number of threads is greater than the maximum number , Can execute execution strategy .

Queue in thread pool

SynchronousQueue: Synchronous queue type one capacity only 1 Queues , The submitted task will not be saved , Just create a new thread to execute the new task .

ArrayBlockingQueue: Bounded queues , Is a bounded blocking queue implemented with arrays , Press FIFO Sorting quantity .

LinkedBlockingQueue: Capacity queue can be set , Blocking queue based on linked list , Press FIFO Sorting task , Capacity can be set , If it is not set, it is a borderless blocking queue , Maximum length is Integer.MAX_VALUE.

Rejection policy for thread pool

Thread pools provide four types of denial policies

  1. AbortPolicy Strategy , Will throw an exception directly
  2. CallerRunsPolicy Strategy , As long as the thread pool is not closed , This policy runs the current task in the calling thread ( If the mission is rejected , The thread submitting the task ( for example main) Perform this task directly )
  3. DiscardOledestPolicy Strategy , Discard the oldest request , Try to commit the current task again .
  4. DiscardPolicy Strategy , Discard unmanageable tasks , Nothing to do with .
/*  Mission  */
public class MyTask implements Runnable {
    

    private int taskNum;

    public MyTask(int num) {
    
        this.taskNum = num;
    }

    @Override
    public void run() {
    
        try {
    
            Thread.currentThread().sleep(4000);
        } catch (InterruptedException e) {
    
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+":task "+taskNum+" completion of enforcement ");
    }
}

/*  Modify the rejection policy in the test class to see the characteristics and differences  */
public class Test {
    
    public static void main(String[] args) {
    
        // Creating a thread pool  7
        ThreadPoolExecutor executor = new ThreadPoolExecutor(2,
                                          5, 200,
                                                         TimeUnit.MILLISECONDS,
                                                         new ArrayBlockingQueue<>(2),
                                                         Executors.defaultThreadFactory(),
                                                         new ThreadPoolExecutor.CallerRunsPolicy());
        for(int i=1;i<=20;i++){
    
            MyTask myTask = new MyTask(i);
            executor.execute(myTask);// Add tasks to thread pool 
            //Future<?> submit = executor.submit(myTask);
        }
        executor.shutdown();
    }
}

execute And submit The difference between

Perform tasks in addition to using execute The method can also be used submit Method .

execute Suitable for situations where the return value is not a concern

submit The method is suitable for situations where you need to focus on the return value

Close thread pool

Close thread pool to call shutdownNow and shutdown Two ways to achieve .

shutdownNow: Issue to the executing thread interrupt(), Stop executing , All tasks that have not been started will be cancelled , Return to the list of tasks that have not yet started .

shutdown: The thread pool no longer accepts new tasks , A single page does not force the termination of tasks that have been submitted or are being executed .

原网站

版权声明
本文为[Jinqingze]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111407569682.html