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
23 changes: 22 additions & 1 deletion src/main/java/mate/academy/AsyncRequestProcessor.java
Original file line number Diff line number Diff line change
@@ -1,16 +1,37 @@
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, UserData> cache = new ConcurrentHashMap<>();

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

public CompletableFuture<UserData> processRequest(String userId) {
return null;
UserData userData = cache.get(userId);
if (userData != null) {
return CompletableFuture.completedFuture(userData);
}

return CompletableFuture.supplyAsync(
() -> cache.computeIfAbsent(userId, this::processUserData),
executor
);
}

private UserData processUserData(String userId) {
try {
Thread.sleep(1000); // Simulate processing delay
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
return new UserData(userId, "Details for " + userId);
}
}
3 changes: 2 additions & 1 deletion src/main/java/mate/academy/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@

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

// Simulating multiple concurrent requests
Expand Down