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 the Springboot thread pool

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

Today, I will talk to you about how to use the Springboot thread pool, which may not be well understood by many people. in order to make you understand better, the editor has summarized the following for you. I hope you can get something from this article.

Create a springboot project

To create a springboot web project threadpooldemoserver,pom.xml with IntelliJ IDEA, the contents are as follows:

4.0.0 com.vincent threadpooldemoserver 1.0-SNAPSHOT UTF-8 1.8 1.8 org.springframework.boot spring-boot-dependencies 2.1.4.RELEASE import pom Org.springframework.boot spring-boot-starter-web org.projectlombok lombok 1.18.6 org.springframework.boot spring-boot-maven-plugin 2.1.4.RELEASE Cn.ac.iie.App repackage Interface and implementation of creating Service layer by org.apache.maven.plugins maven-surefire-plugin true

Create an interface AsyncService for the service layer, as follows:

Public interface AsyncService {/ * execute asynchronous tasks * / void executeAsync ();}

The corresponding AsyncServiceImpl is implemented as follows:

Service@Slf4jpublic class AsyncServiceImpl implements AsyncService {@ Override public void executeAsync () {log.info ("start executeAsync"); try {Thread.sleep (1000);} catch (Exception e) {e.printStackTrace ();} log.info ("end executeAsync");}}

What this method does is simple: sleep for a second

Create controller

Create a controller as Hello, which defines a http interface, and invokes the services of the Service layer, as follows:

@ RestController@Slf4jpublic class Hello {@ Autowired private AsyncService asyncService; @ RequestMapping ("/") public String submit () {log.info ("start submit"); / / call the task of the service layer asyncService.executeAsync (); log.info ("end submit"); return "success";}}

At this point, we have done a http request service, and what is done in it is actually synchronized, and then we begin to configure springboot's thread pool service to submit everything done by the service layer to the thread pool for processing.

Thread pool configuration of springboot

Create a configuration class ExecutorConfig to define how to create a ThreadPoolTaskExecutor. Use @ Configuration and @ EnableAsync annotations to indicate that this is a configuration class and a configuration class for the thread pool, as shown below:

