Concurrent

Configuration

  • To declare the bean of executor based on the pool size we set

@Configuration
@EnableAsync
public class AsyncConfig {
    @Bean
    public Executor taskExecutor(){

        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(1);
        threadPoolTaskExecutor.setQueueCapacity(50);
        threadPoolTaskExecutor.setMaxPoolSize(10);
        return threadPoolTaskExecutor;
    }
}

Controller

  • To declare the method which will be run on the thread in background and monitor it by using future

@Controller
public class AsyncController{

    @Autowired
    private AsyncService asyncService;
    
    @GetMapping("/test")
    public String test(){
        Future<Void> task = asyncService.test();
        return "test";
    }
}

Service

  • To define which bean should be used to run the task

@Service
public class AsyncService{
    @Async("taskExecutor")
    public void test(){
        System.out.println("test");
    }
}

Last updated

Was this helpful?