Opening a database connection is expensive, so applications keep a bounded pool of connections and lend them to callers. When every connection is active, new callers wait until a connection is released.
Design a ConnectionPool class:
ConnectionPool(int poolSize) creates a pool containing poolSize connections. Initially, no connection is active and no caller is waiting.boolean acquire() returns true and occupies one connection when a connection is immediately available. If the pool is full, it queues the caller and returns false.void release() releases one active connection. If callers are waiting, the connection is handed directly to the oldest waiter, so the number of active connections does not change. Otherwise, the connection becomes free.
Every release call is valid: at least one connection is active when it occurs. Queued callers are tracked in arrival order, but because all callers are equivalent, only the queue length is required.
Example 1:
Input:
Output:
Explanation: The first two acquires occupy both connections. The third caller waits. The release hands its connection directly to that waiter, so the pool remains full and the final acquire also waits.
Example 2:
Input:
Output:
Explanation: No caller is waiting at either release, so the connection becomes free and the next acquire succeeds.
Constraints
1 <= poolSize <= 10^5- At most
10^5 calls are made to acquire and release. - Every call to
release occurs while at least one connection is active. - Waiting callers never cancel and are served before later callers.