Asynchronous Execution of Methods
Methods annotated with @Async
will return immediately to its caller while its operation executes asynchronously:
public class Foo { @Async public void save() { // perform some operation here } }
The save()
method will immediately return control to its caller when invoked, without having to wait for the operation to complete. Note that the save()
operation will execute in a separate thread, so you must ensure thread safety for any shared data being manipulated within save()
.
An asynchronous method can also pass a result to its caller by returning a Future
through the returned value of Future.get()
.
public class Foo { @Async public Future<Integer> calculate() { // perform some operation here // return an instance of Future interface } }
Methods annotated with @Async
must strictly have a void
or Future
return type. Otherwise, an exception will be thrown at runtime when the method is invoked. If you wish to check for non-compliant methods at compile time, you may incorporate the annotation processor AsyncReturnTypeProcessor
during your build. Example usage with maven-processor-plugin
:
<plugin> <groupId>org.bsc.maven</groupId> <artifactId>maven-processor-plugin</artifactId> <executions> <execution> <id>process</id> <goals> <goal>process</goal> </goals> <phase>generate-sources</phase> <configuration> <processors> <processor>com.jcabi.aspects.apt.AsyncReturnTypeProcessor</processor> </processors> </configuration> </execution> </executions> </plugin>
The mechanism is implemented with AOP/AspectJ. Read how to integrate it into your pom.xml
.