fast-mutex icon indicating copy to clipboard operation
fast-mutex copied to clipboard

New instance every time or re-use instance?

Open moubry opened this issue 5 years ago • 1 comments

Are you supposed to create a new instance of FastMutex every time you want to acquire a lock, or are you supposed to re-use the same instance every time you want a lock?

This?

import FastMutex from './fast_mutex.js'

window.localStorage.clear()

const mutex = new FastMutex()

const runTest = async () => {
  await mutex.lock('simple_mutex_test')
  console.log('🔓 Unlocked! Insert code here.')
  return mutex.release('simple_mutex_test')
}

runTest()
runTest() // contention

Or this?

import FastMutex from './fast_mutex.js'

window.localStorage.clear()

const runTest = async () => {
  const mutex = new FastMutex()
  await mutex.lock('simple_mutex_test')
  console.log('🔓 Unlocked! Insert code here.')
  return mutex.release('simple_mutex_test')
}

runTest()
runTest() // contention

I ask because the first example gives me an error saying "Lock could not be acquired within 5000ms" immediately when I run the script (it doesn't wait 5 seconds) — so I'm assuming I need a new instance of FastMutex every time I want to acquire a lock.

However, creating a new instance of FastMutex generates a client ID, which makes it seem like you're supposed to re-use that client every time you want to access data from Local Storage, but it does not seem to work for me. However, I'm not sure if I've traded one issue for a more insidious issue — I'm worried that maybe the 2nd example appears to be working but it's actually not?

moubry avatar May 01 '19 15:05 moubry

After reading through the tests, it looks like it is safe/supported to create a new client every time I wish to acquire a lock.

However, whether it's recommended/optimal I'm still unsure about.

moubry avatar May 01 '19 16:05 moubry