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.
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
- Build an in-memory pub-sub with topics, many subscribers per topic and at-least-once delivery. How does a message get redelivered?hardAlso on concurrency6 min
- Design an in-memory job scheduler that runs one-off, delayed and recurring jobs. Write the core classes.hardAlso on concurrency6 min
- A flash sale decrements stock from many threads. Do you go optimistic or pessimistic, and how do you prove nothing oversold?mediumAlso on concurrency5 min
- Design a movie ticket booking system with shows, seats and a temporary hold that expires if the user does not pay. Write the classes.hardAlso on concurrency6 min