X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Futils%2FAsyncLock.ts;h=fe984cebdef97d8043d0f29f6fb9ba99ec502f3c;hb=365cc3b83e3ae98a510608e25b341f9e6d6cfbe1;hp=229086fef1e8d2b45b9ae8f39ca77b867af0e2d5;hpb=42486f2357b011f9244c6b29f4e05185138ce8d1;p=e-mobility-charging-stations-simulator.git diff --git a/src/utils/AsyncLock.ts b/src/utils/AsyncLock.ts index 229086fe..fe984ceb 100644 --- a/src/utils/AsyncLock.ts +++ b/src/utils/AsyncLock.ts @@ -1,39 +1,53 @@ // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved. +import Queue from 'mnemonist/queue.js'; + +import { Constants } from './Constants'; + export enum AsyncLockType { configuration = 'configuration', performance = 'performance', } +type ResolveType = (value: void | PromiseLike) => void; + export class AsyncLock { private static readonly asyncLocks = new Map(); private acquired: boolean; - private readonly resolveQueue: ((value: void | PromiseLike) => void)[]; + private readonly resolveQueue: Queue; private constructor() { this.acquired = false; - this.resolveQueue = []; + this.resolveQueue = new Queue(); } - public static async acquire(type: AsyncLockType): Promise { + public static async runExclusive(type: AsyncLockType, fn: () => T | Promise): Promise { + return AsyncLock.acquire(type) + .then(fn) + .finally(() => { + AsyncLock.release(type).catch(Constants.EMPTY_FUNCTION); + }); + } + + private static async acquire(type: AsyncLockType): Promise { const asyncLock = AsyncLock.getAsyncLock(type); if (!asyncLock.acquired) { asyncLock.acquired = true; - } else { - return new Promise((resolve) => { - asyncLock.resolveQueue.push(resolve); - }); + return; } + return new Promise((resolve) => { + asyncLock.resolveQueue.enqueue(resolve); + }); } - public static async release(type: AsyncLockType): Promise { + private static async release(type: AsyncLockType): Promise { const asyncLock = AsyncLock.getAsyncLock(type); - if (asyncLock.resolveQueue.length === 0 && asyncLock.acquired) { + if (asyncLock.resolveQueue.size === 0 && asyncLock.acquired) { asyncLock.acquired = false; return; } - const queuedResolve = asyncLock.resolveQueue.shift(); - return new Promise((resolve) => { + const queuedResolve = asyncLock.resolveQueue.dequeue()!; + return new Promise((resolve) => { queuedResolve(); resolve(); }); @@ -43,6 +57,6 @@ export class AsyncLock { if (!AsyncLock.asyncLocks.has(type)) { AsyncLock.asyncLocks.set(type, new AsyncLock()); } - return AsyncLock.asyncLocks.get(type); + return AsyncLock.asyncLocks.get(type)!; } }