Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use ThreadPoolTaskExecutor custom thread pool and asynchronous invocation in Spring

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the Spring how to use ThreadPoolTaskExecutor custom thread pool and asynchronous invocation related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that you read this Spring how to use ThreadPoolTaskExecutor custom thread pool and asynchronous invocation article will have a harvest, let's take a look.

Multithreading has always been a high-frequency knowledge point in the job or interview process. Today, I would like to share with you the use of ThreadPoolTaskExecutor to customize the thread pool and implement asynchronous multithreading.

1. ThreadPoolTaskExecutor

This paper uses the factory method of Executors for configuration.

1. Define the parameters used by the thread pool into the configuration file

Create an executor.properties file in the resources directory of the project and add the following configuration:

# Asynchronous thread configuration # maximum number of core threads async.executor.thread.core_pool_size=5# task queue size async.executor.thread.queue_capacity=2# thread pool name prefix idle time of threads in async.executor.thread.name.prefix=async-service-# buffer queue async.executor.thread.keep_alive_seconds=1002, factory configuration of Executors 2.1, Configuration details @ Configuration// @ PropertySource are the files found in the classes directory under the target directory Files under the resources directory are compiled and generated in the classes directory @ PropertySource (value = {"classpath:executor.properties"}, ignoreResourceNotFound=false, encoding= "UTF-8") @ Slf4jpublic class ExecutorConfig {@ Value ("${async.executor.thread.core_pool_size}") private int corePoolSize @ Value ("${async.executor.thread.max_pool_size}") private int maxPoolSize; @ Value ("${async.executor.thread.queue_capacity}") private int queueCapacity; @ Value ("${async.executor.thread.name.prefix}") private String namePrefix; @ Value ("${async.executor.thread.keep_alive_seconds}") private int keepAliveSeconds @ Bean (name = "asyncTaskExecutor") public ThreadPoolTaskExecutor taskExecutor () {log.info ("startup"); ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor (); / / Core threads executor.setCorePoolSize (corePoolSize); / / maximum number of threads executor.setMaxPoolSize (maxPoolSize); / / Task queue size executor.setQueueCapacity (queueCapacity) / / Thread prefix name executor.setThreadNamePrefix (namePrefix); / / Thread idle time executor.setKeepAliveSeconds (keepAliveSeconds); / / reject Policy executor.setRejectedExecutionHandler (new ThreadPoolExecutor.CallerRunsPolicy ()); / / Thread initialization executor.initialize (); return executor;} 2.2, Notes

When the @ Configuration:Spring container starts, it loads the class with the @ Configuration annotation and handles the methods with the @ Bean annotation.

Bean: is a method-level annotation, mainly used in @ Configuration annotated classes, but can also be used in @ Component annotated classes. The id of the added bean is the method name.

PropertySource: loads the specified configuration file. The value value is the configuration file to be loaded, and ignoreResourceNotFound means whether the program ignores the loaded file if it cannot be found. The default is false. If true, the loaded configuration file does not exist and the program does not report an error. In actual project development, it is best to set it to false. If the properties in the application.properties file duplicate those in the custom configuration file, the property values in the custom configuration file are overwritten and the configuration properties in the application.properties file are loaded.

The log output tool of @ Slf4j:lombok. With this note, you can directly call log to output logs at all levels.

Value: invokes the property in the configuration file and assigns a value to the property.

2.3 Thread Pool configuration description

Number of core threads: the number of threads initialized when the thread pool was created. When the number of threads exceeds the number of core threads, the excess threads enter the task queue.

Maximum number of threads: only when the task queue is full will you apply for threads that exceed the number of core threads. Cannot be less than the number of core threads.

Task queue: the part with more threads than the core thread enters the task queue. If the task queue is large enough that threads that exceed the number of core threads will not be created, it will wait for the core threads to finish their own tasks before executing the tasks of the task queue, rather than creating additional threads. For example: if there are 20 tasks to execute, the number of core threads is 10, the maximum number of threads is 20, and the task queue size is 2. The system creates 18 threads. Some of the 18 threads have finished executing the task and then execute the task in the task queue.

Idle time of threads: when the number of threads in the thread pool is greater than the number of core threads, if the idle time of a thread exceeds keepAliveTime, the thread will be terminated. This way, the thread pool can dynamically adjust the number of threads in the pool.

Reject policy: if (total number of tasks-number of core threads-number of task queues)-(maximum number of threads-number of core threads) > 0, thread rejection occurs. For example: (12-5-2)-(8-5) > 0, thread rejection occurs. Thread rejection is divided into four strategies, which are:

CallerRunsPolicy (): let the caller thread run, such as the main thread.

AbortPolicy (): throw an exception directly.

DiscardPolicy (): discard directly.

DiscardOldestPolicy (): discards the oldest task in the queue.

2.4. Personal understanding of thread pool configuration

When a task is submitted to a thread pool, first check to see if all the core threads of the thread pool are executing the task. If not, select a thread to execute the task.

If they are all performing tasks, check to see if the task queue is full. If dissatisfied, the task is stored in the task queue. After the core thread has finished executing its own task, it will process the tasks in the task queue.

If the task queue is full, check to see if the thread pool (maximum number of threads control) is full. If dissatisfied, create a thread to execute the task. If full, follow the policy to deal with tasks that cannot be performed.

Asynchronous invocation thread

ThreadPoolTaskExecutor is usually used with @ Async. Add a @ Async annotation to a method to indicate that the method function is called asynchronously.

@ Async is followed by the method name or bean name of the thread pool, indicating that the asynchronous thread will load the configuration of the thread pool.

@ Component@Slf4jpublic class ThreadTest {/ * loops every 10 seconds, and a thread loops 10 times. * / @ Async ("asyncTaskExecutor") public void ceshi3 () {for (int I = 0; I

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report