I have a spring application that use blockingqueue to run producer-consumer design. Basically when user makes an API call using REST controller, it adds a work to blockingqueue and background thread will consume the queue as soon as it's arrived.
I see that Spring recommends to use it's TaskExecutor, so I have the following class. ThreadConfig.java
@Configuration
public class ThreadConfig {
@Bean
public TaskExecutor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(4);
executor.setMaxPoolSize(4);
executor.setThreadNamePrefix("default_task_executor_thread");
executor.initialize();
return executor;
}
}
I also have a consumer component of which watches the queue and run the task. MessageConsumer.java
@Component
public class MessageConsumer implements Runnable{
private final BlockingQueue<String> queue;
MessageConsumer(BlockingQueue<String> queue){
this.queue = queue;
}
public void run(){
try {
while (true) {
String str = queue.take();
// Do something
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
And now, I am not sure how to start threadpool when spring application starts.
Do I simply add the code in Main?
Any help would be appreciated. Thank you