Implementing an asynchronous data processing pipeline
You're building an analytics dashboard that needs to fetch user data and activity logs from separate services, then process them to create a user summary. This operation should be performed asynchronously to keep your application responsive. You are tasked to implement this using CompletableFuture
.
This exercise is part of the course
Optimizing Code in Java
Exercise instructions
- Add fetching user data in the
CompletableFuture
. - Add processing user data in the
CompletableFuture
. - Add exception handling in the
CompletableFuture
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
import java.util.*;
import java.util.concurrent.CompletableFuture;
public class AsyncDashboard {
public static void main(String[] args) throws Exception {
CompletableFuture userSummaryFuture = CompletableFuture
// Fetch the user data
.____(() -> fetchUserData("user123"))
// Create summary based on fetched data
.____(userData -> createSummary(userData))
// Add exception handling
.____(ex -> new UserSummary(new UserData("error", "Error User")));
Thread.sleep(5000);
}
private static UserData fetchUserData(String userId) {
simulateNetworkLatency(300);
return new UserData(userId, "John Doe");
}
private static UserSummary createSummary(UserData userData) {
simulateNetworkLatency(200);
return new UserSummary(userData);
}
private static void simulateNetworkLatency(int millis) {
try { Thread.sleep(millis); } catch (InterruptedException e) {}
}
static class UserData {
String id, name;
UserData(String id, String name) {
this.id = id;
this.name = name;
}
}
static class UserSummary {
UserData userData;
UserSummary(UserData userData) {
this.userData = userData;
}
}
}