1 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
3 export enum AsyncLockType
{
4 configuration
= 'configuration',
5 performance
= 'performance',
8 export class AsyncLock
{
9 private static readonly asyncLocks
= new Map
<AsyncLockType
, AsyncLock
>();
10 private acquired
: boolean;
11 private readonly resolveQueue
: ((value
: void | PromiseLike
<void>) => void)[];
13 private constructor() {
14 this.acquired
= false;
15 this.resolveQueue
= [];
18 public static async acquire(type: AsyncLockType
): Promise
<void> {
19 const asyncLock
= AsyncLock
.getAsyncLock(type);
20 if (!asyncLock
.acquired
) {
21 asyncLock
.acquired
= true;
23 return new Promise((resolve
) => {
24 asyncLock
.resolveQueue
.push(resolve
);
29 public static async release(type: AsyncLockType
): Promise
<void> {
30 const asyncLock
= AsyncLock
.getAsyncLock(type);
31 if (asyncLock
.resolveQueue
.length
=== 0 && asyncLock
.acquired
) {
32 asyncLock
.acquired
= false;
35 const queuedResolve
= asyncLock
.resolveQueue
.shift();
36 return new Promise((resolve
) => {
42 private static getAsyncLock(type: AsyncLockType
): AsyncLock
{
43 if (!AsyncLock
.asyncLocks
.has(type)) {
44 AsyncLock
.asyncLocks
.set(type, new AsyncLock());
46 return AsyncLock
.asyncLocks
.get(type);