KatInterview

Design a Concurrent Fixed-Size Thread Pool with Task Futures

Data Structure DesignModel answer
MediumModel answerData Structure Designconcurrencythread-pooldesign

Last updated

Design and implement a fixed-size thread pool with safe task queueing, future result retrieval, exception handling, and graceful or forced shutdown mechanism using basic locks and condition variables.

Design and implement a reusable, fixed-size thread pool from scratch. The system should allow client threads to submit asynchronous tasks, receive handle objects (Futures) to obtain task results or exceptions, and gracefully or forcefully terminate the pool.

You must rely on native synchronization primitives (such as mutexes/locks and condition variables/events). Do not use high-level language built-in thread pool implementations or executor frameworks (e.g., Python's concurrent.futures, Java's ExecutorService, or C++ std::async).

Requirements and API Design

  1. Task Submission & Futures:

    • Expose a submit(task) method accepting a callable.
    • Return a Future object that caller threads can use to block and wait for the result (get()) or retrieve any exception thrown during task execution.
  2. Concurrency & Thread Safety:

    • Multiple threads may submit work concurrently, including worker threads within the pool submitting sub-tasks.
    • Idle worker threads must sleep efficiently on a condition variable without busy-waiting or missing wake-up signals.
    • A worker thread must never hold the shared queue lock while executing a user task.
  3. Shutdown Modes:

    • shutdown(graceful=True): Stop accepting new task submissions. Allow already queued and active tasks to finish before stopping all worker threads.
    • shutdown(graceful=False): Stop accepting new submissions, discard pending (unstarted) tasks in the queue, and notify any threads waiting on those unstarted tasks with a cancellation exception.
  4. Queue Capacity & Rejection Strategy:

    • Support a maximum queue capacity (max_queue_size).
    • If the queue is full or if the pool is already shut down, new calls to submit should raise a RejectedExecutionError.

Constraints & Edge Cases

  • Ensure no caller thread remains indefinitely blocked on a Future.get() call if the pool shuts down or if a task fails/cancels.
  • Account for potential deadlocks when tasks submitted to the pool wait on other tasks submitted to the same pool.

Hints

Hint 1

Ensure task state transition (Pending -> Completed/Failed/Cancelled) is guarded by a mutex per Future or a unified synchronization mechanism to prevent race conditions during `Future.get()`.

Hint 2

Always invoke user functions *outside* of the primary queue lock. Holding the main queue lock during execution prevents other workers from picking up queued tasks.

Hint 3

When performing a non-graceful shutdown, ensure all waiting futures in the pending queue receive an explicit cancellation signal so calling threads do not block indefinitely.