Definition and use of SpringBoot2 thread pools
Defining a thread pool
@Slf4j @EnableAsync @Configuration public class AsyncExecutorConfig implements AsyncConfigurer { @Bean public ThreadPoolTaskExecutor asyncServiceExecutor() {// Returns the maximum number of VMS with available processors not less than 1 int CPU = Runtime.getRuntime().availableProcessors(); log.info("start asyncServiceExecutor cpu : {}", cpu); ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // Set the number of core threads executor.setCorePoolSize(CPU); // Set the maximum number of threads executor.setMaxPoolSize(CPU); / / configuration queue size executor. SetQueueCapacity (50); Close it / / used to set the thread pool waiting for all the tasks are completed to destroy other Bean executor. SetWaitForTasksToCompleteOnShutdown (true); / / set the waiting time of task in the thread pool, if more than this time haven't destroy force to destroy, to ensure that the application of the last to be closed, rather than block executor. SetAwaitTerminationSeconds (60); / / the name of the configuration of threads in thread pool prefix executor. SetThreadNamePrefix (" async - service - "); Rejection -policy: how to process a new task when the pool has reached Max size Instead of executing tasks in a new thread, But the caller's thread to perform / / use predefined exception handling executor setRejectedExecutionHandler (new ThreadPoolExecutor. CallerRunsPolicy ()); // Initialize executor.initialize(); return executor; } @Override public Executor getAsyncExecutor() { return asyncServiceExecutor(); } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return (throwable, method, objects) -> { StringBuilder sb = new StringBuilder(); for (Object param : objects) { sb.append(param).append(","); } log.error("Exception message - {}, Method name - {}, Parameter value - {}", throwable.getMessage(), method.getName(), sb.toString()); }; }}Copy the code
How to use
@Autowired
private ThreadPoolTaskExecutor threadPoolTaskExecutor;
public void test(){
CompletableFuture<Void> userFuture = CompletableFuture.runAsync(() -> System.out.println(111), threadPoolTaskExecutor);
}Copy the code
Zhao Xiaopang personal blog