Performance: Why async processing matters
Async processing improves server responsiveness and reduces request blocking, impacting user interaction speed and server throughput.
public CompletableFuture<String> handleRequestAsync() {
return CompletableFuture.supplyAsync(() -> {
try {
// Long operation
Thread.sleep(5000);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
return "done";
});
}public String handleRequest() throws InterruptedException {
// Long blocking operation
Thread.sleep(5000);
return "done";
}| Pattern | Thread Blocking | Request Throughput | Response Delay | Verdict |
|---|---|---|---|---|
| Synchronous blocking | Blocks thread for full task duration | Low under load | High delay | [X] Bad |
| Asynchronous processing | Releases thread immediately | High under load | Low delay | [OK] Good |
@Async?
@Async
public CompletableFuture<String> fetchData() {
// simulate delay
Thread.sleep(1000);
return CompletableFuture.completedFuture("Done");
}@Async
public void process() {
CompletableFuture<String> result = CompletableFuture.supplyAsync(() -> {
throw new RuntimeException("Fail");
});
System.out.println(result.get());
}Pass the test and this pattern moves unknown