SpringBook thread pool configuration and asynchronous task invocation

Way 1: Rewrite spring's default thread pool

1. Configuration of related parameters

#Thread-related configuration
#Number of core threads
task.pool.corePoolSize: 5
#Maximum number of threads in thread pool
task.pool.maxPoolSize: 20
#Maximum idle time of threads
task.pool.keepAliveSeconds: 300
#Maximum queue capacity
task.pool.queueCapacity: 50
#Thread name prefix
task.pool.threadPrefix: pcv-excutor-

2. Rewrite Spring Thread Pool Configuration Injection

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;


@Configuration
@EnableAsync
@Slf4j
public class AsyncConfig implements AsyncConfigurer {

    @Autowired
    Environment environment;

    @Override
    @Bean(name = "taskExecutor")
    public Executor getAsyncExecutor() {
        log.debug("Creating Async Task Executor");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(Integer.parseInt(environment.getProperty("task.pool.corePoolSize"))); //Number of core threads
        executor.setMaxPoolSize(Integer.parseInt(environment.getProperty("task.pool.maxPoolSize")));  //Maximum number of threads
        executor.setQueueCapacity(Integer.parseInt(environment.getProperty("task.pool.keepAliveSeconds"))); //Queue size
        executor.setKeepAliveSeconds(Integer.parseInt(environment.getProperty("task.pool.keepAliveSeconds"))); //Maximum idle time of threads
        executor.setThreadNamePrefix(environment.getProperty("task.pool.threadPrefix")); //// Specifies a prefix for the newly created thread name.
        executor.setRejectedExecutionHandler(
                new ThreadPoolExecutor.CallerRunsPolicy()); // Refusal strategy
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SimpleAsyncUncaughtExceptionHandler();
    }

}

Extension: Thread pool rejection strategy

JDK provides four rejection strategies
 AbortPolicy strategy: throw exceptions directly
 CallerRunsPolicy Policy Policy: Run tasks with only the caller's thread
 Discard Oldest Policy Policy: Discard the tasks that will be executed in the queue and execute the current tasks
 DiscardPolicy Strategy: Direct Discarding Without Handling

3. Writing Task

import lombok.extern.slf4j.Slf4j;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

import java.util.concurrent.Future;

@Component
@Slf4j
public class AysncTask {

    @Autowired
    DavinciUserService davinciUserService;

    @Async("taskExecutor")
    public Future<String> doCheckDavinciUser(UserInfo userInfo) throws InterruptedException{
        log.info("check davinci user task started.");
        long start = System.currentTimeMillis();
        ...
         davinciUserService Executing business logic    
        ...

        long end = System.currentTimeMillis();
        log.info("check davinci user task finished, time elapsed: {} ms.", end-start);

        return new AsyncResult<>("check davinci user task accomplished!");
    }
}

4. Asynchronous Task Call

@RestController
@RequestMapping("/admin")
@Slf4j
public class AdminController {


    @Autowired
    AysncTask aysncTask;

    @GetMapping("/index")
    public RequestEntity<RestResp> index (HttpServletRequest request,
                                          HttpServletResponse response){
        try {
            .......
            Future<String> stringFuture = aysncTask.doCheckDavinciUser(userInfo);
            log.info(stringFuture.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

 

Keywords: Java Spring Lombok JDK

Added by g00bster on Sat, 05 Oct 2019 11:16:46 +0300