Interview topic: Why use thread pool? Principle of Thread Pool Parameters

Why use thread pool?

  1. Reduce resource consumption: improve thread utilization and reduce resource consumption for thread creation and destruction
  2. Improve response speed: When the task comes, threads are directly available for execution, and there is no need to create threads first and then execute them.
  3. Unified management and control of threads: Threads are scarce resources, and the use of thread pools can be used to uniformly allocate, tune and monitor.

Detailed explanation of thread pool parameters

  • corePoolSize represents the number of core threads, which is the number of threads that create jobs under normal circumstances. These threads will not be eliminated after creation, but a kind of resident thread.

  • maxinumPoolSize represents the maximum number of threads, which corresponds to the number of core threads, indicating the maximum number of threads allowed to be created. For example, if there are many current tasks and the number of core threads is used up, it will be created at this time. New thread, but the total number of thread pools in the thread pool will not exceed the maximum number of threads currently set.

  • keepAliveTime unit represents the idle survival time of threads beyond the number of core threads, that is, core threads will not be eliminated, but some threads that exceed the number of core threads will be eliminated if they are idle for a certain period of time. We can set the idle time by setKeepAliveTime .

  • workQueue is used to store the tasks to be executed. Assuming that we have all used the core thread pool, and all tasks come in, they will all be put into the queue. Knowing that the whole queue is full but the tasks are still in order, new threads will be created.

  • ThreadFactory is actually a thread factory, used to produce threads to perform tasks, we can choose to use the default creation factory, the generated threads are in the same group, have the same priority, and are not daemon threads, of course we can also Custom thread factories, generally we will develop different thread factories according to the business.

  • Handler task rejection strategy. There are two situations. The first is when we call shutdown and other methods to close the thread pool, at this time there are still unfinished tasks in the thread pool being executed, but because the thread pool has been closed, we continue to submit to the thread pool The task will be rejected. Another situation is when the maximum number of threads is reached and the thread pool has no ability to continue processing the submitted tasks, it will also be rejected at this time.
    Extension: Four rejection policies
    AbortPolicy (default): Abandon the task and throw a RejectedExecutionException exception. This is the default rejection strategy of the thread pool. When the task can no longer be submitted, an exception is thrown and the program running status is reported back in time. If it is a more critical business, it is recommended to use this rejection strategy, so that when the system cannot carry a larger amount of concurrency, it can be found through exceptions in time.
    DiscardPolicy : Discard the task, but don't throw an exception. If the thread queue is full, subsequent submitted tasks will be discarded, and silently discarded. Using this strategy may prevent us from discovering the abnormal state of the system. The suggestion is that some unimportant businesses adopt this strategy. For example, this kind of rejection strategy can be used to collect statistics.
    DiscardOldestPolicy : Discard the first task in the queue, and then resubmit the rejected task. This rejection strategy is a rejection strategy that likes the new and dislikes the old. Whether to adopt this kind of rejection strategy has to be carefully measured according to whether the actual business allows the discarding of old tasks.
    CallerRunsPolicy : The task is handled by the calling thread. If the task is rejected, the calling thread (the thread submitting the task) directly executes the task.
    Insert picture description here
    Extension:
    1) How to set the thread prefix for thread pool management?

    	ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
    	//等待任务在关机时完成--表明等待所有线程执行完
    	threadPool.setWaitForTasksToCompleteOnShutdown(true);
        threadPool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待时间 (默认为0,此时立即停止),并没等待xx秒后强制停止
        threadPool.setAwaitTerminationSeconds(await_termination_seconds); 
        //  线程名称前缀
        threadPool.setThreadNamePrefix("AsyncExecutor-");
    	```
    

2) Why does the Ali protocol not allow the use of Executors to create thread pools?to

Guess you like

Origin blog.csdn.net/lxn1023143182/article/details/114180272