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.

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

packagecom.javabycode;

import org.springframework.context.annotation.ComponentScan;

import org.springframework.context.annotation.Configuration;

import org.springframework.scheduling.annotation.EnableAsync;

@EnableAsync

@Configuration

@ComponentScan("com.javabycode")

publicclassAppConfig{

}

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

packagecom.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

publicclassMyMailEngine{

staticintinterval=10;//10 seconds

@Async

publicFuture<Boolean>sendMail()throwsInterruptedException{

System.out.println("Sending mail..");

setUpTimer();// countdown timer

Thread.sleep(1000*10);

System.out.println("Sending mail completed");

returnnewAsyncResult<Boolean>(true);

}

publicvoidsetUpTimer(){

finalTimer timer=newTimer();

timer.scheduleAtFixedRate(newTimerTask(){

publicvoidrun(){

System.out.println(setInterval(timer)+"s");

}

},1000,1000);

}

staticfinalintsetInterval(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