I am writing Spring (Java 8) web application and per each request(separate thread) my application make a few tasks, which should be completed as quickly as possible to return result to client in browser, so I'd like to find worker pool library, which can be accessed from different threads in safe way.
I have read about Execution pool, Rabbit MQ, but I couldn't find information about the feature of accessing the tasks queue from different threads.
I will really appreciate if somebody can give me advice how to do it in Java.
Here you can use asynchronous method call supported by Spring via @Async
annotation.
The @Async
annotated method will be executed in new thread and the result will be available in Future
object (void
return is also supported). Do note that the method call is non-blocking which will help return the response quickly without waiting for every task to complete. However if required the main thread can be made to wait for all task i.e. Future
to complete via Future.get()
which is blocking.
To configure the asynchronous support, annotate the configuration class with @EnableAsync
and provide below method definition as described here.
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(2);
executor.setQueueCapacity(500);
executor.initialize();
return executor;
}