Run function in separate thread in Spring Boot

We will need to create a config file for this.

@Configuration
@EnableAsync
public class ExecutorConfig {

    @Bean("sample-executor")
    public TaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(1);
        executor.setMaxPoolSize(4);
        executor.setThreadNamePrefix("sample-executor-thread-");
        executor.initialize();
        return executor;
    }
}

Now just apply @Async on the function which need to be run separate thread.

@Service
class MyService {
    
    @Async("sample-executor")
    public void runAsync() {
        System.out.println("this will be executed in separate thread");
    }
    
}

Leave a Comment

Your email address will not be published. Required fields are marked *