Last active
December 8, 2023 01:58
-
-
Save colinmollenhour/808fec7e38fc37e541b2f91ea2e1c699 to your computer and use it in GitHub Desktop.
Poor man's in-memory exclusive lock mechanism for Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Uses 100ms intervals to check for released lock - super simple | |
* @author Me and ChatGPT | |
*/ | |
class PoboyLock { | |
constructor() { | |
this.lockedKeys = new Set(); | |
} | |
async getLock(key) { | |
return new Promise((resolve, reject) => { | |
const startTime = Date.now(); | |
const timeoutDuration = 30000; // 30 seconds | |
const checkLock = () => { | |
if (!this.lockedKeys.has(key)) { | |
this.lockedKeys.add(key); | |
resolve(key); | |
} else { | |
const elapsedTime = Date.now() - startTime; | |
if (elapsedTime < timeoutDuration) { | |
setTimeout(checkLock, 100); | |
} else { | |
reject(new Error("Failed to obtain lock within the timeout period.")); | |
} | |
} | |
}; | |
checkLock(); | |
}); | |
} | |
releaseLock(key) { | |
if (this.lockedKeys.has(key)) { | |
this.lockedKeys.delete(key); | |
console.log(`Lock released for key: ${key}`); | |
} else { | |
console.warn(`Trying to release a lock that is not held for key: ${key}`); | |
} | |
} | |
} | |
// Example usage: | |
const poboyLock = new PoboyLock(); | |
async function exampleUsage() { | |
try { | |
const key = await poboyLock.getLock("myKey"); | |
// Do something with the lock | |
console.log(`Working with lock for key: ${key}`); | |
// Release the lock when done | |
poboyLock.releaseLock(key); | |
} catch (error) { | |
console.error(error.message); | |
} | |
} | |
exampleUsage(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment