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
32 changes: 31 additions & 1 deletion src/main/java/mate/academy/AsyncRequestProcessor.java
Original file line number Diff line number Diff line change
@@ -1,16 +1,46 @@
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<>();
private final Map<String, CompletableFuture<UserData>> inFlight =
new ConcurrentHashMap<>();

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

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

return inFlight.computeIfAbsent(userId, id ->
CompletableFuture.supplyAsync(() -> {
simulateDelay();
return new UserData(id, "Details for " + id);
Comment on lines +27 to +29

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 lambda constructs the UserData correctly ("Details for " + id) which matches checklist item #16 — good. However, after the UserData is produced you must store the result into the required Map<String, UserData> cache (checklist item #13). Consider attaching a whenComplete/thenApply handler on the in-flight future to put the finished UserData into cache and remove the entry from the in-flight map.

}, executor).whenComplete((result, error) -> {
inFlight.remove(id);
if (error == null) {
cache.put(id, result);
}
})
);
}

private void simulateDelay() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
21 changes: 8 additions & 13 deletions src/main/java/mate/academy/Main.java
Original file line number Diff line number Diff line change
@@ -1,26 +1,21 @@
package mate.academy;

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

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

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 input array matches the requirement ({"user1", "user2", "user3", "user1"}). If the tests expect the exact ordering from the spec, avoid printing inside thenAccept. Instead collect results together with their original index and print them in input order after CompletableFuture.allOf(...).join() so the console sequence matches the required output.


for (int i = 0; i < userIds.length; i++) {
String userId = userIds[i];
futures[i] = asyncRequestProcessor.processRequest(userId)
.thenAccept(userData -> System.out.println("Processed: " + userData));
for (String userId : userIds) {
processor.processRequest(userId)
.thenAccept(result ->
System.out.println("Processed: " + result));
}

// Wait for all futures to complete
CompletableFuture.allOf(futures).join();
executor.shutdown();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Calling executor.shutdown() immediately may not wait for the submitted asynchronous tasks to finish; the JVM can exit before all thenAccept prints run. Collect the returned CompletableFuture<UserData> instances (e.g., in a list) and wait for them to complete with CompletableFuture.allOf(...).join() or use executor.shutdown(); executor.awaitTermination(...) before exiting to ensure all results are printed.

}
}
1 change: 0 additions & 1 deletion src/main/java/mate/academy/UserData.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
package mate.academy;

public record UserData(String userId, String details) {

}