Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

async-lock

rogierschouten7.2mMIT1.4.1TypeScript support: definitely-typed

Lock on asynchronous code

lock, async, concurrency, critical, section, mutex

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

changelog

1.4.0

  • add execution timeout (thank you @mottymilshtein)

1.3.2

  • Handle errors from user-supplied callback better (Thank you @simeonborko)
  • Ensure the array parameter does not get mutated for batch acquire (Thank you @taschmidt)

1.3.1

  • Show queue name in errors (thank you @luke-stead-sonocent)

1.3.0

  • Add maxOccupationTime option (Thank you @abozaralizadeh and @ThePiz)

1.2.8

  • Fix #37 process not set when acquiring lock (Thank you @Philipp91)

1.2.7

DO NOT USE, erroneous publish

1.2.6

  • Fix maxPending = Infinity no longer allowed (thank you @coderaiser)

1.2.5

  • Allow maxPending = 0 (thank you @bmrpatel)
  • Upgrade dependencies

1.2.4

  • Be robust to lock names that are also Object keys - simpler solution, extra tests.

1.2.3

  • Be robust to lock names that are also Object keys.
  • Upgrade dependencies

1.2.2

  • Fix grunt-env accidentally having become a dependency (#25)

1.2.1

  • Remove empty postinstall script (#24)
  • Fixed some vulnerable dev dependencies

1.2.0

  • ES5 compatibility (#21)

1.1.4

  • Fix for #17, update dependencies

1.1.3

  • Fix for #14

1.1.1

  • Fix result Promise not resolving when locking empty key array

1.1.0 / 2017-10-17

  • Add option to add waiters to the front of the queue

1.1.0 / 2017-10-17

  • Add option to add waiters to the front of the queue

1.0.0 / 2017-06-29

0.3.10 / 2017-06-27

  • Remove dependencies on Q-specific nodify(), try(), and defer() methods so that you can inject e.g. standard ES6 promises using new AsyncLock({ Promise: Promise })

0.3.9 / 2016-11-30

  • Referred to MIT license in package.json
  • Update NPM module dependencies, remove no-longer-maintained blanket code coverage
  • Change author to rogierschouten
  • Fix invalid JSDoc comments (thanks @JonathanPicques)
  • Bugfix: TypeError when locking multiple keys at once

0.3.7-0.3.8

Unknown, previous author did not commit this to Github.

0.3.6 / 2015-09-07

  • Performance improvement

0.3.5 / 2015-06-15

  • Performance improvement

0.3.4 / 2015-06-09

  • Bug fix

0.3.3 / 2015-05-19

  • Bug fix

0.3.2 / 2015-05-08

  • Set default timeout to never

0.3.1 / 2015-04-15

  • Use your own promise

0.3.0 / 2015-03-06

  • Domain reentrant

0.2.0 / 2015-02-21

  • Support promise mode
  • Pending task limit

0.1.0 / 2015-01-13

  • Initial version