-
Notifications
You must be signed in to change notification settings - Fork 243
implemented cacheable AsyncRequestProcessor #237
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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<>(); | ||
| } | ||
|
|
||
| public CompletableFuture<UserData> processRequest(String userId) { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 A robust way to solve this, while keeping the required
|
||
| 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) | ||
| ); | ||
| } | ||
| } | ||
There was a problem hiding this comment.
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 toMap<String, CompletableFuture<UserData>>and store/return futures directly (thencomputeIfAbsentcan install an in-flight future).