Thread-Safe, Lazily Initialized Connection Pool
Context
You need to design a thread-safe connection pool in Python that lazily creates connections and reuses them. The pool should cap the number of total connections and block callers when no connections are available. A PooledConnection wrapper should ensure that calling close returns the connection to the pool instead of closing the underlying connection.
Assumptions:
-
Language: Python, multi-threaded environment.
-
A connection factory (callable) can be provided to create new underlying connections. For demonstration, a simple stub Connection is used.
Requirements
Implement the following classes and methods:
-
ConnectionPool
-
init
(maxConnectionNum, connection_factory=None)
-
getConnection(timeout=None)
-
close()
-
PooledConnection
-
init
(pool, raw_connection)
-
close()
Behavioral constraints:
-
Lazy initialization: do not create connections in
init
.
-
Reuse idle connections when available.
-
Create a new connection on getConnection only if there are no idle connections and the total created is below maxConnectionNum.
-
Cap total connections at maxConnectionNum. When the cap is reached and no idle connections exist, getConnection should block (optionally with timeout) until one is returned.
-
PooledConnection.close returns the connection to the pool (idempotent); it should not close the underlying connection unless the pool is closed.
-
Pool close() closes idle connections immediately, marks the pool as closed, and causes future getConnection calls to fail. Connections returned after close should be closed rather than re-pooled.