KatInterview

Design a Thread-Safe Resource Pool with RAII Handles

Data Structure DesignModel answer
HardModel answerData Structure Designconcurrencyc++raii

Last updated

Build a concurrent object pool in C++ that safely manages reusable resources with blocking acquisition, automatic return via RAII, and graceful shutdown.

You need to implement a production-quality object pool in C++ that manages a collection of reusable resources under concurrent access. The pool should support safe borrowing and returning of objects across multiple threads while preventing common concurrency bugs.

Your implementation must satisfy these requirements:

Core Operations:

  • borrow() acquires an object from the pool. If none are available and the pool hasn't reached maximum capacity, create a new one. If at capacity, block until an object becomes available. Support an optional timeout parameter.
  • returnObject(obj) returns an object to the pool for reuse. Validate that the object belongs to this pool and hasn't been returned already.
  • Objects should be reset to a clean state before being made available again.

RAII Handle:

  • Design a scoped handle type returned by borrow() that automatically returns the object when the handle goes out of scope.
  • The handle must be movable (to allow returning from functions and storing in containers) but not copyable (to prevent double-return).

Concurrency & Safety:

  • Use std::mutex and std::condition_variable to coordinate access; avoid busy-waiting.
  • Ensure fairness: threads waiting longest should acquire objects first.
  • Prevent race conditions, double-free bugs, and use-after-free errors.
  • Guard against returning the same object multiple times or returning objects that don't belong to the pool.

Shutdown:

  • The destructor must cleanly terminate all operations: wake blocked threads, prevent new borrows, and release all managed resources without deadlocks.

Testing:

  • Provide tests demonstrating correct behavior with at least 10 threads concurrently borrowing and returning objects.
  • Show that the pool correctly limits capacity and blocks/unblocks as expected.

Assume C++17 or later. Document time complexity for borrow() and returnObject(). Explain key design choices and potential failure modes.

Hints

Hint 1

Consider using a queue or deque to store available objects and maintain FIFO ordering for fairness.

Hint 2

Use std::unique_ptr with a custom deleter in your handle to automatically return objects; this enables move semantics naturally.

Hint 3

Track each object's state (available, borrowed) to detect invalid returns; consider storing metadata alongside each object or using a set of valid addresses.