Comece agoraComece grátis

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 exercicio faz parte do curso

Optimizing Code in Java

Ver curso

Instruções do exercicio

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

exercicio interativo prático

Tente este exercicio completando este código de exemplo.

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 e Executar Código