Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.util.concurrent.*;
- class Solution {
- // Java 17 record
- record TaskResult(String taskId, String status, String result) {}
- // Custom thread-safe map with eviction + order
- static class CustomMap<K, V> {
- private final int capacity;
- private final LinkedHashMap<K, V> map;
- public CustomMap(int capacity) {
- this.capacity = capacity;
- this.map = new LinkedHashMap<>();
- }
- public synchronized void put(K key, V value) {
- if (map.size() >= capacity) {
- K oldestKey = map.keySet().iterator().next();
- map.remove(oldestKey); // evict oldest
- }
- map.put(key, value);
- }
- public synchronized List<V> snapshot() {
- return new ArrayList<>(map.values());
- }
- }
- public void solve() {
- int capacity = 5;
- CustomMap<String, TaskResult> store = new CustomMap<>(capacity);
- ExecutorService executor = Executors.newFixedThreadPool(5);
- List<CompletableFuture<Void>> futures = new ArrayList<>();
- for (int i = 1; i <= 10; i++) {
- String taskId = "Task-" + i;
- CompletableFuture<Void> future = CompletableFuture
- .supplyAsync(() -> {
- try {
- // simulate work
- Thread.sleep(new Random().nextInt(2000));
- if (new Random().nextInt(5) == 0) {
- throw new RuntimeException("Error");
- }
- return "Result-" + taskId;
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }, executor)
- // timeout handling
- .orTimeout(1, TimeUnit.SECONDS)
- .handle((res, ex) -> {
- if (ex != null) {
- if (ex instanceof TimeoutException) {
- store.put(taskId, new TaskResult(taskId, "TIMEOUT", null));
- } else {
- store.put(taskId, new TaskResult(taskId, "FAILED", null));
- }
- } else {
- store.put(taskId, new TaskResult(taskId, "SUCCESS", res));
- }
- return null;
- });
- futures.add(future);
- }
- // wait for all tasks
- CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
- executor.shutdown();
- // summary
- List<TaskResult> results = store.snapshot();
- long success = results.stream().filter(r -> r.status.equals("SUCCESS")).count();
- long failed = results.stream().filter(r -> r.status.equals("FAILED")).count();
- long timeout = results.stream().filter(r -> r.status.equals("TIMEOUT")).count();
- System.out.println("Summary:");
- System.out.println("SUCCESS: " + success);
- System.out.println("FAILED: " + failed);
- System.out.println("TIMEOUT: " + timeout);
- System.out.println("\nOrdered Snapshot:");
- for (TaskResult r : results) {
- System.out.println(r);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment