Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom ThreadPoolTaskExecutor with Spring Boot Async

I have a Spring Boot application which is responsible for answering requests via REST. I also push metrics about my application call. Since this is a separate task and I have to response users immediately, I want to make that metrics publishing asynchronously. So I've used that:

ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(2);
executor.setQueueCapacity(500);
executor.setThreadNamePrefix("MyApp-");
executor.initialize();
return executor;

However, this one uses SimpleAsyncTaskExecutor and does not reuse any threads.

1) How can I use ConcurrentTaskExecutor instead of SimpleAsyncTaskExecutor?

2) Which implementation could best fit for my needs?

like image 208
kamaci Avatar asked Jun 17 '26 22:06

kamaci


1 Answers

To make your custom Executor work, make sure it's registered as a Bean, and reference it on the method annotated with @Async:

@Bean(name = "transcodingPoolTaskExecutor")
public Executor transcodingPoolTaskExecutor() {
    final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(2);
    executor.setMaxPoolSize(2);
    executor.setQueueCapacity(500);
    executor.setThreadNamePrefix("transcoder-");
    executor.initialize();
    return executor;
}

And in the @Service which is holding the method:

@Async("transcodingPoolTaskExecutor")
public void transcodeVideo(UUID fileId) {
    mediaFileService.transcodeVideo(fileId);
}
like image 165
yglodt Avatar answered Jun 20 '26 11:06

yglodt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!