Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Added a delay before retrying in case of concurrency issue.

  • Loading branch information...
commit 0473cc44b4e4ff9ece94c47a9e604e05d5ac2924 1 parent df71328
@rakeshpai rakeshpai authored
Showing with 24 additions and 15 deletions.
  1. +24 −15 index.js
View
39 index.js
@@ -11,25 +11,34 @@ function acquireLock(client, lockName, timeout, onLockAquired) {
if(err) return process.nextTick(retry);
if(result === 0) {
- client.get(lockName, function(err, timeStamp) {
- if(err || !timeStamp) return process.nextTick(retry);
+ // Lock couldn't be aquired. Check if the existing lock has timed out.
- timeStamp = parseFloat(timeStamp);
+ client.get(lockName, function(err, existingLockTimestamp) {
+ if(err) return process.nextTick(retry);
+ if(!existingLockTimestamp) {
+ // Wait, the lock doesn't exist!
+ // Someone must have called .del after we called .setnx but before .get.
+ // https://github.com/errorception/redis-lock/pull/4
+ return setTimeout(retry, 50);
+ }
- if(timeStamp > Date.now()) {
- setTimeout(retry, 50);
- } else {
- lockTimeoutValue = (Date.now() + timeout + 1)
- client.getset(lockName, lockTimeoutValue, function(err, result) {
- if(err) return process.nextTick(retry);
+ existingLockTimestamp = parseFloat(existingLockTimestamp);
- if(result == timeStamp) {
- onLockAquired(lockTimeoutValue);
- } else {
- retry();
- }
- });
+ if(existingLockTimestamp > Date.now()) {
+ // Lock looks valid so far. Wait some more time.
+ return setTimeout(retry, 50);
}
+
+ lockTimeoutValue = (Date.now() + timeout + 1)
+ client.getset(lockName, lockTimeoutValue, function(err, result) {
+ if(err) return process.nextTick(retry);
+
+ if(result == existingLockTimestamp) {
+ onLockAquired(lockTimeoutValue);
+ } else {
+ retry();
+ }
+ });
});
} else {
onLockAquired(lockTimeoutValue);
Please sign in to comment.
Something went wrong with that request. Please try again.