dreadlocks

3.0.0 • Public • Published

dreadlocks

Dread-free locks that drive consistency.

Summary

Dreadlocks allows you to create deadlocks on a set of keys. There is no limitation as to what key can be, it could be an Object, an Array, a String, or anything that can be a key in Map.

  • Create and use keys to identify objects:
    • const key1 = {};
  • Create key sets for keys involved in each task:
    • const keySet = [key1, key2, key3]
  • Lock these key sets
    • Dread.lock(keySet).then(task)
  • Release these key sets once you're done.
    • Dread.release(keySet)

Perks

  • Respects FIFO (first-in-first-out) flow:
    • Iterates on queue item 0 to n then back to 0.
    • Reverts index to 0 on each performed lock.
    • Reverts index to 0 on each performed release.
  • Uses Map so you can use anything as a key.
    • Although of course, use of strings are the most encouraged.
  • Uses setInterval for periodic checks and processing of queue.
    • new Dreadlock(interval) accepts custom interval in ms, 4 by default; 1000/4 = 250 checks/s

Use Cases:

  • Database consistency & transactions.
  • Ensuring order in execution of tasks that wish to modify possibly similar objects or entities.

API

Constructor

new Dreadlocks({ defaultLockTimeout = Infinity })

Construct an instance of Dreadlock. You can also set a default timeout to wait for a lock.

Methods

#lock(keyset[], { lockTimeout = this.defaultLockTimeout } = {})

  • keyset array of keys to lock
  • lockTimeout timeout in ms for the lock to be obtained

Return a Promise which will resolve when the lock is obtained, or reject when the timeout is reached.

#release(keyset[])

  • keyset array of keys to release

Properties

#size

Current size of instance Map


Usage:

Install

npm install dreadlocks --save
yarn add dreadlocks
const Dreadlock = require('dreadlocks');

Create instance

const Dread = new Dreadlock();

Lock your keys anywhere in your code:

const keySet1 = ['key1', 'key2', 'key3'];
Dread.lock(keySet1)
  .then(() => {
    console.log('Working with keySet1.');
    // Use your keySet1 keys here
    console.log('Done with keySet1.');
    return Dread.release(keySet1);
  })
  .then(() => {
    console.log('keySet1 released.');
  });
const keySet2 = ['key1', 'key4', 'key5'];
Dread.lock(keySet2)
  .then(() => {
    console.log('Working with keySet2.');
    // Use your keySet2 keys here
    console.log('Done with keySet2.');
    return Dread.release(keySet2);
  })
  .then(() => {
    console.log('keySet2 released.');
  });

See the magic:

Working with keySet1.
Done with keySet1.
keySet1 released.
Working with keySet2.
Done with keySet2.
keySet2 released.

LICENSE

C 0

Package Sidebar

Install

npm i dreadlocks

Weekly Downloads

1

Version

3.0.0

License

CC0-1.0

Unpacked Size

16.8 kB

Total Files

6

Last publish

Collaborators

  • xemasiv