BaşlayınÜcretsiz Başlayın

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.

Bu egzersiz

Optimizing Code in Java

kursunun bir parçasıdır
Kursu Görüntüle

Egzersiz talimatları

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

Uygulamalı interaktif egzersiz

Bu örnek kodu tamamlayarak bu egzersizi bitirin.

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) {}
    }
}
Kodu Düzenle ve Çalıştır