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
17 changes: 16 additions & 1 deletion src/main/java/mate/academy/AsyncRequestProcessor.java
Original file line number Diff line number Diff line change
@@ -1,16 +1,31 @@
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 Map<String, CompletableFuture<UserData>> cache;

public AsyncRequestProcessor(Executor executor) {
this.executor = executor;
cache = new ConcurrentHashMap<>();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The cache is declared and instantiated as a ConcurrentHashMap, which is correct. If you want immediate-return semantics and to deduplicate concurrent requests, consider changing the cache type to Map<String, CompletableFuture<UserData>> and store/return futures directly (then computeIfAbsent can install an in-flight future).

}

public CompletableFuture<UserData> processRequest(String userId) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a great improvement, and you've correctly added the initial cache check.

However, there's a subtle race condition that causes a requirement to be missed. In Main.java, two requests for "user1" are dispatched very quickly. Both will call cache.get("user1"), find it empty, and proceed to schedule a new expensive task. This violates the requirement that "Repeated requests for the same userId should be served from the cache, significantly reducing the response time."

A robust way to solve this, while keeping the required Map<String, UserData> for caching final results, is to use a second map to manage in-flight operations. For example:

  1. Create a Map<String, CompletableFuture<UserData>> inFlightRequests.
  2. Use inFlightRequests.computeIfAbsent() to create and store a CompletableFuture for a new userId. This ensures only one task is ever created.
  3. When the future completes, you can add its result to the main cache and remove it from the inFlightRequests map (e.g., using .whenComplete()).

return null;
return cache.computeIfAbsent(userId, id ->
CompletableFuture.supplyAsync(() -> {
try {
UserData userData = new UserData(userId, "Details for " + id);
Thread.sleep(1000);
return userData;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Request for " + id + " was interrupted");
}
},executor)
);
}
}
7 changes: 3 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,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(3);
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 +19,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