Scoped-down version of what could easily spiral into a full system design problem.
Start by clarifying requirements: pool size, blocking vs non-blocking acquire, timeout, and whether connections are pre-created. Then design a thread-safe pool using a queue and condition variable (or semaphore), and implement acquire/release with proper synchronization and error handling. Finally, discuss trade-offs like fairness, resource cleanup, and scalability.
Pro tip: Mention that release should validate the connection and handle broken connections by discarding and replacing them, not just returning to the pool. Also, consider using a timeout on acquire to avoid indefinite blocking, which is crucial in production systems.
Ask about expected pool size, concurrency level, blocking behavior, timeout, and whether connections are created lazily or eagerly. Confirm that db.query is mocked and we only need to manage connection objects.
Use a thread-safe queue (e.g., LinkedBlockingQueue) or a list with a condition variable to store available connections. Use a lock and condition to block acquire when pool is empty and signal release when a connection is returned.
acquire: wait until a connection is available or timeout, then remove and return it. release: return the connection to the pool and notify waiting threads. Handle edge cases like releasing a connection not from the pool or double release.
On release, check if the connection is still valid (e.g., not closed). If invalid, discard it and optionally create a new one to maintain pool size. On acquire, if timeout occurs, throw an exception or return null based on requirements.
Talk about fairness (FIFO vs LIFO), scalability (lock contention), and alternatives like semaphores. Mention metrics, dynamic pool sizing, and health checks as potential improvements.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.