abelaska/jedis-lock — pull request #3 by tonyghita (2014-10-22 20:16:02+00:00)
Title: Simplify lock expiration mechanism and add ownership safety to release()

cc @abelaska

Reviving this project from 4 years of dormancy :) Some notes:

Simplifying the lock expiration mechanism:

Since Redis 2.6.12, the SET operation supports a set of options which
modify its behavior (see: http://redis.io/commands/set). The options
we are interested in are PX (set specified expire time in ms) and NX
(only set the key if it does not already exist).

The ability to perform both of these atomically is awesome for our use
case. Replacing the former call to SETNX with the new SET with options
not only moves us away from using deprecated functionality but also
allows us to drop the expiration checking code of past.

Adding lock ownership for safety:

To prevent locks from releasing each others hold on keys, we introduce a
unique token. The token is the value of the lockKey. In release(), a
check was added which (atomically, with the Lua script) releases the
lock only if the lock owner releases.

Unfortunately, I don't believe there is any way to achieve this behavior
with Redis without the aid of a Lua script.