Motivation: Creating and destroying certain objects (e.g., database connections, threads) is expensive, and the application needs many short-lived instances.
Intent: Manage a pool of reusable objects, lending them out on demand and reclaiming them when no longer in use, rather than creating and destroying them repeatedly.
This is a pool of resources that can be lent out and returned when needed (connection pool, thread pool).
class ConnectionPool(private val maxSize: Int) {
private val available = ArrayDeque<Connection>()
private val inUse = mutableSetOf<Connection>()
fun acquire(): Connection {
val conn = if (available.isNotEmpty()) available.removeFirst()
else Connection()
inUse.add(conn)
return conn
}
fun release(conn: Connection) {
inUse.remove(conn)
conn.reset()
available.addLast(conn)
}
}