Backend Development 8 min read

Understanding Synchronous and Asynchronous Calls in Spring Boot with @Async

This article explains the difference between synchronous and asynchronous method calls in Java, demonstrates how to implement synchronous tasks, then shows how to convert them to asynchronous execution using Spring Boot's @Async annotation, @EnableAsync configuration, and Future-based callbacks to measure total execution time.

Code Ape Tech Column
Code Ape Tech Column
Code Ape Tech Column
Understanding Synchronous and Asynchronous Calls in Spring Boot with @Async

Asynchronous calls are often used to improve performance in high‑concurrency web applications, while synchronous calls execute sequentially, waiting for each method to finish before proceeding.

Synchronous call example : a Task class defines three methods ( doTaskOne , doTaskTwo , doTaskThree ) that each sleep for a random time up to 10 seconds and log start/end messages. A unit test injects the Task bean and calls the three methods one after another, producing ordered output and total execution time equal to the sum of the three sleeps.

@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) + "毫秒");
    }
    // doTaskTwo and doTaskThree are similar
}
@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();
    }
}

The test output shows the three tasks executing sequentially.

Asynchronous call conversion : By adding the @Async annotation to each task method and enabling async processing with @EnableAsync on the Spring Boot application class, the three tasks can 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 may produce no output, partial output, or out‑of‑order output because the main thread finishes before the async tasks complete.

Asynchronous callback with Future : To know when all async tasks finish, change the methods to return Future and modify the test to collect the Future objects, poll isDone() in a loop, and compute total elapsed time after all tasks complete.

@Async
public Future
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
task1 = task.doTaskOne();
    Future
task2 = task.doTaskTwo();
    Future
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 test now prints the start of each task, their individual completion times, and the total elapsed time, demonstrating that concurrent execution reduces overall runtime.

backendJavaconcurrencySpring BootasyncFutureAsync
Code Ape Tech Column
Written by

Code Ape Tech Column

Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.