An airport has a few hundred luggage trolleys. You take one from the row, use it, and leave it at a stand for the next traveller. Nobody pushes a trolley someone else is using. When the row is empty, you wait for one to come back. A trolley with a broken wheel goes for repair, not back into the row.
Software has the same shape wherever an object is slow to make and only a few may exist at once. Connections to a database or a payment gateway and large buffers are lent and returned like trolleys. A thread pool keeps a few threads the same way, though callers hand it tasks rather than borrowing the threads.
The Object Pool pattern creates a few such objects, lends each one to one user at a time, and takes it back for the next. In this article we build a PNR (passenger name record) status service twice. The first version opens a new database connection for every request. The second borrows connections from a pool. Then we look at what the pool costs, when it is too much, and how it differs from Flyweight and Singleton.
All the code is Java. Every snippet without a Sketch label is cut from a project that compiles: the first-version snippet from the connection-per-request version, the rest from the finished design. Both programs run, and the outputs shown are what they print.
The service we are building
The service answers two requests: the status of a PNR, and a cancellation. Each one needs a connection to the railway's reservation database, and the database server accepts at most 4 connections from our service.
The service must:
- Answer status checks and cancellations, each over one database connection.
- Reuse connections. It opens a new one only when no open one is free.
- Keep at most a fixed number open, no more than the server's limit, however many requests arrive.
- Wait a short, bounded time when every connection is in use, then answer "busy" instead of failing or waiting forever.
- Lend each connection to one request at a time.
- Hand every request a clean connection, with no transaction left open by the request before.
- Never lend a connection it knows is broken. A connection found closed is thrown away, and a new one is opened when one is needed.
- Get every connection back, on every path out of a request, and refuse
lease.get()after the lease is closed. - Close every idle connection on shutdown, and each lent one when it comes back.
This is the figure to draw first in an interview. It names every point where the pool does work: the borrow, the reset, the check and the destroy. At each one, a weak design hands one user's mess, or a dead connection, to the next.
The first version: a new connection for every request
The obvious service opens a connection, runs its query and closes the connection:
public String status(String pnr) { Objects.requireNonNull(pnr, "pnr"); try { Connection connection = database.open(); try { return pnr + ": " + connection.query("status " + pnr); } finally { connection.close(); } } catch (DatabaseException e) { return pnr + ": could not check (" + e.getMessage() + ")"; } }This code is correct, and it is fine for a few requests a minute. The program runs it under two loads:
1,000 status checks, one after another: connections opened: 1000 time spent opening them, at 30 ms each: 30 seconds 10 status checks at the same moment, and the server allows 4 connections: answered: 4 refused: 6, each told "4521873690: could not check (too many connections)"
Every request pays for opening a connection. Opening a database connection means a network round trip, often an encrypted handshake, and a login. Our stand-in server counts opens, and we assume each one takes 30 ms. 1,000 checks open 1,000 connections, so 30 seconds go into opening connections that are each used once.
A burst goes past the server's limit. Ten checks arrive together. The first four open connections, and the server refuses the other six. Those six see "could not check", though the server could have answered them a moment later.
Nothing in our code caps the connections. There are as many as there are requests in progress, so the server's refusal is the first sign of trouble.
The idea
The pattern works like this:
- Open a connection once and lend it out many times. A request borrows one, uses it alone, and gives it back.
- Keep at most a fixed number of them, the pool's size. When every one is lent, the next borrower waits for one to come back, for a bounded time.
- Clean and check each object when it comes back, before anyone else can borrow it. A broken one is destroyed, and a new one is created when the pool needs it.
- Make giving back hard to forget, by handing the borrower something that returns the object when it is closed.
The objects being lent are the pooled objects. Taking one is borrowing or acquiring it, and giving it back is returning or releasing it. The code that borrows is the pool's client.
Building it, step by step
Step 1: what the pool needs to know about its objects
The pool should not know that it holds database connections. It needs four things from whatever it holds, and ObjectFactory names them:
public interface ObjectFactory<T> { /** Makes a new object. This is the costly step the pool exists to repeat less. */ T create(); /** Puts back anything the last borrower changed, before the next one gets it. */ void reset(T object); /** False for an object that must not be lent again, such as a closed connection. */ boolean isUsable(T object); /** Releases an object the pool is throwing away. */ void destroy(T object);}ConnectionFactory fills them in for connections:
@Override public Connection create() { return database.open(); } @Override public void reset(Connection connection) { // A borrower that left a transaction open must not hand it to the next one. if (connection.inTransaction()) { connection.rollback(); } } @Override public boolean isUsable(Connection connection) { return connection.isOpen(); } @Override public void destroy(Connection connection) { connection.close(); }Resetting rolls back a transaction the last borrower left open. A connection is usable while it is open, and destroying it closes it.
Because the pool is generic, it can lend anything that is slow to create, not only connections. The cost is one more interface than a pool written only for connections would need.
Step 2: borrowing, with a limit and a wait
borrow takes a permit, then takes an idle object or creates one:
public Lease<T> borrow(Duration timeout) throws InterruptedException { Objects.requireNonNull(timeout, "timeout"); if (timeout.isNegative()) { throw new IllegalArgumentException("timeout must not be negative, was " + timeout); } requireOpen(); if (!permits.tryAcquire(TimeUnit.NANOSECONDS.convert(timeout), TimeUnit.NANOSECONDS)) { throw new PoolExhaustedException(maxSize, timeout); } boolean lent = false; try { T object = takeIdleOrCreate(); if (closed.get()) { discard(object); // close() ran while we were taking or creating it throw new IllegalStateException("the pool is closed"); } Lease<T> lease = new Lease<>(this, object); lent = true; return lease; } finally { if (!lent) { permits.release(); } } } private T takeIdleOrCreate() { T object; while ((object = idle.pollFirst()) != null) { boolean usable = false; try { usable = isUsable(object); } finally { if (!usable) { discard(object); // even if the check threw an Error } } if (usable) { return object; } } requireOpen(); // close() may have run while we checked idle objects object = Objects.requireNonNull(factory.create(), "factory.create() returned null"); open.incrementAndGet(); return object; }A Semaphore holds one permit for each object that may be lent at once, so the pool of size 4 starts with 4 permits. Line 41 waits up to timeout for a permit. With a permit in hand, lines 63 to 75 take idle objects from the front of the list until one passes the check. A broken idle object is destroyed on the way, in a finally, even if the check throws an Error. If none is left, line 77 creates a new one.
If creating fails, the server refusing for example, the finally on line 54 gives the permit back. lent becomes true only once the lease exists, so this covers an exception and an Error alike. Without it, every failed open would shrink the pool by one for ever. TimeUnit.NANOSECONDS.convert turns a very long timeout into the longest wait a long can hold, instead of overflowing.
When are the objects created?
All of them when the pool starts
Startup opens 4 connections, and every borrow after that finds one ready. A database that is down is found at startup, not by the first user. The cost is connections held open that may never be used, and a slower start.
One at a time, when no idle one is freeOur pick
The pool opens only as many as the load has needed, up to its size. The demo's four status checks, one after another, open exactly one connection. The cost is that the first requests of a burst wait for opens, and a database that is down is found by a user.
A pool can also open a few at startup and create the rest lazily, which changes only the constructor.
What happens when every object is lent?
Wait until one comes back
permits.acquire() waits for ever. If a borrower never returns its object, every later request hangs, and nothing says why.
Refuse at once
borrow calls permits.tryAcquire() with no wait. A connection that would have come back in 2 ms is not waited for, so short bursts turn into refusals.
Wait up to a timeout, then throwOur pick
The caller picks how long it can afford to wait. PoolExhaustedException says the pool's size and how long the caller was willing to wait, and PnrService turns it into "busy, please try again". The cost is a timeout to choose: too short refuses requests a moment early, and too long keeps a person staring at a spinner.
Step 3: giving back: reset, check, then lend again
When a borrower is done, the object goes through giveBack:
/** Called once per lease, by Lease.close. */ void giveBack(T object) { boolean kept = false; try { if (!closed.get() && resetAndCheck(object)) { idle.offerFirst(object); kept = true; if (closed.get()) { drainIdle(); // close() may have emptied the idle list just before we added to it } } } finally { try { if (!kept) { discard(object); } } finally { permits.release(); } } } private boolean resetAndCheck(T object) { try { factory.reset(object); return factory.isUsable(object); } catch (RuntimeException e) { return false; // an object that cannot be reset is not lent again } }Line 106 resets the object and line 107 checks it. Line 87 puts a healthy object at the front of the idle list, so the one returned last is lent first. If the reset or the check fails or throws, kept stays false and line 96 destroys the object. Line 99 gives the permit back. Both are in finally blocks, so even an Error inside reset leaves no object half kept and no permit lost.
The reset is what makes cancel safe:
public String cancel(String pnr) { requireValid(pnr); try (Lease<Connection> lease = pool.borrow(wait)) { Connection connection = lease.get(); connection.begin(); connection.query("cancel " + pnr); connection.query("refund " + pnr); connection.commit(); return pnr + ": cancelled"; } catch (PoolExhaustedException e) { return pnr + ": " + BUSY; } catch (DatabaseException e) { // The lease is already closed here, and the pool's reset has rolled back the transaction. return pnr + ": not cancelled (" + e.getMessage() + ")"; } catch (InterruptedException e) { Thread.currentThread().interrupt(); return pnr + ": " + BUSY; } }If the refund fails, line 48's commit never runs. The try block closes the lease before the catch on line 52 runs, so the connection is already back in the pool, and the reset has rolled the half-done cancellation back. cancel could roll back itself. The pool resets anyway, because the next borrower should not depend on every earlier borrower being careful.
When is a connection checked?
Only when it comes back
This catches a connection that broke while it was lent. It misses one that was closed while it sat idle, which happens when a server or a firewall ends connections that have been quiet for a while.
Only when it is borrowed
This catches both cases, but a broken connection sits in the idle list as if it were healthy, and the pool counts it as open.
BothOur pick
A connection is checked when it comes back and again just before it is lent. The demo shows both. The cost is a check on every borrow. Ours calls isOpen(), which is enough for our fake server, because it marks a dropped connection closed. A real connection usually finds out it was dropped only when it next sends something. So a real check, such as isValid on a Java Database Connectivity (JDBC) connection, costs a round trip, and a pool can skip it for connections used a moment ago.
Step 4: a lease, so a connection is returned once
A pool that hands out the bare connection trusts every caller to give it back exactly once. borrow hands out a Lease instead:
public final class Lease<T> implements AutoCloseable { private final ObjectPool<T> pool; private final T object; private final AtomicBoolean returned = new AtomicBoolean(); Lease(ObjectPool<T> pool, T object) { this.pool = Objects.requireNonNull(pool, "pool"); this.object = Objects.requireNonNull(object, "object"); } public T get() { if (returned.get()) { throw new IllegalStateException("this lease was already returned"); } return object; } @Override public void close() { // Only the first close gives the object back; a second one does nothing. if (returned.compareAndSet(false, true)) { pool.giveBack(object); } }}Lease is AutoCloseable, so a try-with-resources block returns the connection on every way out of the block, including an exception:
public String status(String pnr) { requireValid(pnr); try (Lease<Connection> lease = pool.borrow(wait)) { return pnr + ": " + lease.get().query("status " + pnr); } catch (PoolExhaustedException e) { return pnr + ": " + BUSY; } catch (DatabaseException e) { return pnr + ": could not check (" + e.getMessage() + ")"; } catch (InterruptedException e) { Thread.currentThread().interrupt(); return pnr + ": " + BUSY; } }Line 30 of Lease lets only the first close through. compareAndSet changes returned from false to true in one step, so two threads that close the same lease at once still give it back once. Line 21 refuses get after the lease is closed.
What does a second close do?
Gives the object back again
The object is added to the idle list twice. Two later borrowers get the same connection and run their queries on it at once. This is the worst outcome, because it looks like a working pool.
Throws
A double close is a mistake, and throwing points at it. But code that closes the lease inside the block, after which try-with-resources closes it again, would fail on a harmless repeat.
Does nothingOur pick
This follows Java's Closeable rule that closing something twice has no effect. The cost is that a real double-close bug goes unnoticed. That bug can no longer hurt anyone, because the object went back only once.
Step 5: many threads at once
Every request thread shares one pool. Two structures hold its state, and both are safe to share:
- The
Semaphorecounts how many objects may still be lent. - The
ConcurrentLinkedDequeholds the idle objects. ItspollFirsthands each object to one thread, even when several threads poll at once.
The order of the steps keeps them in agreement. A borrower takes a permit before it looks for an object, and a returner puts the object back before it gives its permit back. So a thread creates a new object only when it holds a permit and finds no idle object. While the pool is open, every object that exists is idle or held by a thread with a permit. That keeps the number of open objects at or below the pool's size.
How do threads share the pool?
One lock and a Condition
borrow locks, waits on a condition while nothing is free, and unlocks. Everything sits under one lock, which is easy to reason about. But opening a connection takes milliseconds, and it must not happen while the lock is held, or every other borrower waits behind one open. So the code has to reserve a slot under the lock, open outside it, and undo the reservation if the open fails.
A Semaphore and a concurrent listOur pick
The semaphore already does the counting, the waiting and the timeout. Opening a connection happens with only a permit held, so other threads keep borrowing and returning meanwhile. The cost is the argument above: the two structures are only correct together, in that order.
demo/RaceCheck.java sends 16 threads at a pool of 4, each making 500 status checks:
16 threads, 500 status checks each, one pool of 4, and the server allows 4 checks answered: 8000 of 8000 connections the server refused: 0 most connections open at once: 4 or fewer times two threads used one connection at once: 0
Every check was answered, and the server never refused a connection. No connection was used by two threads at once. Without the semaphore, with a plain int count and an ArrayDeque, two threads can both see a free slot and both open a connection, and two threads can take the same object from the list. The server then refuses connections, and two requests share one connection.
close() runs once, and a second caller returns at once, possibly before the first has finished. It marks the pool closed, destroys the idle connections, and releases one permit. A waiting borrower takes that permit, finds the pool closed, and passes it on through the finally on line 54, so every waiter is refused in turn. A borrow that starts after the close is refused before it waits, so a shut-down service never answers "busy". giveBack destroys each lent connection when it comes back. Two races need care. A borrow that was taking a connection when the pool closed destroys it instead of lending it, on lines 47 to 50. Line 76 stops most such borrows from opening a new one, and one that gets past it just before the close has its new connection destroyed on line 48. A return that checked the flag just before the close can add its connection to the idle list after close() has emptied it, so line 89 checks again and empties the list itself. A borrow that finishes at the very moment close() runs can still hand out a lease, and that connection is destroyed when it comes back.
The finished design
Here is one status check, traced through the objects:
The whole project is below. Click any class name in the code to open that class.
package pool; import java.time.Duration;import java.util.Deque;import java.util.Objects;import java.util.concurrent.ConcurrentLinkedDeque;import java.util.concurrent.Semaphore;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicBoolean;import java.util.concurrent.atomic.AtomicInteger; /** * Lends up to maxSize objects, each to one borrower at a time, and takes them * back for the next borrower. Objects are created only when none is idle. */public final class ObjectPool<T> implements AutoCloseable { private final ObjectFactory<T> factory; private final int maxSize; private final Semaphore permits; private final Deque<T> idle = new ConcurrentLinkedDeque<>(); private final AtomicInteger open = new AtomicInteger(); private final AtomicBoolean closed = new AtomicBoolean(); public ObjectPool(ObjectFactory<T> factory, int maxSize) { this.factory = Objects.requireNonNull(factory, "factory"); // close() adds one permit, and a Semaphore holds at most Integer.MAX_VALUE. if (maxSize < 1 || maxSize == Integer.MAX_VALUE) { throw new IllegalArgumentException("maxSize must be 1 to Integer.MAX_VALUE - 1, was " + maxSize); } this.maxSize = maxSize; // One permit per object that may be lent at once; fair, so waiters are served in order. this.permits = new Semaphore(maxSize, true); } public Lease<T> borrow(Duration timeout) throws InterruptedException { Objects.requireNonNull(timeout, "timeout"); if (timeout.isNegative()) { throw new IllegalArgumentException("timeout must not be negative, was " + timeout); } requireOpen(); if (!permits.tryAcquire(TimeUnit.NANOSECONDS.convert(timeout), TimeUnit.NANOSECONDS)) { throw new PoolExhaustedException(maxSize, timeout); } boolean lent = false; try { T object = takeIdleOrCreate(); if (closed.get()) { discard(object); // close() ran while we were taking or creating it throw new IllegalStateException("the pool is closed"); } Lease<T> lease = new Lease<>(this, object); lent = true; return lease; } finally { if (!lent) { permits.release(); } } } private T takeIdleOrCreate() { T object; while ((object = idle.pollFirst()) != null) { boolean usable = false; try { usable = isUsable(object); } finally { if (!usable) { discard(object); // even if the check threw an Error } } if (usable) { return object; } } requireOpen(); // close() may have run while we checked idle objects object = Objects.requireNonNull(factory.create(), "factory.create() returned null"); open.incrementAndGet(); return object; } /** Called once per lease, by Lease.close. */ void giveBack(T object) { boolean kept = false; try { if (!closed.get() && resetAndCheck(object)) { idle.offerFirst(object); kept = true; if (closed.get()) { drainIdle(); // close() may have emptied the idle list just before we added to it } } } finally { try { if (!kept) { discard(object); } } finally { permits.release(); } } } private boolean resetAndCheck(T object) { try { factory.reset(object); return factory.isUsable(object); } catch (RuntimeException e) { return false; // an object that cannot be reset is not lent again } } private boolean isUsable(T object) { try { return factory.isUsable(object); } catch (RuntimeException e) { return false; } } private void discard(T object) { open.decrementAndGet(); try { factory.destroy(object); } catch (RuntimeException e) { // The object is already being thrown away; its failure must not reach the borrower. } } private void requireOpen() { if (closed.get()) { throw new IllegalStateException("the pool is closed"); } } /** Destroys the idle objects now and each lent one when it comes back, and refuses waiting borrowers. */ @Override public void close() { if (!closed.compareAndSet(false, true)) { return; } try { drainIdle(); } finally { // One permit wakes one waiter; it is refused and passes the permit on in borrow's finally. permits.release(); } } private void drainIdle() { Error first = null; T object; while ((object = idle.pollFirst()) != null) { try { discard(object); } catch (Error e) { first = first == null ? e : first; // keep destroying the rest, then report it } } if (first != null) { throw first; } } public int openCount() { return open.get(); } public int idleCount() { return idle.size(); } public int maxSize() { return maxSize; }}demo/Main.java runs a pool of 2 connections against a server that allows 4. The lines starting server: and conn- come from the fake server, and the brackets show the pool after each step:
1. Four status checks, one after another server: opened conn-1 conn-1: status 4521873690 4521873690: CNF, coach B3, berth 42 [open 1, idle 1] conn-1: status 8204417733 8204417733: RAC 12 [open 1, idle 1] conn-1: status 6139025588 6139025588: WL 7 [open 1, idle 1] conn-1: status 4521873690 4521873690: CNF, coach B3, berth 42 [open 1, idle 1] connections opened for 4 checks: 1 2. Two callers hold both connections, and a third waits 100 ms server: opened conn-2 two callers hold conn-1 and conn-2 [open 2, idle 0] 8204417733: busy, please try again [open 2, idle 0] both callers gave their connections back [open 2, idle 2] 3. A cancellation fails half way, inside a transaction conn-1: cancel 6139025588 conn-1: refund 6139025588 conn-1: rolled back an open transaction 6139025588: not cancelled (refund declined) [open 2, idle 2] the next borrower gets conn-1, in a transaction: false [open 2, idle 1] 4. The network drops connections server: dropped conn-1 conn-2: status 4521873690 4521873690: CNF, coach B3, berth 42 [open 1, idle 1] server: dropped conn-2 a query on a dropped connection failed: conn-2 is closed [open 0, idle 0] server: opened conn-3 conn-3: status 8204417733 8204417733: RAC 12 [open 1, idle 1] 5. A lease closed twice, then used closed the same lease twice; idle connections: 1 [open 1, idle 1] get() after close: this lease was already returned [open 1, idle 1] 6. Shutting the pool down server: closed conn-3 connections open at the server: 0, opened in all: 3 [open 0, idle 0]
Part 1 is requirement 2: four checks in a row open one connection. In part 2, two callers hold both connections, so the third check waits 100 ms and is told "busy" (requirement 4). Part 3 is requirement 6: the failed cancellation left a transaction open, the pool rolled it back, and the next borrower got conn-1 with no transaction. Part 4 is requirement 7. conn-1 was dropped while idle, so the next check skipped it and used conn-2. Then conn-2 was dropped while lent, so its next query failed and it was destroyed when it came back, and the next check opened conn-3. Part 5 is requirement 8, and part 6 is requirement 9: after shutdown the server has no connections open, and three were opened in all.
What it costs
A request with an idle connection skips the open. Checks one after another share one connection: the demo's four checks opened one, where the first version would have opened four.
The server's load has a ceiling we set. However many requests arrive, the server sees at most the pool's size from us. The extra requests wait in our service, and some are told "busy".
The reset list must keep up with the object. Anything a borrower can change on a connection must be put back: a transaction, a session setting, a temporary table. Each new feature of the object can add to that list, and a forgotten item passes one user's state to the next.
A leak shrinks the pool. A borrower that never closes its lease holds a permit for ever. With a pool of 4, four leaks stop the service. try-with-resources prevents most of them. A pool can also record when each lease was taken and report the ones held too long. That is a follow-up.
Idle objects still cost. An open connection holds memory on the server even when no request uses it. A pool can close connections that have been idle for a while, which is another follow-up. Taking the most recently returned one first leaves the others idle long enough for that.
The size is a guess you have to tune. Too small, and requests wait while the server could do more. Too large, and several copies of the service can together pass the server's limit: 3 copies with pools of 4 can open 12 connections.
When a pool is too much
Most Java objects should not be pooled. Creating a short-lived object on a current Java virtual machine (JVM) is usually a quick bump in a per-thread memory area, and collecting short-lived garbage is cheap. A pooled object lives a long time instead, and every borrow goes through shared state. For a small object, plain new is usually both faster and simpler:
String line(Booking booking) { StringBuilder text = new StringBuilder(); // made, used and dropped in one call text.append(booking.pnr()).append(": ").append(booking.status()); return text.toString();}The same reasoning applies to threads. Java's platform threads are costly, so thread pools exist. Java 21's virtual threads are cheap to create, and the advice for them is the opposite: create one per task and do not pool them.
In production Java, a connection pool usually comes from a library rather than being written by hand. It does the same jobs as ours, with more settings.
Object Pool, Flyweight, Singleton or a cache?
All four keep objects around for reuse, so they are easy to confuse.
| Object Pool | Flyweight | Singleton | Cache | |
|---|---|---|---|---|
| How many objects | Up to the pool's size | One per distinct value | One in the program | One per key, for a while |
| Shared or lent | Lent to one user at a time | Shared by many at once | Shared by everyone | Shared |
| Can it change | Yes, and it is reset on return | Never | It may hold state that changes | An entry can expire or be refreshed |
| Given back | Yes, after each use | Never | Never | Never |
| It saves | Slow creation, and it caps the number | Memory | Having two of something that must be one | Repeated slow work |
| Example | A database connection | The dollars style shared by many cells | An order-number generator | A price lookup kept for 5 minutes |
The Flyweight pattern page's style pool has "pool" in its name, but its styles never change and are never returned, so any number of cells use one at once. A pooled connection changes while it is in use, which is why only one user may hold it. The Singleton pattern page's generator must exist once for correctness, while a pool holds several objects.
A short way to say it: a flyweight is shared because it never changes, and a pooled object is lent because it does.
In an interview
The pattern appears in questions about a database connection pool, a client for a rate-limited outside service, and anything that holds a few expensive or limited resources. A thread pool question uses the same ideas, with tasks handed in rather than threads lent out.
A good order for presenting it:
- Say what is expensive and what is limited. "Opening a connection takes a round trip and a login, and the server allows 4."
- Draw the lifecycle. Borrow, use, return, reset, check, destroy. Say what happens when every object is lent.
- Then write the pool: the semaphore, the idle list, the lease, and the order of the steps that keeps them in agreement.
Common mistakes:
- Not resetting on return. The next borrower inherits an open transaction or a changed setting.
- Putting a broken object back. Every later borrower who gets it fails, and the pool never recovers.
- Losing a permit on a failure path. A failed create, or a reset that throws, keeps a permit for ever, and the pool slowly shrinks.
- Counting with a plain field and a check-then-act. Two threads both see 3 of 4 lent and both create, so the server sees 5.
- Returning the bare object to callers. Nothing stops a double return or use after return, and two callers end up sharing one object.
- Pooling cheap objects. It adds shared state and stale contents, and it saves an allocation that was usually cheap already.
Summary
- Use Object Pool when an object is slow to create or limited in number, and each user needs it alone for a short time.
- Lend each object to one borrower, through a lease that returns it once, and create new ones only when none is idle.
- Reset and check every object when it comes back, and check idle ones again before lending them. Destroy the broken ones.
- Bound the number with a semaphore, take a permit before taking an object, and give it back on every path.
- Bound the wait too, and turn an empty pool into a clear refusal.
- Do not pool cheap objects. Plain
newis usually faster and has no stale state.