Skip to content
Preptima
hardCodingDesignMidSenior

Implement a thread-safe pool of N connections with acquire, release and a timeout.

A thread-safe connection pool pairs a Semaphore of N permits, which bounds how many connections exist and gives acquire its timeout, with a queue of idle connections. Acquire returns a lease that releases exactly once from a finally block, and a broken connection is discarded without losing its permit.

6 min readUpdated 2026-10-10Target archetype: Big Tech, Enterprise Captive, Product Startup

Answer

Short answer

Bound the connection pool with a Semaphore of N permits and keep idle connections in a concurrent queue. acquire takes a permit with tryAcquire(timeout, unit), reuses a valid idle connection or opens a new one, and returns a lease. Closing the lease puts the connection back, or discards it if broken, then releases the permit exactly once. Callers use try-with-resources, so release happens in a finally.

Was this answer helpful?

Likely follow-ups

  • Callers forget to release under an exception path. How would the pool detect a leaked lease and report where it was taken?
  • Validating with isValid on every borrow adds a round trip. When would you skip it, and what do you check instead?
  • How do you shut the pool down while leases are still out, without closing a connection mid-query?
  • Why would you choose a fair Semaphore here, and what throughput does fairness cost?

Related questions

Further reading