Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.util.stream.*;
- import java.lang.*;
- import java.io.*;
- import java.util.concurrent.*;
- import java.util.concurrent.atomic.AtomicInteger;
- class Solution {
- public sealed interface TaskOutcome permits TaskSuccess, TaskFailure, TaskTimeout { String taskId(); }
- public record TaskSuccess(String taskId, Object result) implements TaskOutcome {}
- public record TaskFailure(String taskId, Throwable error) implements TaskOutcome {}
- public record TaskTimeout(String taskId) implements TaskOutcome {}
- public record ExecutionSummary(int submitted, int success, int failed, int timeout, Map<String, TaskOutcome> snapshot) {}
- static class CustomBoundedMap<K, V> {
- class Node { K k; V v; Node p, n; Node(K k, V v) { this.k = k; this.v = v; } }
- private final int cap;
- private final Map<K, Node> m = new HashMap<>();
- private Node head, tail;
- CustomBoundedMap(int cap) { this.cap = cap; }
- public synchronized void put(K k, V v) {
- if (m.containsKey(k)) { m.get(k).v = v; return; }
- if (m.size() >= cap && head != null) {
- m.remove(head.k);
- head = head.n;
- if (head != null) head.p = null; else tail = null;
- }
- Node nn = new Node(k, v);
- if (tail == null) head = tail = nn; else { tail.n = nn; nn.p = tail; tail = nn; }
- m.put(k, nn);
- }
- public synchronized Map<K, V> snapshot() {
- Map<K, V> snap = new LinkedHashMap<>();
- for (Node c = head; c != null; c = c.n) snap.put(c.k, c.v);
- return snap;
- }
- }
- static class ProcessingEngine {
- private final ExecutorService exec;
- private final CustomBoundedMap<String, TaskOutcome> storage;
- public ProcessingEngine(int threads, int cap) {
- this.exec = Executors.newFixedThreadPool(threads);
- this.storage = new CustomBoundedMap<>(cap);
- }
- public ExecutionSummary processTasks(Map<String, Callable<Object>> tasks, long timeout, TimeUnit unit) {
- var s = new AtomicInteger(); var f = new AtomicInteger(); var t = new AtomicInteger();
- var futures = tasks.entrySet().stream().map(e -> CompletableFuture.supplyAsync(() -> {
- try { return e.getValue().call(); } catch (Exception ex) { throw new CompletionException(ex); }
- }, exec).orTimeout(timeout, unit).handle((res, ex) -> {
- String id = e.getKey();
- if (ex == null) { s.incrementAndGet(); storage.put(id, new TaskSuccess(id, res)); }
- else if (ex.getCause() instanceof TimeoutException) { t.incrementAndGet(); storage.put(id, new TaskTimeout(id)); }
- else { f.incrementAndGet(); storage.put(id, new TaskFailure(id, ex.getCause())); }
- return null;
- })).toArray(CompletableFuture[]::new);
- CompletableFuture.allOf(futures).join();
- return new ExecutionSummary(tasks.size(), s.get(), f.get(), t.get(), storage.snapshot());
- }
- public void shutdown() { exec.shutdown(); }
- }
- public void solve() {
- ProcessingEngine engine = new ProcessingEngine(4, 4);
- Map<String, Callable<Object>> tasks = new LinkedHashMap<>();
- tasks.put("task-1", () -> "Completed Fast");
- tasks.put("task-2", () -> { throw new RuntimeException("Simulated Failure"); });
- tasks.put("task-3", () -> { Thread.sleep(2000); return "Will Timeout"; });
- tasks.put("task-4", () -> "Completed Fast 2");
- tasks.put("task-5", () -> "Completed Fast 3");
- ExecutionSummary summary = engine.processTasks(tasks, 500, TimeUnit.MILLISECONDS);
- System.out.println("Submitted: " + summary.submitted());
- System.out.println("Success: " + summary.success());
- System.out.println("Failed: " + summary.failed());
- System.out.println("Timeout: " + summary.timeout());
- summary.snapshot().forEach((key, outcome) ->
- System.out.println(key + " -> " + outcome.getClass().getSimpleName())
- );
- engine.shutdown();
- }
- }
- public class Main {
- public static void main(String[] args) {
- Solution solution = new Solution();
- solution.solve();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment