Task Submission and Synchronization (LLD)

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2022-02-28

Problem Statement

Design and implement a lightweight task execution framework that provides APIs similar to Thread.start() and Thread.join(), but abstracted as submit(task) and block_until_finish().


Functional Requirements


1.<span></span>APIs to Implement
2.<span></span>submit(task)
3.<span></span>Accepts a unit of work (Runnable/Callable/lambda).
4.<span></span>Starts execution asynchronously in a separate thread.
5.<span></span>Returns a TaskHandle (or equivalent) representing the submitted task.
6.<span></span>block_until_finish()
7.<span></span>Blocks the calling thread until the submitted task finishes execution.
8.<span></span>Should be callable on the TaskHandle.
9.<span></span>Task Behavior
10.<span></span>Each task runs independently in its own thread.
11.<span></span>Multiple tasks may run concurrently.
12.<span></span>If a task throws an exception, the framework should capture and expose it.
13.<span></span>Thread Safety
14.<span></span>Multiple threads should be able to call submit concurrently.
15.<span></span>block_until_finish must handle concurrent calls safely (e.g., multiple threads waiting on the same task).


Constraints


1.<span></span>No use of high-level concurrency frameworks (ExecutorService, std::async, etc.); implement using low-level primitives (Thread, synchronized, wait/notify, mutex/condition_variable).
2.<span></span>Support up to 1000 concurrent tasks.
3.<span></span>Must handle:
4.<span></span>Normal completion
5.<span></span>Exceptions in tasks
6.<span></span>Multiple waiters on the same task


Example Usage


<div><div>java</div><div>CopyEdit</div><div>TaskHandle handle = TaskManager.submit(() -> {</div><div> // some computation</div><div> System.out.println("Task running...");</div><div>});</div><div><br /></div><div>handle.block_until_finish(); // waits until task completes</div><div>System.out.println("Task finished!");</div></div>


Deliverables


1.<span></span>Class design (e.g., TaskManager, TaskHandle).
2.<span></span>Implementation of synchronization between task completion and block_until_finish.
3.<span></span>Unit tests covering:
4.<span></span>Single task execution
5.<span></span>Multiple concurrent tasks
6.<span></span>Exceptions in tasks
7.<span></span>Multiple threads waiting on the same task


Solution

Comments