ComenzarEmpieza gratis

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.

The UserData and UserSummary classes have been preloaded for you.

Este ejercicio forma parte del curso

Optimizing Code in Java

Ver curso

Instrucciones del ejercicio

  • Add fetching user data in the CompletableFuture.
  • Add processing user data in the CompletableFuture.
  • Add exception handling in the CompletableFuture.

Ejercicio interactivo práctico

Prueba este ejercicio y completa el código de muestra.

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) {}
    }
}
Editar y ejecutar código