Category: java
Introduction to Asynchronous Programming
Published on 24 Jul 2026
Explanation
Asynchronous programming allows long-running tasks to execute in the background without blocking the main application thread. Spring Boot supports asynchronous execution using the @Async annotation, improving application responsiveness and throughput.
Code:
@SpringBootApplication
@EnableAsync
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Explanation
Annotate a service method with @Async to execute it in a separate thread. The caller continues processing without waiting for the task to finish, making it useful for sending emails, generating reports, or processing files.
Code:
@Service
public class EmailService {
@Async
public void sendEmail(String email) {
System.out.println("Sending email to " + email);
}
}
Explanation
CompletableFuture represents the result of an asynchronous computation. It allows methods to return results later, chain multiple asynchronous operations, and handle success or failure without blocking the calling thread.
Code:
@Async
public CompletableFuture<String> generateReport() {
return CompletableFuture.completedFuture("Report Generated");
}
Explanation
CompletableFuture.allOf() executes multiple asynchronous tasks in parallel and waits until all tasks complete. This improves performance when independent operations such as API calls or database queries can run simultaneously.
Code:
CompletableFuture<String> task1 = service.taskOne(); CompletableFuture<String> task2 = service.taskTwo(); CompletableFuture.allOf(task1, task2).join();
Explanation
CompletableFuture provides methods such as thenApply(), thenAccept(), exceptionally(), and join() to process results, transform data, handle exceptions, and wait for task completion only when the result is actually needed.
Code:
service.generateReport()
.thenAccept(System.out::println)
.exceptionally(ex -> {
System.out.println(ex.getMessage());
return null;
});