X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Futils%2FAsyncLock.ts;h=7f44bd257251f32cde860ce6a40d6eb82cf1a51c;hb=7436ee0df05bb41f3ce8a553adf5d9ed8da78903;hp=1b61532594b0af1d3148ccddcc6b0779405302b5;hpb=1227a6f190a8020afd953a26bdede86e5f04eb0c;p=e-mobility-charging-stations-simulator.git diff --git a/src/utils/AsyncLock.ts b/src/utils/AsyncLock.ts index 1b615325..7f44bd25 100644 --- a/src/utils/AsyncLock.ts +++ b/src/utils/AsyncLock.ts @@ -1,11 +1,13 @@ +// Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved. + export enum AsyncLockType { configuration = 'configuration', performance = 'performance', } export class AsyncLock { - private static readonly instances = new Map(); - private acquired = false; + private static readonly asyncLocks = new Map(); + private acquired: boolean; private readonly resolveQueue: ((value: void | PromiseLike) => void)[]; private constructor(private readonly type: AsyncLockType) { @@ -13,32 +15,34 @@ export class AsyncLock { this.resolveQueue = []; } - public static getInstance(type: AsyncLockType): AsyncLock { - if (!AsyncLock.instances.has(type)) { - AsyncLock.instances.set(type, new AsyncLock(type)); - } - return AsyncLock.instances.get(type); - } - - public async acquire(): Promise { - if (!this.acquired) { - this.acquired = true; + public static async acquire(type: AsyncLockType): Promise { + const asyncLock = AsyncLock.getAsyncLock(type); + if (!asyncLock.acquired) { + asyncLock.acquired = true; } else { return new Promise((resolve) => { - this.resolveQueue.push(resolve); + asyncLock.resolveQueue.push(resolve); }); } } - public async release(): Promise { - if (this.resolveQueue.length === 0 && this.acquired) { - this.acquired = false; + public static async release(type: AsyncLockType): Promise { + const asyncLock = AsyncLock.getAsyncLock(type); + if (asyncLock.resolveQueue.length === 0 && asyncLock.acquired) { + asyncLock.acquired = false; return; } - const queuedResolve = this.resolveQueue.shift(); + const queuedResolve = asyncLock.resolveQueue.shift(); return new Promise((resolve) => { queuedResolve(); resolve(); }); } + + private static getAsyncLock(type: AsyncLockType): AsyncLock { + if (!AsyncLock.asyncLocks.has(type)) { + AsyncLock.asyncLocks.set(type, new AsyncLock(type)); + } + return AsyncLock.asyncLocks.get(type); + } }