async-lock vs async-mutex
非同期ロックライブラリ
async-lockasync-mutex類似パッケージ:

非同期ロックライブラリ

非同期ロックライブラリは、JavaScriptの非同期処理において、リソースへの同時アクセスを制御するためのツールです。これにより、データの整合性を保ちながら、複数の非同期操作を安全に実行することができます。特に、競合状態やデータの不整合を防ぐために使用されます。

npmのダウンロードトレンド

3 年

GitHub Starsランキング

統計詳細

パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
async-lock042518.3 kB52年前MIT
async-mutex01,40163 kB152年前MIT

機能比較: async-lock vs async-mutex

ロックの種類

  • async-lock:

    async-lockは、基本的な排他ロックを提供します。これは、特定のリソースに対して同時にアクセスできるのは1つのプロセスのみであることを保証します。シンプルで直感的なAPIを持ち、簡単に実装できます。

  • async-mutex:

    async-mutexは、排他ロックに加えて、再入可能なロックをサポートしています。これにより、同じプロセスがロックを再取得することができ、複雑な非同期処理においても柔軟に対応できます。

使用シナリオ

  • async-lock:

    async-lockは、短期間のロックが必要なシナリオに最適です。例えば、データベースへの一時的な書き込みや、キャッシュの更新など、迅速な処理が求められる場合に適しています。

  • async-mutex:

    async-mutexは、長時間のロックや複雑な非同期処理が必要なシナリオに適しています。例えば、複数の非同期操作が連携して動作する場合や、状態を維持する必要がある場合に有効です。

APIのシンプルさ

  • async-lock:

    async-lockは、シンプルで直感的なAPIを提供しており、すぐに使用を開始できます。特に、非同期処理に不慣れな開発者にとって、使いやすさが大きな利点です。

  • async-mutex:

    async-mutexは、より多機能なAPIを提供しますが、その分学習コストが高くなる可能性があります。高度な機能を必要とする場合には適していますが、シンプルな用途にはオーバーヘッドが大きくなるかもしれません。

パフォーマンス

  • async-lock:

    async-lockは、軽量で高速なロック機構を提供しており、短期間のロックにおいて優れたパフォーマンスを発揮します。特に、頻繁にロックと解除を行うシナリオにおいて効果的です。

  • async-mutex:

    async-mutexは、より複雑なロック機構を提供するため、オーバーヘッドが大きくなることがあります。しかし、適切に使用すれば、複数の非同期操作を安全に管理することができ、全体的なパフォーマンスを向上させることができます。

エラーハンドリング

  • async-lock:

    async-lockは、ロックの取得や解除に失敗した場合のエラーハンドリングがシンプルです。基本的なエラー処理を行うことで、開発者は迅速に問題を特定できます。

  • async-mutex:

    async-mutexは、複雑なロック機構を持つため、エラーハンドリングがやや複雑になることがあります。特に、再入可能なロックを使用する場合、エラーの原因を特定するのが難しくなることがあります。

選び方: async-lock vs async-mutex

  • async-lock:

    async-lockは、シンプルなロック機構を提供し、特に短期間のロックが必要な場合に適しています。複雑なロジックを必要とせず、簡単に使用できるため、軽量なアプリケーションに最適です。

  • async-mutex:

    async-mutexは、より高度なロック機能を提供し、複雑な非同期処理や長時間のロックが必要な場合に適しています。特に、複数のロックを管理する必要がある場合や、再入可能なロックが必要な場合に選択すべきです。

async-lock のREADME

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