pool
import "std/concurrency" (included in import "std") · namespace std.concurrency
Pool<T>: a thread-safe pool of costly, reusable things such as database connections, sockets, parsers and large buffers. Threads check items out and give them back. The pool caps how many exist and makes callers wait when all are in use. It health-checks items that sat idle before handing them out, closes items idle too long, and can give a thread back the item it used last.
grav
import "std"
class Conn {
public id: int
public alive: bool = true
constructor(id: int) { self.id = id }
}
fn main() {
let made = new AtomicInt(0)
let pool = new Pool<Conn>(fn() -> Conn { return new Conn(made.increment() as int) }, 4)
.onClose(fn(c: Conn) { print("closing ${c.id}") })
.healthCheck(fn(c: Conn) -> bool { return c.alive }, 0)
let a = pool.acquire()
let b = pool.acquire()
pool.release(a)
print("reused: ${pool.acquire().id == a.id}")
b.alive = false
pool.release(b)
print("after a failed check: ${pool.acquire().id}")
let id = pool.use::<int>(fn(c: Conn) -> int { return c.id })
print("use gave back ${id}; ${pool.stats()}")
let caught = false
let small = new Pool<Conn>(fn() -> Conn { return new Conn(0) }, 1)
let held = small.acquire()
try { small.acquire(20) } catch (e: TimeoutError) { caught = true }
print("timed out waiting: ${caught}")
small.release(held)
}reused: true
closing 2
after a failed check: 3
use gave back 4; size=3 idle=1 inUse=2 waiting=0 created=4 closed=1 failedChecks=1 timeouts=0
timed out waiting: true- Checking out:
acquire()hands out an idle item, or makes one while under the cap, or waits.acquire(timeoutMs)waits at most that long and then throwsTimeoutError.tryAcquire()never waits and returnsnullinstead. - Giving back:
release(item)returns an item for reuse.discard(item)closes a broken one, and the pool makes a new one when needed.use::<R>(body)andwith(body)give the item back even when the body throws. - Order: idle items are reused last-in first-out, so the warmest ones stay busy and the rest age out under
idleTimeout(ms).maxIdle(n)caps how many sit idle. - Health checks:
healthCheck(check, afterIdleMs)runscheckonly on an item idle longer thanafterIdleMs(30 s by default; 0 checks every time). A failing item is closed and the next one tried. A database client can ping before reusing a connection the server may have closed. - Affinity: with
threadAffinity()a thread gets the item it used last when that item is idle (warm caches, per-connection session state). - Making and closing run outside the lock, so a slow connect blocks no one else.
close()closes the idle items and every item given back afterwards, and wakes waiting threads with aStateError. - State:
size(),idle(),inUse()andstats()(adds created, closed, failed checks, timeouts and threads waiting).
API
class PoolEntry<T>
Constructors
new PoolEntry(item: T, since: long, owner: long)
Fields
item: Tsince: long— When it came back (monotonic ms) and the thread that last used it.owner: long
class PoolStats
What a pool has done so far.
Fields
size: intidle: intinUse: intwaiting: intcreated: longclosed: longfailedChecks: longtimeouts: long
Methods
fn toString() -> string
class Pool<T>
A thread-safe pool of up to maxSize items made by factory.
Constructors
new Pool(factory: fn() -> T, maxSize: int = 8)
Methods
fn onClose(closer: fn(T)) -> Pool<T>— Called on every item the pool throws away (closed, failed its check, evicted).fn healthCheck(check: fn(T) -> bool, afterIdleMs: long = 30000) -> Pool<T>— Checks an item that has been idle longer thanafterIdleMsbefore handing it out; one that fails is closed and another taken (0: check every time).fn idleTimeout(ms: long) -> Pool<T>— Closes items idle longer than this (checked as items come and go).fn maxIdle(n: int) -> Pool<T>— Keeps at most this many idle items; the oldest extra ones are closed.fn threadAffinity(on: bool = true) -> Pool<T>— Hands a thread the item it used last when that one is idle (warm caches, the same session state).fn acquire(timeoutMs: long = -1) -> T— An item, waiting up totimeoutMs(-1: as long as it takes) when all are out; TimeoutError when none came free, StateError once the pool is closed.fn tryAcquire() -> T?— An idle item (or a new one under the cap) without waiting; null when all are out.fn release(item: T)— Gives an item back for reuse.fn discard(item: T)— Takes back an item that is broken (it is closed, and a new one made when needed).fn use<R>(body: fn(T) -> R) -> R— Runsbodywith an item and gives it back afterwards, even when body throws.fn with(body: fn(T))— use, for a body without a result.fn close()— Closes the idle items and every item given back from now on; waiting acquires fail with StateError.fn evictIdle()— Closes idle items past the idle timeout now (the pool otherwise does it as items come and go).fn size() -> int— Items alive (idle and in use), idle, and in use.fn idle() -> intfn inUse() -> intfn maxSize() -> intfn isClosed() -> boolfn stats() -> PoolStats