Async Task Executor
HardConcurrencyExecutorServiceFutureCompletableFutureThread PoolAsync
Problem Statement
Design an Async Task Executor that accepts tasks with optional dependencies. A task should only execute after all its dependent tasks have completed. Tasks with no pending dependencies run immediately (in parallel). The executor manages a thread pool internally.
class AsyncTaskExecutor {
public AsyncTaskExecutor(int threadPoolSize) {}
// Submit a task with no dependencies
public Future<Void> submit(String taskId, Runnable task) {}
// Submit a task that depends on listed taskIds completing first
public Future<Void> submit(String taskId, Runnable task, List<String> dependsOn) {}
public void shutdown() throws InterruptedException {}
public TaskStatus getStatus(String taskId) {}
public long getCompletionTime(String taskId) {}
}
enum TaskStatus { PENDING, RUNNING, COMPLETED, FAILED }
Key Entities
- ExecutorService: Underlying thread pool for task execution.
- CompletableFuture: Represents async task completion and chains dependencies.
- DAG (Directed Acyclic Graph): Tracks task dependency graph.
- ConcurrentHashMap<String, CompletableFuture>: Maps taskId → future for dependency resolution.
Requirements
- Tasks with satisfied dependencies run immediately on the thread pool.
- A task waits (non-blocking for the caller) until all its dependencies complete.
- If a dependency fails, dependent tasks are marked FAILED too (cascading failure).
- Detect and reject cyclic dependencies.
- Thread-safe status tracking.
Asked at: Google, Amazon, Microsoft, Uber, Netflix, Airbnb, LinkedIn
!Constraints
- Task IDs are unique non-empty strings.
- Dependency graph must be a DAG (no cycles).
- Thread pool size: 1–50.
- A task submitted before its dependencies exist should queue until dependencies are submitted.
- Circular dependencies should throw IllegalArgumentException.
Output
Run or submit your code to see output here.