ObjectPool

class ObjectPool<T>(val capacity: Int, factory: () -> T, reset: (T) -> Unit = {})

A bounded pool that reuses instances instead of creating new ones.

borrow returns a pooled instance when one is available and otherwise creates a fresh one with factory. recycle resets an instance with the reset callback and stores it, unless the pool already holds capacity instances, in which case the instance is dropped without reset. The pool never verifies that a recycled instance came from borrow.

This class is not thread-safe.

Type Parameters

T

the pooled instance type.

Throws

Constructors

Link copied to clipboard
constructor(capacity: Int, factory: () -> T, reset: (T) -> Unit = {})

Creates an empty pool. No instance is created until the first borrow on an empty pool.

Properties

Link copied to clipboard

The maximum number of idle instances the pool stores.

Link copied to clipboard

The number of idle instances currently stored, from 0 to capacity.

Functions

Link copied to clipboard
fun borrow(): T

Returns a pooled instance, or a new instance from the factory when the pool is empty.

Link copied to clipboard
fun recycle(instance: T)

Resets instance and stores it for a later borrow.

Link copied to clipboard
inline fun <R> use(block: (T) -> R): R

Borrows an instance, runs block with it, and recycles it, including when block throws.