Spring async service example

The Spring async service example show you how to use Spring @Async Thread execution together with Java’s Future callback. We are using Spring @Async to fire up a new thread and get the result in a later time. This is the best solution in case you want to make a time consuming task.

Let’s begin:

Spring Dependencies
Spring have built-in @Async for the asynchronous thread callbacks, so we need the following dependencies.

Spring Application Java Configuration

In this Spring async service example, we are creating Spring application which supports asynchronous execution.

Dig deeper:
@EnableAsync annotation: such as its name, it enables the asynchronous processing. Without this annotation the methods annotated with the @Async will not execute asynchronously.

Mail engine with Spring @Async Method
Now we create a simple mail engine with the sending email method which allow sending mail and receive the result in 10 seconds later. This method is annotated with Spring @Async annotation. The return of the method is a Future which is one of the new libraries of Java 7. A Future object represents the result of an asynchronous computation.

Notice: In our mail engine, we add a countdown timer 10 seconds which help you get the visual output

Test Spring @Async Methods
In this Spring async service example, we create a main class to test the sending email process using Spring @Async Methods above

Run the main above, the console will print the following message.

That’s all on the Spring async service example.

References
Future JavaDoc
Timer JavaDoc
@EnableAsync JavaDoc
@Async JavaDoc

Download complete source code, click link below

spring-async-annotation-example.zip (11 downloads)

Leave a Comment

*

Please share it if you found this useful
Hide Buttons