Understanding Synchronous and Asynchronous Calls in Spring Boot with Java
This article explains the difference between synchronous and asynchronous method calls in Spring Boot, demonstrates how to convert blocking tasks into @Async‑enabled concurrent executions, and shows how to use Future for callback handling to measure total execution time.
Asynchronous calls are often used to address performance issues in high‑concurrency web applications; this article first defines what an "asynchronous call" is compared to a synchronous call.
Synchronous Call
A simple Java example illustrates a synchronous execution where three tasks are performed sequentially, each sleeping for a random time up to 10 seconds.
@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 { /* similar */ }
public void doTaskThree() throws Exception { /* similar */ }
}In a unit test the Task bean is injected and the three methods are called one after another, producing ordered output and total execution time equal to the sum of the three sleeps.
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
public class ApplicationTests {
@Autowired
private Task task;
@Test
public void test() throws Exception {
task.doTaskOne();
task.doTaskTwo();
task.doTaskThree();
}
}Asynchronous Call
When the tasks have no inter‑dependency, they can be executed concurrently to reduce overall latency. Adding the @Async annotation to each method and enabling async processing in the Spring Boot main class converts the calls to asynchronous execution.
@Component
public class Task {
@Async
public void doTaskOne() throws Exception { /* same body */ }
@Async
public void doTaskTwo() throws Exception { /* same body */ }
@Async
public void doTaskThree() throws Exception { /* same body */ }
}The main application must be annotated with @EnableAsync:
@SpringBootApplication
@EnableAsync
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}Running the test repeatedly may produce no output, partial output, or out‑of‑order output because the main thread finishes before the async tasks complete.
@Async‑annotated methods should not be static, otherwise the async behavior will not work.
Asynchronous Callback
To know when all async tasks have finished, each method can return a Future<String>. The test records a start time, invokes the three async methods, and then polls the returned Future objects until all are done, finally computing the total elapsed time.
@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 (true) {
if (task1.isDone() && task2.isDone() && task3.isDone()) {
break;
}
Thread.sleep(1000);
}
long end = System.currentTimeMillis();
System.out.println("任务全部完成,总耗时:" + (end - start) + "毫秒");
}The output shows that the three tasks run concurrently, reducing the total execution time compared with the synchronous 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.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
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.
