Performance: @Async for async methods
This affects how quickly the server responds to requests by running methods asynchronously, improving user interaction speed.
@Async
public void longTask() throws InterruptedException {
Thread.sleep(5000); // simulate long work
}
@GetMapping("/process")
public String process() {
longTask(); // runs asynchronously
return "done";
}@GetMapping("/process") public String process() throws InterruptedException { longTask(); // runs synchronously return "done"; } public void longTask() throws InterruptedException { Thread.sleep(5000); // simulate long work }
| Pattern | Thread Blocking | Response Delay | Server Load | Verdict |
|---|---|---|---|---|
| Synchronous method call | Blocks main thread | High delay | Lower concurrency | [X] Bad |
| @Async method call | No main thread block | Low delay | Higher concurrency | [OK] Good |
What is the main purpose of using @Async in a Spring Boot application?
@Async does@Async allows methods to run in a separate thread, so they don't block the main thread.Which annotation must be added to a Spring Boot configuration class to enable @Async support?
@EnableAsync on a configuration class to activate async processing.@EnableAsync, not any other variant.Consider this Spring Boot method annotated with @Async:
@Async
public CompletableFuture<String> fetchData() {
return CompletableFuture.completedFuture("Done");
}What will be the output if you call fetchData().get()?
get() blocks the caller until the async task finishes and then returns the result.Given this Spring Boot service method:
@Async
public void process() {
System.out.println("Start");
throw new RuntimeException("Error");
}What happens when process() is called?
You want to run two independent tasks asynchronously and wait concurrently for both to finish before proceeding. Which approach using @Async and CompletableFuture is correct?
@Async
public CompletableFuture<String> taskOne() { ... }
@Async
public CompletableFuture<String> taskTwo() { ... }
public void runTasks() throws Exception {
CompletableFuture<String> future1 = taskOne();
CompletableFuture<String> future2 = taskTwo();
// What to do here?
}get() sequentially works but is inefficient and blocks one after another.CompletableFuture.allOf(future1, future2).join() waits for both tasks to complete concurrently.Pass the test and this pattern moves unknown