Class: MemoryMutex
Package:
@litert/concurrentImport path:@litert/concurrentSource: packages/partials/concurrent/src/Classes/MemoryMutex.ts
A lightweight in-memory mutex. Multiple instances can share the same lock by calling share() — each shared instance gets a unique lock identifier and competes for access without accidentally releasing a lock held by another instance.
Constructor
new MemoryMutex(opts?: IMemoryMutexOptions)See IMemoryMutexOptions.
Properties
| Property | Type | Description |
|---|---|---|
reentrant | boolean (readonly) | Whether the mutex allows the same instance to re-acquire an already held lock |
Methods
lock()
lock(): booleanAttempts to acquire the lock.
- If the mutex is unlocked, acquires it and returns
true. - If the mutex is held by this same instance and
reentrantistrue, returnstrue. - If the mutex is held by another instance (or by this instance when
reentrantisfalse), returnsfalse.
Returns: boolean — true if the lock was acquired.
unlock()
unlock(): booleanReleases the lock if it is held by this instance.
Returns: boolean — true if successfully released.
isLocked()
isLocked(): booleanReturns true if the mutex is currently locked by any instance.
share()
share(): MemoryMutexReturns a new MemoryMutex instance that shares the same underlying lock state. The new instance has its own unique lock identifier, so it can compete for the same lock without conflicting with the original.
run(fn)
run<T extends IFunction>(fn: T): ReturnType<T>Acquires the lock, calls fn, then releases the lock.
Throws: E_LOCK_FAILED if the lock cannot be acquired.
wrap(fn)
wrap<T extends IFunction>(fn: T): TReturns a wrapper function that acquires the lock before each call and releases it after.
Throws: E_LOCK_FAILED on each call if the lock cannot be acquired.
Example
import { MemoryMutex } from '@litert/concurrent';
const mutex = new MemoryMutex();
if (mutex.lock()) {
try {
doExclusiveWork();
} finally {
mutex.unlock();
}
} else {
console.log('Could not acquire lock');
}
// Using run() for automatic lock management
mutex.run(() => {
doExclusiveWork();
});
// Sharing the lock across two instances
const mutexA = new MemoryMutex();
const mutexB = mutexA.share();
mutexA.lock(); // true
mutexB.lock(); // false — same underlying lock, different ID
mutexA.unlock();
mutexB.lock(); // true now