async-lock vs async-mutex
JavaScript Concurrency Control Libraries
async-lockasync-mutexSimilar Packages:

JavaScript Concurrency Control Libraries

Concurrency control libraries in JavaScript are essential for managing asynchronous operations and ensuring that shared resources are accessed in a controlled manner. These libraries help prevent race conditions and ensure data integrity when multiple asynchronous tasks are executed simultaneously. They provide mechanisms to lock resources, allowing only one operation to access a resource at a time, which is crucial in scenarios where data consistency is paramount, such as in database operations or shared state management in applications.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
async-lock042518.3 kB52 years agoMIT
async-mutex01,40163 kB152 years agoMIT

Feature Comparison: async-lock vs async-mutex

Locking Mechanism

  • async-lock:

    async-lock provides a straightforward locking mechanism that allows you to create a lock for a specific resource. Once a lock is acquired, no other asynchronous operations can access that resource until the lock is released, ensuring that critical sections of code are executed without interruption.

  • async-mutex:

    async-mutex offers a more flexible locking mechanism that supports both exclusive and shared locks. This allows multiple asynchronous operations to read a resource simultaneously while ensuring that write operations are exclusive, providing a more nuanced approach to concurrency control.

Ease of Use

  • async-lock:

    async-lock is designed to be simple and easy to use, with a minimal API that allows developers to quickly implement locking in their asynchronous code. This makes it an excellent choice for developers who need a quick solution without the overhead of complex configurations.

  • async-mutex:

    async-mutex, while slightly more complex due to its support for multiple lock types, still maintains a user-friendly API. It may require a bit more understanding of its features, but it provides powerful capabilities for managing concurrency.

Performance

  • async-lock:

    async-lock is lightweight and optimized for performance, making it suitable for scenarios where locking is needed but overhead must be minimized. It is particularly effective in environments with high concurrency demands where performance is critical.

  • async-mutex:

    async-mutex may introduce slightly more overhead due to its advanced locking features, but it is designed to handle complex concurrency scenarios efficiently. Its performance is generally acceptable for most applications, especially those that require shared access to resources.

Use Cases

  • async-lock:

    async-lock is ideal for simple use cases where you need to ensure that a specific asynchronous operation completes before another can start, such as in caching mechanisms or when accessing shared resources like files or databases.

  • async-mutex:

    async-mutex is better suited for more complex scenarios where you need to manage multiple types of access to a shared resource, such as in applications that require both read and write operations to a shared state.

Community and Support

  • async-lock:

    async-lock has a smaller community compared to async-mutex, but it is actively maintained and has sufficient documentation to help developers implement it effectively in their projects.

  • async-mutex:

    async-mutex benefits from a larger community and more extensive documentation, providing better support for developers who may encounter issues or need guidance on best practices.

How to Choose: async-lock vs async-mutex

  • async-lock:

    Choose async-lock if you need a simple and lightweight solution for locking resources in asynchronous operations. It is particularly useful for scenarios where you want to ensure that a specific piece of code is executed exclusively, preventing other asynchronous tasks from interfering until the lock is released.

  • async-mutex:

    Choose async-mutex if you require a more comprehensive locking mechanism that supports both exclusive and shared locks. It is suitable for more complex scenarios where you might need to allow multiple readers but only one writer, making it ideal for situations involving shared resources with varying access patterns.

README for async-lock

async-lock

Lock on asynchronous code

Build Status

  • ES6 promise supported
  • Multiple keys lock supported
  • Timeout supported
  • Occupation time limit supported
  • Execution time limit supported
  • Pending task limit supported
  • Domain reentrant supported
  • 100% code coverage

Disclaimer

I did not create this package, and I will not add any features to it myself. I was granted the ownership because it was no longer being maintained, and I volunteered to fix a bug.

If you have a new feature you would like to have incorporated, please send me a PR and I will be happy to work with you and get it merged. For any bugs, PRs are most welcome but when possible I will try to get them resolved as soon as possible.

