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 final Executor executor;
private final Map<String, CompletableFuture<UserData>> cache = new ConcurrentHashMap<>();

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

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

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.newFixedThreadPool(4);
AsyncRequestProcessor asyncRequestProcessor = new AsyncRequestProcessor(executor);

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

for (int i = 0; i < userIds.length; i++) {
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