Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion src/main/java/mate/academy/AsyncRequestProcessor.java
Original file line number Diff line number Diff line change
@@ -1,16 +1,29 @@
package mate.academy;

import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;

public class AsyncRequestProcessor {
private static final Map<String, UserData> cache = new ConcurrentHashMap<>();
private final Executor executor;

public AsyncRequestProcessor(Executor executor) {
this.executor = executor;
}

public CompletableFuture<UserData> processRequest(String userId) {
return null;
return CompletableFuture.supplyAsync(() ->
cache.computeIfAbsent(userId, id -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(
"Error while processing request: " + id, e);
}
return new UserData(id, "Details for " + id);
}), executor);
}
}
6 changes: 2 additions & 4 deletions src/main/java/mate/academy/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,13 @@

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
public static void main(String[] args) {
// Feel free to play with AsyncRequestProcessor in this main method if you want
ExecutorService executor = null; // Provide implementation that fits your needs
ExecutorService executor = Executors.newCachedThreadPool();
AsyncRequestProcessor asyncRequestProcessor = new AsyncRequestProcessor(executor);

// Simulating multiple concurrent requests
String[] userIds = {"user1", "user2", "user3", "user1"}; // Note: "user1" is repeated
CompletableFuture<?>[] futures = new CompletableFuture[userIds.length];

Expand All @@ -19,7 +18,6 @@ public static void main(String[] args) {
.thenAccept(userData -> System.out.println("Processed: " + userData));
}

// Wait for all futures to complete
CompletableFuture.allOf(futures).join();
executor.shutdown();
}
Expand Down
Loading