springmvc Configure Thread Pool Executor to Do Multi Thread Concurrent Operation Code Example
- 2021-07-03 00:09:12
- OfStack
Load the xml file
Add in the ApplicationContext. xml file
xmlns:task="http://www.springframework.org/schema/task"
xmlns file and added in xsi: schemaLocation
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd
Configuring Executor in spring
Add in the ApplicationContext. xml file
<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<!-- Number of core threads -->
<property name="corePoolSize" value="${task.core_pool_size}" />
<!-- Maximum number of threads -->
<property name="maxPoolSize" value="${task.max_pool_size}" />
<!-- Maximum queue length -->
<property name="queueCapacity" value="${task.queue_capacity}" />
<!-- Thread pool maintains the allowed idle time of threads, which defaults to 60s -->
<property name="keepAliveSeconds" value="${task.keep_alive_seconds}" />
</bean>
<!-- Annotation -->
<task:annotation-driven />
Add in dbconfig. properties
maxOpenPreparedStatements=20
removeAbandoned=true
removeAbandonedTimeout=1800
logAbandoned=true
This is to configure the thread pool separately
Add dependency injection
Add in the required service or controller class
@Resource(name = "taskExecutor")
private TaskExecutor taskExecutor;
Concurrent operations using thread pools
The code is as follows
taskExecutor.execute(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
// Concurrent operations to be performed
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Prompt
Pay attention to the scope of variables when manipulating variables in threads. You need to declare the following variables in this controller or sevice
@Controller
public class IndexController {
int studentscount = 0;
@RequestMapping(value = "/index.html")
public ModelAndView goIndex() {
logBefore(logger, " List Center");
ModelAndView mv = this.getModelAndView();
taskExecutor.execute(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
// Get the number of all students
try {
studentscount = coursesService.getStudentCount(pd);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
mv.addObject("studentscount", studentscount);
mv.setViewName("common/index");
return mv;
}
Summarize