General Tech
1 experiences · 1p3a (1)
LLD Java Concurrency: Design Cancelled Task Tracker for ExecutorService
Interview Experience
Question You have an ExecutorService that runs tasks. When you call shutdownNow(), it returns a list of tasks that were never started. But what about the tasks that were already running and got interrupted mid‑execution? Those are gone – no trace, no list. How can you reliably track which tasks were cancelled (interrupted) during an abrupt shutdown, so you can later re‑process them? --- Key Concepts - shutdown() vs shutdownNow() shutdown(): graceful – no new tasks, but running tasks continue. shutdownNow(): abrupt – tries to interrupt running tasks and returns pending tasks. - Thread interruption Running tasks that respect interruption may throw InterruptedException or check Thread.interrupted(). shutdownNow() sets the interrupt flag on all worker threads. - Tracking in‑flight cancellations You need to know which tasks were interrupted after they started but before they completed. - Wrapper pattern Decorate an ExecutorService to add tracking logic without changing the underlying executor. --- Solution 1. Create a wrapper class that holds a reference to a real ExecutorService and a thread‑safe set (e.g., ConcurrentHashMap.newKeySet()) for cancelled tasks. 2. Override execute(Runnable r) Submit a wrapper Runnable to the real executor. Inside that wrapper: Call r.run() inside a try block. In a finally block, check if the executor is shutting down (isShutdown()) and the current thread is interrupted (Thread.currentThread().isInterrupted()). If both are true, add the original task to the cancelled set. public void execute(final Runnable runnable) { exec.execute(() -> { try { runnable.run(); } finally { if (isShutdown() && Thread.currentThread().isInterrupted()) tasksCancelledAtShutdown.add(runnable); } }); }