-
Notifications
You must be signed in to change notification settings - Fork 4
Asynchronous methods
A method can be marked with @Async
to have every call to it intercepted and executed in a different thread:
@Async
public void doParallel() {
// do something
}
When you call doParallel
on an instance created by the Injector
, your call will be intercepted and return immediately. The execution of the method is delegated to a Thread using Java's ExecutorService
. Interception is subject to all limitations listed here.
Asynchronous methods can have parameters that need to be passed by the caller. Please note that all parameters passed must be thread safe. This does also count for fields of the surrounding class that are being used within the asynchronous method.
Asynchronous methods can return values by wrapping them in a Future
object.
@Async
public Future<Integer> compute(int n) {
final int result = doActualCompute();
return Futures.delegate(result);
}
Futures.delegate
creates a dummy Future which will be replaced with the actual Future object by the interceptor.
Since version 1.1.0 it is also possible to return a CompletableFuture
:
@Async
public CompletableFuture<Integer> compute(int n) {
final int result = doActualCompute();
return Futures.delegateCompletable(result);
}