Asynchronous Methods with @Async
Learn to execute methods asynchronously using Spring's `@Async` annotation and thread pools.
Intro to Async Operations
Imagine you're ordering food online. If the app made you wait for the chef to cook your meal before you could even browse other options, that would be a bad experience!
This is like synchronous operations: one task must finish before the next can start. It blocks the main flow.
Asynchronous operations, on the other hand, let you start a task and immediately move on to something else. The task runs in the background, and you get notified when it's done.
- Non-blocking: Your application remains responsive.
- Efficient: Better utilization of resources by performing multiple tasks concurrently.
Sync vs. Async Demo
Let's see a simple Java example of a blocking (synchronous) operation. Notice how the main thread waits for doSyncTask() to complete.
Try running this example:
public class Main {
public static void main(String[] args) {
System.out.println("Main thread: Starting sync task...");
long startTime = System.currentTimeMillis();
doSyncTask(); // This call blocks the main thread
long endTime = System.currentTimeMillis();
System.out.println("Main thread: Sync task finished in " + (endTime - startTime) + "ms.");
System.out.println("Main thread: Continues immediately after sync task.");
}
public static void doSyncTask() {
try {
System.out.println("Sync task: Simulating work for 2 seconds...");
Thread.sleep(2000); // Simulate a long operation
System.out.println("Sync task: Completed!");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.err.println("Sync task: Interrupted!");
}
}
}All lessons in this course
- Asynchronous Methods with @Async
- Introduction to Message Queues
- Integrating RabbitMQ/Kafka
- Scheduling Tasks with @Scheduled