当前位置:网站首页>Experience of using thread pool in project

Experience of using thread pool in project

2022-06-23 10:25:00 cfcoolya

1 Summary of the application of thread pool in the project

1.1 background

In the work , Where thread pools are used is the ability to synchronize staff workload , This function is to select time synchronization personnel workload , The workload comes from the Zen system +Digiprocess System .

Normal is to initiate a workload request , Business logic processing , Response warehousing . There is a big disadvantage in this way, that is, one more request for data from other systems + Database operation , This in turn may result in slower response .

Use thread pool , Put the synchronization method in the queue , And then directly return the response , It will greatly improve the response speed of the interface .

1.2 Role of thread pool

  • Thread reuse

  • Thread Resource Management

  • Control the maximum concurrency of the operating system 、 To ensure the efficient and safe operation of the system

1.3 Thread pool core parameters

  • corePoolSize The number of threads in the core of the thread pool

  • maxmumPoolSize Thread pool the maximum number of thread pools

  • keepAliveTime When the thread exceeds corePoolSize, Extra free thread lifetime

  • unit KeepAliveTime The unit of

  • workQueue Task queue

  • threadFactory Thread factory

  • handler Refusal strategy , The queue is full , And the number of worker threads is greater than or equal to the maximum number of threads in the thread pool

1.4 working principle

1.5 Three important thread pools

  • newFixedThreadPool Fixed size thread pool , Perform long-term tasks

  • newSingleThreadExecutor The thread pool of a single thread

  • newCachedTreadPool Cacheable thread pool For short-term tasks

1.6 JDK Built in rejection strategy

  • AbortPolicy Direct selling rejectedExecutionException Exceptions prevent the system from functioning properly

  • CallerRunsPolicy Don't drop the mission , Call back some tasks to the caller

  • DiscarOldPolicy Discard the task waiting the longest in the queue , Then add the current task to the queue

  • DiscarPolicy Discard tasks directly

2 SpringBoot Creation of thread pool

2.1 Start class configuration

stay SpringBoot In the main program of @EnableAsync

2.2 To configure

@EnableAsync
@Configuration
public class TaskPoolConfig {
    /** 
 *    By default , After the thread pool is created , The number of threads in the thread pool is 0, When the mission comes , A thread is created to execute the task ,
 *     When the number of threads in the thread pool reaches corePoolSize after , The arriving task is placed in the cache queue ;
 *   When the line is full , Continue to create threads , When the number of threads is greater than or equal to maxPoolSize after , Start using the reject policy to reject  
 */
   @Value("${task.pool.corePoolSize}")
   private Integer corePoolSize;// Set the number of core threads 
   @Value("${task.pool.maxPoolSize}")
   private Integer maxPoolSize;// Set the maximum number of threads 
   @Value("${task.pool.keepAliveSeconds}")
   private Integer keepAliveSeconds;// Set thread active time ( second )
   @Value("${task.pool.queueCapacity}")
   private Integer queueCapacity;// Set the queue capacity 
   
   @Bean("taskExecutor")
   public Executor taskExecutor() {
      // Create a thread pool 
      ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
      //  Number of core threads 10: The number of threads initialized when the thread pool is created 
      executor.setCorePoolSize(corePoolSize);
      //  Maximum number of threads 20: The maximum number of threads in the thread pool , Only after the buffer queue is full will it apply for more than the number of core threads 
      executor.setMaxPoolSize(maxPoolSize);
      //  Buffer queue 200: The queue used to buffer the execution of the task 
      executor.setQueueCapacity(queueCapacity);
      //  Allow free time for threads 60 second : When more than the core thread out of the thread in the idle time will be destroyed 
      executor.setKeepAliveSeconds(keepAliveSeconds);
      //  Prefix of thread pool name : After setting, it is convenient for us to locate the thread pool where the processing task is located 
      executor.setThreadNamePrefix("taskExecutor-");
      //  The processing strategy of the thread pool to reject the task :
      //  Here we use CallerRunsPolicy Strategy , When the thread pool has no processing power ,
      //  The strategy will be directly in  execute  Method to run a rejected task in the calling thread of the ;
      //  If the executing program is closed , The task will be discarded 
      executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
      return executor;
   }
}
@Async Will get threads from the thread pool by default , You can also explicitly specify @Async("asyncTaskExecutor")

2.3 properties To configure

###  Thread pool 
task.pool.corePoolSize=10
task.pool.maxPoolSize=20
task.pool.keepAliveSeconds=60
task.pool.queueCapacity=200

2.4 matters needing attention

The following way will make @Async invalid

  • The asynchronous method uses static modification

  • Asynchronous classes are not used @Component annotation ( Or other comments ) Lead to spring Cannot scan to asynchronous class

  • An asynchronous method cannot be in the same class as the called asynchronous method

  • Class @Autowired or @Resource Wait for the annotation to inject automatically , You can't do it by yourself new object

  • If you use SpringBoot The framework must add... To the startup class @EnableAsync annotation

原网站

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