In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-07 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Editor to share with you the example analysis of spring task and thread pool, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
Research on spring task and Thread Pool 1. How to configure spring task timing tasks
Due to the need of work, a method needs to be executed regularly. After relevant comparison, it is found that the task that comes with spring can be satisfied and the configuration is simple.
Steps
1) add the configuration file and add the relevant task tag to the applicationContext-cfg.xml main configuration file
2) write bean classes and execution methods
Write the jobService class, which implements the testjobThread method and calls the spring injected action and service methods
@ Component ("jobService") public class jobService {private static Logger logger = Logger.getLogger (jobService.class); @ Autowired private ThreadPoolTaskExecutor taskExecutor; final CountDownLatch countDownLatch = new CountDownLatch (3); / * * @ Title: DZFP_job * @ Description: invoice timing task * / public void testjobThread () {Date startdate = new Date () Logger.info ("DZFP_job_JOB starts executing tasks..., time" + startdate); try {DzfpAction.Dzfp_SendAll ();} catch (Exception e) {/ / TODO Auto-generated catch block e.printStackTrace (); logger.error (StringUtil.grabExceptionMessage (e)) } Date enddate = new Date (); logger.info ("DZFP_job_JOB task completed... Time "+ enddate +" time "String.valueOf (enddate.getTime ()-startdate.getTime ()) +" millisecond ");}
3) configure task-related configuration files and add the following to the file applicationContext-cfg.xml
Pool-size= "5" this parameter mainly solves the problem of multiple scheduling in parallel, such as the following figure of 5 task tasks. It is recommended to set 3 Murray 5 scheduling.
If the configuration parameter is 1, the following five task tasks will be executed in turn. If a time is exceeded, the following tasks will be waiting all the time, affecting the business.
With the above configuration, the startup project can execute the business in the testjobThread method on a regular basis.
2. How to configure a thread pool by using multithreading in a job method in task
After testing, the methods in spring task are executed serially. For example, the testjobThread method configured above is executed every 5 seconds. If an execution process takes too long, the next call will not be started until the last execution is completed.
In other words, spring task is the main thread that monitors the execution of the method, and if the main thread is not finished, it will not be executed next time.
According to the business requirements, the business in this testjobThread needs to be executed by multiple threads (batch extraction of data).
Thread pool is recommended in the spring framework.
1) configure thread pool
Add the configuration to the applicationContext-cfg.xml file as follows
2) modify the business operation class to thread class to implement the run () method
Add counter CountDownLatch to control the end of the child thread, and then end the main thread
Note that the object implements @ Scope ("prototype"), using member variable parameters
Package cn.hao24.action;import java.util.Date; import java.util.concurrent.CountDownLatch; import org.springframework.context.annotation.Scope;import org.springframework.stereotype.Component; import cn.hao24.util.DateUtil;import cn.hao24.util.SpringContextUtils @ Component ("testThreadAction") @ Scope ("prototype") public class testThreadAction extends Thread {/ * spring tash defaults to single-thread serial execution, that is, the subsequent job will not execute until a method is executed * but if a thread is generated in the main method, if the main thread does not wait for the child thread to finish, the task task will be scheduled multiple times * / private String Treadname; private CountDownLatch latch Public testThreadAction (String Treadname,CountDownLatch latch) {this.Treadname=Treadname; this.latch=latch;} @ Override public void run () {try {/ / main business method for (int I = 0; I < 10; iBusiness +) {Thread current = Thread.currentThread () System.out.println ("Thread number:" + current.getId () + "- -" + current.getName () + "- -" + Treadname + ":-runing---" + I + "-" + DateUtil.format (new Date (), "yyyyMMddHHmmss"); Thread.sleep (20000) }} catch (InterruptedException e) {/ / TODO Auto-generated catch block e.printStackTrace ();} finally {/ / set instance execution completed latch.countDown ();}} public void setTreadname (String treadname) {Treadname = treadname } public void setLatch (CountDownLatch latch) {this.latch = latch;}}
2) the method of modifying job scheduling is multithreading, and configure 3 threads
Package cn.hao24.job; import java.util.Date;import java.util.concurrent.CountDownLatch; import javax.annotation.Resource; import org.apache.log4j.Logger;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;import org.springframework.stereotype.Component; import cn.hao24.action.DzfpAction;import cn.hao24.action.HzgdAction;import cn.hao24.action.KJGOrderjob;import cn.hao24.action.testThreadAction;import cn.hao24.service.ZFBService;import cn.hao24.util.SpringContextUtils Import cn.hao24.util.StringUtil; @ Component ("jobService") public class jobService {private static Logger logger = Logger.getLogger (jobService.class); @ Autowired private ThreadPoolTaskExecutor taskExecutor; final CountDownLatch countDownLatch = new CountDownLatch (3); public void testjobThread () {try {CountDownLatch latch=new CountDownLatch (3) / java utility class, similar to the counter, the main implementation child thread does not end the money, the main thread has been waiting for testThreadAction test1 = (testThreadAction) SpringContextUtils.getBean ("testThreadAction", "test1", latch); testThreadAction test2 = (testThreadAction) SpringContextUtils.getBean ("testThreadAction", "test2", latch); testThreadAction test3 = (testThreadAction) SpringContextUtils.getBean ("testThreadAction", "test3", latch); taskExecutor.execute (test1) TaskExecutor.execute (test2); taskExecutor.execute (test3); latch.await (); / / wait for / / test1.run () before the child thread ends;} catch (Exception e) {e.printStackTrace (); logger.error (StringUtil.grabExceptionMessage (e));}
The execution results are as follows:
Although testjobThread executes once every 5 seconds, because latch.await () latch.countDown () is used; you need to wait for the child thread to finish execution before the next job
The child thread will sleep for 20 seconds each time it loops. Judging from the results below, the three threads only print once every 20 seconds. Meet the final requirements
Thread number: 29--taskExecutor-3-- test3:---runing--- 0muri 20170622145500
Thread number: 28--taskExecutor-2-- test2:---runing--- 0muri 20170622145500
Thread number: 27--taskExecutor-1-- test1:---runing--- 0muri 20170622145500
Thread number: 28--taskExecutor-2-- test2:---runing--- 1 Murray 20170622145520
Thread number: 27--taskExecutor-1-- test1:---runing--- 1 Murray 20170622145520
Thread number: 29--taskExecutor-3-- test3:---runing--- 1 Murray 20170622145520
Thread number: 29--taskExecutor-3-- test3:---runing--- 2 Murray 20170622145540
Thread number: 28--taskExecutor-2-- test2:---runing--- 2 Murray 20170622145540
Thread number: 27--taskExecutor-1-- test1:---runing--- 2 Murray 20170622145540
Spring thread pool configuration default thread pool ThreadPoolTaskExecutor configuration
Configure core parameters
Configure core parameters directly in application.properties
Spring.task.execution.pool.core-size=8spring.task.execution.pool.max-size=12spring.task.execution.pool.keep-alive=60sspring.task.execution.pool.queue-capacity=100000spring.task.execution.pool.allow-core-thread-timeout=truespring.task.execution.thread-name-prefix=swy-task-
Create JavaBean injection
@ Configurationpublic class ExecutorConfig {private static final Logger logger = LoggerFactory.getLogger (ExecutorConfig.class); @ Bean public Executor asyncServiceExecutor () {logger.info ("start asyncServiceExecutor"); ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor (); / / configure the number of core threads executor.setCorePoolSize (5); / / configure the maximum number of threads executor.setMaxPoolSize (6); / / configure queue size executor.setQueueCapacity (99999) / / configure the name prefix executor.setThreadNamePrefix ("swy-task-") 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;}}
Open the @ EnableAsync annotation in the configuration class, or the entry class
@ SpringBootApplication@EnableAsyncpublic class MultiThreadApplication {public static void main (String [] args) {SpringApplication.run (MultiThreadApplication.class, args);}}
Add @ Async annotations to classes or methods in the Service layer or Controller layer
@ Asyncpublic void doSomethingAsync () {logger.info ("start executeAsync"); try {Thread.sleep (5000);} catch (Exception e) {e.printStackTrace ();} logger.info ("end executeAsync");} Custom thread pool ThreadPoolTaskExecutor configuration
Inheriting ThreadPoolTaskExecutor to create a new thread pool class
Public class CustomThreadPoolTaskExecutor extends ThreadPoolTaskExecutor {private static final Logger logger = LoggerFactory.getLogger (CustomThreadPoolTaskExecutor.class); private void showThreadPoolInfo (String prefix) {ThreadPoolExecutor threadPoolExecutor = getThreadPoolExecutor (); if (null==threadPoolExecutor) {return } logger.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) }}
Configure the core parameters of the new thread pool class
@ Configurationpublic class ExecutorConfig {private static final Logger logger = LoggerFactory.getLogger (ExecutorConfig.class); @ Bean public Executor asyncServiceExecutor () {logger.info ("start asyncServiceExecutor"); ThreadPoolTaskExecutor executor = new CustomThreadPoolTaskExecutor (); / / configure the number of core threads executor.setCorePoolSize (5); / / configure the maximum number of threads executor.setMaxPoolSize (8); / / 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;}}
Open the @ EnableAsync annotation in the configuration class, or the entry class
@ SpringBootApplication@EnableAsyncpublic class MultiThreadApplication {public static void main (String [] args) {SpringApplication.run (MultiThreadApplication.class, args);}}
When you add @ Async annotations to classes or methods in the Service layer or Controller layer, be sure to indicate the name of the Bean method.
@ Async ("asyncServiceExecutor") public void doSomethingAsync () {logger.info ("start executeAsync"); try {Thread.sleep (5000);} catch (Exception e) {e.printStackTrace ();} logger.info ("end executeAsync");} this is all of the article "sample Analysis of spring task and Thread Pool". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.