Skip to content

implemented cacheable AsyncRequestProcessor#237

Open
letmerelaxpls wants to merge 3 commits into
mate-academy:mainfrom
letmerelaxpls:hw-jv-async-request-processor
Open

implemented cacheable AsyncRequestProcessor#237
letmerelaxpls wants to merge 3 commits into
mate-academy:mainfrom
letmerelaxpls:hw-jv-async-request-processor

Conversation

@letmerelaxpls

Copy link
Copy Markdown

No description provided.

@mateacademy-ai-mentor mateacademy-ai-mentor left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Review Summary

I am requesting changes because one core requirement of the task is currently violated and this affects the functional behavior of the async cache. In AsyncRequestProcessor.java, the cache lookup and insertion are done inside CompletableFuture.supplyAsync, so even when a userId is already cached, you still schedule work on the executor instead of returning an already-completed future immediately; this breaks the requirement that repeated requests should be served from the cache right away. To fix this, either (1) first do a direct lookup like UserData cached = cache.get(userId); if (cached != null) return CompletableFuture.completedFuture(cached); before scheduling, or (2) change the cache type to Map<String, CompletableFuture<UserData>> and use computeIfAbsent on futures so you can return an in-flight or completed future immediately. Also in the computeIfAbsent lambda, you currently capture the outer userId instead of using the lambda parameter (e.g., id), both for constructing UserData and for the exception message; this can be confusing and should be corrected so the mapping consistently uses its key parameter. These issues are critical for meeting the task’s checklist about immediate cache hits and correct mapping behavior, but your overall structure with CompletableFuture, the ConcurrentHashMap, and the main flow in Main.java is on the right track. Once you adjust the cache behavior and lambda parameter usage, your solution should satisfy the functional requirements more accurately.


✨ Please rate this review in the Platform's notification center1. I will be grateful for your feedback! ✨

Important

Fix the issues, commit the changes, and then re-request my review using the Re-request review button2 in the Reviewers tab.

Tip

If you have any comments about this review, please leave a message in the Add a comment section below and mention me with the @mateacademy-ai-mentor tag3.
I will read your message during my next review of your pull request. Please do not reply directly to my comments, as that feature is not supported yet.

Caution

Do not close the pull request until the review is complete. Closing it early can lead to unexpected behavior and disrupt the review process.

Footnotes

  1. Rate AI review example

  2. Re-request AI review example

  3. Add AI review comments example

Comment on lines +18 to +27
return CompletableFuture.supplyAsync(() -> cache.computeIfAbsent(userId, id -> {
try {
UserData userData = new UserData(userId, "Details for " + userId);
Thread.sleep(1000);
return userData;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Request for " + userId + " was interrupted");
}
}), executor);

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 code wraps cache.computeIfAbsent(...) inside CompletableFuture.supplyAsync, which means cached values are still looked up on a worker thread and callers won't receive an already-completed future. This violates the requirement to "check if the userId is already in the cache. If yes, return the cached result immediately." Consider doing UserData cached = cache.get(userId); if (cached != null) return CompletableFuture.completedFuture(cached); before scheduling, or change the cache to Map<String, CompletableFuture<UserData>> so you can computeIfAbsent a future and return it immediately (also deduplicates in-flight requests).

return null;
return CompletableFuture.supplyAsync(() -> cache.computeIfAbsent(userId, id -> {
try {
UserData userData = new UserData(userId, "Details for " + 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.

Inside the computeIfAbsent mapping function you use the outer userId variable. Use the mapping parameter id instead (e.g. new UserData(id, "Details for " + id)) to avoid capturing the outer variable and to ensure the mapping uses the correct key value.


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).

return userData;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Request for " + userId + " was interrupted");

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 exception message inside the mapping uses the outer userId. Prefer using the mapping key id so the message accurately reflects the key being processed (and avoids confusion if variable capture changes).

@mateacademy-ai-mentor mateacademy-ai-mentor left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Review Summary

Great job implementing the initial cache check before scheduling the asynchronous task! Your solution is very close, but this requires a change to address a subtle but important race condition.

Currently, if two requests for the same new userId arrive concurrently, both will find the cache empty and proceed to execute the expensive processing task. This leads to redundant work and violates the requirement that repeated requests should be served faster from the cache.

To fix this, you can manage the in-flight operations. A common pattern is to use a map to store the CompletableFuture itself, for example, Map<String, CompletableFuture<UserData>>. By using computeIfAbsent on this map, you can ensure only one expensive task is ever created for a given userId, and any subsequent requests for that ID would get the same in-progress future to await.


✨ Please rate this review in the Platform's notification center1. I will be grateful for your feedback! ✨

Important

Fix the issues, commit the changes, and then re-request my review using the Re-request review button2 in the Reviewers tab.

Tip

If you have any comments about this review, please leave a message in the Add a comment section below and mention me with the @mateacademy-ai-mentor tag3.
I will read your message during my next review of your pull request. Please do not reply directly to my comments, as that feature is not supported yet.

Caution

Do not close the pull request until the review is complete. Closing it early can lead to unexpected behavior and disrupt the review process.

Footnotes

  1. Rate AI review example

  2. Re-request AI review example

  3. Add AI review comments example

cache = new ConcurrentHashMap<>();
}

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()).

@mateacademy-ai-mentor mateacademy-ai-mentor left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Review Summary

Excellent work! Your solution is approved. You've perfectly solved the race condition by caching the CompletableFuture itself, which is the most robust and efficient way to handle this scenario. Using computeIfAbsent is the ideal, thread-safe approach here. While the task description literally mentioned a Map<String, UserData>, your choice to use Map<String, CompletableFuture<UserData>> shows a deeper understanding of concurrency and was the correct decision to meet the core requirement of preventing duplicate processing. This is a fantastic implementation. Great job!


✨ Please rate this review in the Platform's notification center1. I will be grateful for your feedback! ✨

Footnotes

  1. Rate AI review example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants