How to create multiple thread pools in Spring Boot?

In Spring Boot, you can create multiple thread pools using Java’s configuration class. To do so, first create a configuration class as shown below:

@Configuration
public class ThreadPoolConfig {

    @Bean("threadPoolA")
    public ExecutorService threadPoolA() {
        return Executors.newFixedThreadPool(10);
    }

    @Bean("threadPoolB")
    public ExecutorService threadPoolB() {
        return Executors.newFixedThreadPool(10);
    }
}

In the example above, we defined two thread pools, named threadPoolA and threadPoolB. You can customize the name and attributes of the thread pools according to your actual needs.

Next, in the place where the thread pool is used, specify the thread pool to be used using the @Qualifier annotation, as shown below:

@Service
public class MyService {

    @Autowired
    @Qualifier("threadPoolA")
    private ExecutorService threadPoolA;

    @Autowired
    @Qualifier("threadPoolB")
    private ExecutorService threadPoolB;

    // 使用threadPoolA执行任务
    public void executeTaskA() {
        threadPoolA.execute(() -> {
            // 执行任务逻辑
        });
    }

    // 使用threadPoolB执行任务
    public void executeTaskB() {
        threadPoolB.execute(() -> {
            // 执行任务逻辑
        });
    }
}

In the example above, we injected a thread pool into the MyService class using the @Autowired and @Qualifier annotations, and used different thread pools to execute tasks in the executeTaskA and executeTaskB methods.

It is important to note that the created thread pool needs to be manually shut down after use to avoid resource leakage. A shutdown method can be added to the Spring Boot lifecycle to close the thread pool, as shown below:

@Configuration
public class ThreadPoolConfig {

    // 省略其他代码

    @PreDestroy
    public void destroy() {
        threadPoolA.shutdown();
        threadPoolB.shutdown();
    }
}

In the example above, we used the @PreDestroy annotation to mark the destroy method, which will be automatically called when Spring Boot stops, closing the thread pool.

Leave a Reply 0

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


广告
Closing in 10 seconds
bannerAds