Object Pool Pattern
MediumConcurrencyObject PoolBlockingQueueSemaphoreResource ManagementConnection Pool
Problem Statement
Design a generic, thread-safe Object Pool that manages reusable expensive-to-create objects (e.g., database connections, socket connections, parser instances). Objects are borrowed from the pool, used, and returned. If no objects are available, the caller blocks (or times out).
class ObjectPool<T> {
public ObjectPool(int maxSize, Supplier<T> factory) {}
// Borrow an object; blocks until one is available (or timeout)
public T acquire() throws InterruptedException {}
public T acquire(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException {}
// Return object to pool for reuse
public void release(T obj) {}
// Release object permanently (don't return to pool)
public void invalidate(T obj) {}
public int availableCount() {}
public void shutdown() {}
}
Key Entities
- BlockingDeque/BlockingQueue: Holds available pooled objects.
- Semaphore(maxSize): Limits concurrent borrows to pool size.
- Factory (Supplier<T>): Creates new objects when pool is initially filling.
- Set<T> borrowed: Tracks all objects currently in use (for validation in release).
Requirements
- Lazy initialization: create objects only when needed (up to maxSize).
acquire()blocks when all objects are borrowed;acquire(timeout)returns null on timeout.release()must return a valid, non-null object back to the pool.invalidate()removes the object permanently and may trigger creation of a replacement.- Pool must be thread-safe for concurrent borrows and returns.
Asked at: Amazon, Google, Oracle, Netflix, Uber, LinkedIn
!Constraints
- 1 ≤ maxSize ≤ 100
- Objects must not be returned to the pool more than once (double-return detection).
- Timeout precision: millisecond granularity.
- Pool must not create more than maxSize objects total.
- shutdown() must drain remaining borrows and close/destroy all objects.
Output
Run or submit your code to see output here.