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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javabycode.spring.core</groupId> <artifactId>spring-async-annotation-example</artifactId> <version>1.0.0-SNAPSHOT</version> <url>http://javabycode.com</url> <name>SPRING - ${project.artifactId}</name> <properties> <spring.version>4.3.0.RELEASE</spring.version> </properties> <dependencies> <!-- spring dependencies --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> </dependencies> </project> |
Spring Application Java Configuration
In this Spring async service example, we are creating Spring application which supports asynchronous execution.
1 2 3 4 5 6 7 8 9 10 11 12 |
package com.javabycode; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableAsync; @EnableAsync @Configuration @ComponentScan("com.javabycode") public class AppConfig { } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
package com.javabycode; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.AsyncResult; import org.springframework.stereotype.Component; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Future; @Component public class MyMailEngine { static int interval = 10; //10 seconds @Async public Future<Boolean> sendMail() throws InterruptedException { System.out.println("Sending mail.."); setUpTimer();// countdown timer Thread.sleep(1000 * 10); System.out.println("Sending mail completed"); return new AsyncResult<Boolean>(true); } public void setUpTimer(){ final Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { public void run() { System.out.println(setInterval(timer)+"s"); } }, 1000, 1000); } static final int setInterval(Timer timer) { if (interval == 1) timer.cancel(); return --interval; } } |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.javabycode; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; public class MySpringApplication { public static void main(String...args) throws InterruptedException, ExecutionException { ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); MyMailEngine mailEngine = context.getBean(MyMailEngine.class); System.out.println("Mail sending will run immediately."); Future<Boolean> future = mailEngine.sendMail(); Boolean result = future.get(); System.out.println("Mail send result: " + result); } } |
Run the main above, the console will print the following message.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Sending mail.. 9s 8s 7s 6s 5s 4s 3s 2s 1s 0s Sending mail completed Mail send result: true |
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 (78 downloads)