Skip to content

Class: FiberPool

Package: @litert/concurrentImport path: @litert/concurrentSource: packages/partials/concurrent/src/Classes/FiberPool.tsExtends: EventEmitter<IFiberPoolEvents>

A pool of reusable FiberController workers. Fibers are created on demand up to maxFibers and kept idle (up to maxIdleFibers) for reuse. Idle fibers above minIdleFibers are released after idleTimeout ms.


Constructor

ts
new FiberPool(options: IFiberPoolOptions)

See IFiberPoolOptions.


Constants

ConstantValueDescription
DEFAULT_MIN_IDLE_FIBERS1Default minIdleFibers
DEFAULT_MAX_IDLE_FIBERS1Default maxIdleFibers
DEFAULT_IDLE_TIMEOUT10000Default idle timeout (ms)
DEFAULT_WAIT_TIMEOUT10000Default wait timeout for run() (ms)
DEFAULT_MAX_WAITS10Default max concurrent callers waiting for a free fiber

Properties

PropertyTypeDescription
idleFibersnumber (readonly)Current number of idle fibers
busyFibersnumber (readonly)Current number of fibers executing a task

Methods

run(opts)

ts
run<TData, TResult>(opts: IRunOptions<TData, TResult>): Promise<TResult>

Picks an idle fiber (or creates a new one if under maxFibers), executes opts.function(opts.data) inside it, and returns the result.

If all fibers are busy, waits up to waitTimeout ms for one to become available. If maxWaits callers are already waiting, the call is rejected immediately.

ParameterTypeDescription
optsIRunOptions<TData, TResult>Task options — see IRunOptions

Returns: Promise<TResult> — the value returned by opts.function.

Throws:

  • TimeoutError — if no fiber became available within waitTimeout ms.
  • Any error thrown by opts.function.

close()

ts
close(): void

Closes all idle fibers and prevents new tasks from being submitted.


isClosed()

ts
isClosed(): boolean

Returns true if the pool has been closed.


Events

See IFiberPoolEvents.

EventDescription
'error'Emitted on internal unhandled fiber errors

Example

ts
import { FiberPool } from '@litert/concurrent';

const pool = new FiberPool({
    maxFibers: 4,
    maxIdleFibers: 2,
    minIdleFibers: 1,
});

const result = await pool.run({
    data: { userId: 42 },
    function: async ({ userId }) => {
        return fetchUser(userId);
    },
});

console.log(result);

pool.close();