@ Configuration@EnableAsync@Slf4jpublic class ExecutorConfig {@ Bean public Executor asyncServiceExecutor () {log.info ("start asyncServiceExecutor"); ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor (); / / configure core threads executor.setCorePoolSize (5); / / configure maximum number of threads executor.setMaxPoolSize (5); / / configure queue size executor.setQueueCapacity (99999) / / configure the name prefix executor.setThreadNamePrefix ("async-service-") of the thread in the thread pool; / / rejection-policy: how to handle the new task when the pool has reached max size / / CALLER_RUNS: instead of executing the task in the new thread, the caller's thread executes the executor.setRejectedExecutionHandler (new ThreadPoolExecutor.CallerRunsPolicy ()) / / perform initialization executor.initialize (); return executor;}}

Note that the above method is named asyncServiceExecutor and will be used immediately.

Asynchronize services in the Service layer

Open AsyncServiceImpl.java and add @ Async ("asyncServiceExecutor") to the executeAsync method. AsyncServiceExecutor is the method name in the previous ExecutorConfig.java, indicating that the thread pool entered by the executeAsync method is created by the asyncServiceExecutor method, as follows:

@ Service@Slf4jpublic class AsyncServiceImpl implements AsyncService {@ Override @ Async ("asyncServiceExecutor") public void executeAsync () {log.info ("start executeAsync"); try {Thread.sleep (1000);} catch (Exception e) {e.printStackTrace ();} log.info ("end executeAsync");}} verification effect

Run the springboot (execute mvn spring-boot:run under the folder where the pom.xml is located)

Enter: http://localhost:8080 in the browser

Quickly refresh several times with the F5 button in the browser

You can see the log on the console of springboot as follows:

2019-08-12 15 INFO 23 cn.ac.iie.controller.Hello 00.320 INFO 5848-[nio-8080-exec-2] cn.ac.iie.controller.Hello: start submit2019-08-12 15 cn.ac.iie.controller.Hello 23 cn.ac.iie.controller.Hello 00.327 INFO 5848-[nio-8080-exec-2] cn.ac.iie.controller.Hello: end submit2019-08-12 15 cn.ac.iie.controller.Hello 23 cn.ac.iie.controller.Hello 00.327 INFO 5848-[async-service-1] cn.ac.iie .service.impl.AsyncServiceImpl: start executeAsync2019-08-12 15 async-service-1 23 INFO 01.329 INFO 5848-[async-service-1] cn.ac.iie.service.impl.AsyncServiceImpl: end executeAsync2019-08-12 1515 async-service-1 2417.449 INFO 5848-[nio-8080-exec-5] Impl: AsyncServiceImpl: AsyncServiceImpl-[nio-8080-exec-5] Cn.ac.iie.controller.Hello: end submit2019-08-12 15 cn.ac.iie.service.impl.AsyncServiceImpl 24 INFO 17.450 INFO 5848-[async-service-2] cn.ac.iie.service.impl.AsyncServiceImpl: start executeAsync2019-08-12 15 INFO 24 18.125 INFO 5848-[nio-8080-exec-6] cn.ac.iie.controller.Hello: start submit2019-08-12 15 Swiss 24 INFO 5848 [nio-8080-exec-6] cn.ac.iie.controller.Hello: end submit2019-08-12 15 end submit2019 24 INFO 18.128 INFO 5848-[async-service-3] cn.ac.iie.service.impl.AsyncServiceImpl: start executeAsync2019-08-12 15 15 Swiss 24 INFO 18.451 INFO 5848-[async-service-2] cn.ac.iie.service.impl.AsyncServiceImpl: end executeAsync2019-08-12 15 Swiss 2418.685 INFO 5848-- -- [nio-8080-exec-7] cn.ac.iie.controller.Hello: start submit2019-08-12 15 start submit2019 24 INFO 18.688 INFO 5848-[nio-8080-exec-7] cn.ac.iie.controller.Hello: end submit2019-08-12 15 15 15 nio-8080-exec-7: INFO 18.703 INFO 5848-[async-service-4] cn.ac.iie.service.impl.AsyncServiceImpl: start executeAsync2019-08-12 15 : 24cn.ac.iie.service.impl.AsyncServiceImpl 19.130 INFO 5848-[async-service-3] cn.ac.iie.service.impl.AsyncServiceImpl: end executeAsync2019-08-12 15 cn.ac.iie.service.impl.AsyncServiceImpl 24purl 19.704 INFO 5848-[async-service-4] cn.ac.iie.service.impl.AsyncServiceImpl: end executeAsync

As shown in the log above, we can see that the execution thread of controller is "nio-8080-exec-5", which is the execution thread of tomcat, while the log of service layer shows that the thread is named "async-service-1", which has obviously been executed in our configured thread pool, and the start and end logs of controller are printed continuously in each request, indicating that each request responds quickly. Time-consuming operations are left to threads in the thread pool to execute asynchronously.

Extended ThreadPoolTaskExecutor

Although we have used the thread pool, it is not clear what the thread pool was like, how many threads were executing and how many were waiting in the queue. Here I have created a subclass of ThreadPoolTaskExecutor that prints the health of the current thread pool each time the thread is submitted, as follows:

@ Slf4jpublic class VisiableThreadPoolTaskExecutor extends ThreadPoolTaskExecutor {private void showThreadPoolInfo (String prefix) {ThreadPoolExecutor threadPoolExecutor = getThreadPoolExecutor (); if (null==threadPoolExecutor) {return } log.info ("{}, {}, taskCount [{}], completedTaskCount [{}], activeCount [{}], queueSize [{}]", this.getThreadNamePrefix (), prefix, threadPoolExecutor.getTaskCount (), threadPoolExecutor.getCompletedTaskCount (), threadPoolExecutor.getActiveCount (), threadPoolExecutor.getQueue (). Size ()) } @ Override public void execute (Runnable task) {showThreadPoolInfo ("1.do execute"); super.execute (task);} @ Override public void execute (Runnable task, long startTimeout) {showThreadPoolInfo ("2.do execute"); super.execute (task, startTimeout);} @ Override public Future submit (Runnable task) {showThreadPoolInfo ("1.do submit"); return super.submit (task) } @ Override public Future submit (Callable task) {showThreadPoolInfo ("2.do submit"); return super.submit (task);} @ Override public ListenableFuture submitListenable (Runnable task) {showThreadPoolInfo ("1.do submitListenable"); return super.submitListenable (task);} @ Override public ListenableFuture submitListenable (Callable task) {showThreadPoolInfo ("2.do submitListenable"); return super.submitListenable (task) }}

As shown above, the total number of tasks, the number of completed threads, the number of active threads and the queue size are all printed in the showThreadPoolInfo method, and then Override the execute, submit and other methods of the parent class, in which the showThreadPoolInfo method is called, so that every time a task is submitted to the thread pool, the basic information of the current thread pool will be printed to the log.

Modify the asyncServiceExecutor method of ExecutorConfig.java to change ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor () to ThreadPoolTaskExecutor executor = new VisiableThreadPoolTaskExecutor (), as follows:

@ Bean public Executor asyncServiceExecutor () {log.info ("start asyncServiceExecutor"); ThreadPoolTaskExecutor executor = new VisiableThreadPoolTaskExecutor (); / / configure core threads executor.setCorePoolSize (5); / / configure maximum number of threads executor.setMaxPoolSize (5); / / configure queue size executor.setQueueCapacity (99999) / / configure the name prefix executor.setThreadNamePrefix ("async-service-") of the thread in the thread pool; / / rejection-policy: how to handle the new task when the pool has reached max size / / CALLER_RUNS: instead of executing the task in the new thread, the caller's thread executes the executor.setRejectedExecutionHandler (new ThreadPoolExecutor.CallerRunsPolicy ()) / / perform initialization executor.initialize (); return executor;}

Modify hello.java to make it easy to view thread pool results:

@ RequestMapping ("/") public Object submit () {log.info ("start submit"); / / call service layer task asyncService.executeAsync (); log.info ("end submit"); JSONObject jsonObject = new JSONObject (); ThreadPoolExecutor threadPoolExecutor = visiableThreadPoolTaskExecutor.getThreadPoolExecutor (); jsonObject.put ("ThreadNamePrefix", visiableThreadPoolTaskExecutor.getThreadNamePrefix ()); jsonObject.put ("TaskCount", threadPoolExecutor.getTaskCount ()) JsonObject.put ("completedTaskCount", threadPoolExecutor.getCompletedTaskCount ()); jsonObject.put ("activeCount", threadPoolExecutor.getActiveCount ()); jsonObject.put ("queueSize", threadPoolExecutor.getQueue (). Size ()); return jsonObject;}

Start the project again, and then refresh the http://localhost:8080 repeatedly in the browser. The log you see is as follows:

{"activeCount": 2, "queueSize": 1, "TaskCount": 26, "completedTaskCount": 23, "ThreadNamePrefix": "async-service-"} after reading the above, do you have any further understanding of how to use the Spring boot thread pool? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

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

Internet Technology

Wechat

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

12
Report