Why do you need locking on single threaded nodejs?

Nodejs is single threaded, and the code execution never gets interrupted inside an event loop, so locking is unnecessary? This is true ONLY IF your critical section can be executed inside a single event loop. However, if you have any async code inside your critical section (it can be simply triggered by any I/O operation, or timer), your critical logic will across multiple event loops, therefore it's not concurrency safe!

Consider the following code

redis.get('key', function(err, value) {
	redis.set('key', value * 2);
});

The above code simply multiply a redis key by 2. However, if two users run concurrently, the execution order may like this

user1: redis.get('key') -> 1
user2: redis.get('key') -> 1
user1: redis.set('key', 1 x 2) -> 2
user2: redis.set('key', 1 x 2) -> 2

Obviously it's not what you expected

With asyncLock, you can easily write your async critical section

lock.acquire('key', function(cb) {
	// Concurrency safe
	redis.get('key', function(err, value) {
		redis.set('key', value * 2, cb);
	});
}, function(err, ret) {
});

Get Started

var AsyncLock = require('async-lock');
var lock = new AsyncLock();

/**
 * @param {String|Array} key 	resource key or keys to lock
 * @param {function} fn 	execute function
 * @param {function} cb 	(optional) callback function, otherwise will return a promise
 * @param {Object} opts 	(optional) options
 */
lock.acquire(key, function(done) {
	// async work
	done(err, ret);
}, function(err, ret) {
	// lock released
}, opts);

// Promise mode
lock.acquire(key, function() {
	// return value or promise
}, opts).then(function() {
	// lock released
});

Error Handling

// Callback mode
lock.acquire(key, function(done) {
	done(new Error('error'));
}, function(err, ret) {
	console.log(err.message) // output: error
});

// Promise mode
lock.acquire(key, function() {
	throw new Error('error');
}).catch(function(err) {
	console.log(err.message) // output: error
});

Acquire multiple keys

lock.acquire([key1, key2], fn, cb);

Domain reentrant lock

Lock is reentrant in the same domain

var domain = require('domain');
var lock = new AsyncLock({domainReentrant : true});

var d = domain.create();
d.run(function() {
	lock.acquire('key', function() {
		//Enter lock
		return lock.acquire('key', function() {
			//Enter same lock twice
		});
	});
});

Options

// Specify timeout - max amount of time an item can remain in the queue before acquiring the lock
var lock = new AsyncLock({timeout: 5000});
lock.acquire(key, fn, function(err, ret) {
	// timed out error will be returned here if lock not acquired in given time
});

// Specify max occupation time - max amount of time allowed between entering the queue and completing execution
var lock = new AsyncLock({maxOccupationTime: 3000});
lock.acquire(key, fn, function(err, ret) {
	// occupation time exceeded error will be returned here if job not completed in given time
});

// Specify max execution time - max amount of time allowed between acquiring the lock and completing execution
var lock = new AsyncLock({maxExecutionTime: 3000});
lock.acquire(key, fn, function(err, ret) {
	// execution time exceeded error will be returned here if job not completed in given time
});

// Set max pending tasks - max number of tasks allowed in the queue at a time
var lock = new AsyncLock({maxPending: 1000});
lock.acquire(key, fn, function(err, ret) {
	// Handle too much pending error
})

// Whether there is any running or pending async function
lock.isBusy();

// Use your own promise library instead of the global Promise variable
var lock = new AsyncLock({Promise: require('bluebird')}); // Bluebird
var lock = new AsyncLock({Promise: require('q')}); // Q

// Add a task to the front of the queue waiting for a given lock
lock.acquire(key, fn1, cb); // runs immediately
lock.acquire(key, fn2, cb); // added to queue
lock.acquire(key, priorityFn, cb, {skipQueue: true}); // jumps queue and runs before fn2

Changelog

See Changelog

Issues

See issue tracker.

License

MIT, see LICENSE