Mutual Exclusion in Javascript

According to Wikipedia Mutual Exclusion means:

Mutual exclusion is a property of concurrency control, which is instituted for the purpose of preventing race conditions. It is the requirement that one thread of execution never enters its critical section at the same time that another concurrent thread of execution enters its own critical section.

Well in short it means execute only a part of the code by one thread at the same time.

Back in my Java days™️, Java had a nice simple keyword to make a method synchronized, which means mutually exclusive. Javascript doesn’t have something similar, that’s the reason I came up with this Javascript mutex implementation. It’s probably not perfect, but hey, it does the job!

This example shows how to create a function that returns a promise in which the work executes synchronized:

See Github for full source code


const data = {
    counter: 0
}

/**
 * Some heavy calculations in a promise.
 *
 * @param {number} executionSequence The index number of execution
 * @param {{counter:number}} data Wrapper object with counter
 * @return {Promise<number>} Promise that resolves on success or rejects otherwise
 */
function execute(executionSequence, data) {
    const promise = new Promise(resolve => {
        synchronized(release => {

            // Release the lock when the promise is done.
            promise.finally(release);

            // Wait a random time between 0 and 2 seconds.
            setTimeout(() => {

                data.counter++;
                console.log('Execute promise: ' + executionSequence);
                console.log('Counter: ' + data.counter);
                resolve(data.counter);

            }, Math.random() * 2 * 1000);
        });
    });
    return promise;
}

for (let i = 1; i <= 10; i++) { console.log(`==== Create promise: ${i}`); execute(i, data).then(result => {
        console.log(`Promise success: ${i}, result: ${result}`);
    })
}

 

The title image is shamefully stolen from this article:
Mollie: How to use Mutex locks responsibly

One thought on “Mutual Exclusion in Javascript”

Leave a Reply

Your email address will not be published.