How to Transform Synchronous Java Methods into Asynchronous Calls with Spring Boot
This article explains the difference between synchronous and asynchronous calls, demonstrates a Java Spring Boot example that converts blocking methods into concurrent @Async tasks, and shows how to use Future for callback handling to measure total execution time.
What Is Asynchronous Call?
Asynchronous call is the opposite of synchronous call. In a synchronous call each line waits for the previous one to finish; an asynchronous call proceeds without waiting for the result.
Synchronous Call Example
Define a Task class with three methods doTaskOne, doTaskTwo, doTaskThree that each sleep for a random time (up to 10 seconds) and print start and finish messages.
@Component
public class Task {
public static Random random = new Random();
public void doTaskOne() throws Exception {
System.out.println("开始做任务一");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
System.out.println("完成任务一,耗时:" + (end - start) + "毫秒");
}
public void doTaskTwo() throws Exception {
System.out.println("开始做任务二");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
System.out.println("完成任务二,耗时:" + (end - start) + "毫秒");
}
public void doTaskThree() throws Exception {
System.out.println("开始做任务三");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
System.out.println("完成任务三,耗时:" + (end - start) + "毫秒");
}
}In a unit test the three methods are invoked sequentially, producing ordered output and a total execution time equal to the sum of the three durations.
Asynchronous Call with Spring Boot
By adding the @Async annotation to the task methods and enabling async processing with @EnableAsync in the main application, the methods run concurrently.
@Component
public class Task {
@Async
public void doTaskOne() throws Exception { /* same body as before */ }
@Async
public void doTaskTwo() throws Exception { /* same body as before */ }
@Async
public void doTaskThree() throws Exception { /* same body as before */ }
} @SpringBootApplication
@EnableAsync
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}Running the same unit test now may produce no output, partial output, or out‑of‑order output because the main thread finishes before the async tasks complete.
Note: Methods annotated with @Async must not be static.
Asynchronous Callback Using Future
To know when all async tasks finish, change the methods to return Future<String> and use AsyncResult. In the test, capture the Future objects, poll their isDone() status, and calculate total elapsed time after all are finished.
@Async
public Future<String> doTaskOne() throws Exception {
System.out.println("开始做任务一");
long start = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
long end = System.currentTimeMillis();
System.out.println("完成任务一,耗时:" + (end - start) + "毫秒");
return new AsyncResult<>("任务一完成");
} @Test
public void test() throws Exception {
long start = System.currentTimeMillis();
Future<String> task1 = task.doTaskOne();
Future<String> task2 = task.doTaskTwo();
Future<String> task3 = task.doTaskThree();
while (!(task1.isDone() && task2.isDone() && task3.isDone())) {
Thread.sleep(1000);
}
long end = System.currentTimeMillis();
System.out.println("任务全部完成,总耗时:" + (end - start) + "毫秒");
}The final output shows the three tasks start together and the total time is significantly shorter than the sequential version.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
