I am trying to implement a spring @Async task which has a return type of Future, but I can't really figure out how to do it properly.
EDIT
From spring source and spring refrence manual :
Even methods that return a value can be invoked asynchronously. However, such methods are required to have a Future typed return value. This still provides the benefit of asynchronous execution so that the caller can perform other tasks prior to calling get() on that Future.
and the it gives an example like so :
@Async
Future<String> returnSomething(int i) {
// this will be executed asynchronously
}
How to implement this correctly ?
Simply put, annotating a method of a bean with @Async will make it execute in a separate thread. In other words, the caller will not wait for the completion of the called method. One interesting aspect in Spring is that the event support in the framework also has support for async processing if necessary.
The @EnableAsync annotation switches on Spring's ability to run @Async methods in a background thread pool. This class also customizes the Executor by defining a new bean. Here, the method is named taskExecutor , since this is the specific method name for which Spring searches.
EnableAsync is used for configuration and enable Spring's asynchronous method execution capability, it should not be put on your Service or Component class, it should be put on your Configuration class like: @Configuration @EnableAsync public class AppConfig { }
Asynchronous programming in Java is a technique for parallel programming that lets teams distribute work and build application features separately from the primary application thread. Then, when the team is ready with the feature, the code is synced with the main thread.
Check out this blog post.
Using @Async
allows you to run a computation in a method asynchronously. This means that if it's called (on a Spring managed bean), the control is immediately returned to the caller and the code in the method is run in another thread. The caller receives a Future
object that is bound to the running computation and can use it to check if the computation is running and/or wait for the result.
Creating such a method is simple. Annotate it with @Async
and wrap the result in AsyncResult
, as shown in the blog post.
Check out this blog post.
Important configuration is:
@Async
on Spring managed bean method.<!--
Enables the detection of @Async and @Scheduled annotations
on any Spring-managed object.
-->
<task:annotation-driven />
SimpleAsyncTaskExecutor will be used by default.
Wrap the response in a Future<>
object.
@Async
public Future<PublishAndReturnDocumentResult> generateDocument(FooBarBean bean) {
// do some logic
return new AsyncResult<PublishAndReturnDocumentResult>(result);
}
You can then check if the result is done using result.isDone()
or wait to get the response result.get()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With