0
0
Spring Bootframework~5 mins

@Async for async methods in Spring Boot

Choose your learning style9 modes available
Introduction

@Async lets your program do tasks in the background without waiting. This helps your app stay fast and responsive.

When you want to send emails without making the user wait.
When you need to process files or data without blocking the main work.
When calling slow external services but want to keep your app quick.
When running scheduled tasks that should not stop other actions.
Syntax
Spring Boot
@Async
public CompletableFuture<Type> methodName() {
    // method body
}

Use @Async above a method to run it in a new thread.

The method should return CompletableFuture or void.

Examples
This method runs in the background and returns nothing.
Spring Boot
@Async
public void sendEmail() {
    // send email code
}
This method runs async and returns a future result.
Spring Boot
@Async
public CompletableFuture<String> fetchData() {
    // fetch data code
    return CompletableFuture.completedFuture("data");
}
Sample Program

This example shows a service with an async method that waits 1 second then returns a message. The main runner calls it without blocking, then waits for the result to print.

Spring Boot
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.CompletableFuture;

@Configuration
@EnableAsync
public class AsyncConfig {
}

@Service
public class AsyncService {

    @Async
    public CompletableFuture<String> asyncTask() {
        try {
            Thread.sleep(1000); // simulate delay
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return CompletableFuture.completedFuture("Task Completed");
    }
}

// Usage in another component
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.util.concurrent.CompletableFuture;

@Component
public class AppRunner implements CommandLineRunner {

    @Autowired
    private AsyncService asyncService;

    @Override
    public void run(String... args) throws Exception {
        System.out.println("Starting async call");
        CompletableFuture<String> future = asyncService.asyncTask();
        System.out.println("Async call made");
        System.out.println("Result: " + future.get());
    }
}
OutputSuccess
Important Notes

Remember to add @EnableAsync in your configuration to activate async support.

Async methods must be public and called from outside their own class to work properly.

Summary

@Async runs methods in the background to keep your app responsive.

Use it for tasks that take time but don't need to block the user.

Make sure to enable async support with @EnableAsync.