Each participant creates ephemeral child under /barrier
2
When child count == N, all may proceed
3
Use watches to be notified of count change
3. Implementing Distributed Locks
Example: Redis SET NX lock with token
String token = UUID.randomUUID().toString();String resp = jedis.set("lock:order:42", token, SetParams.setParams().nx().px(10_000));if ("OK".equals(resp)) { try { criticalSection(); } finally { // Release only if we still own it String lua = "if redis.call('get', KEYS[1]) == ARGV[1] then " + "return redis.call('del', KEYS[1]) else return 0 end"; jedis.eval(lua, List.of("lock:order:42"), List.of(token)); }}
Implementation
Notes
Redis SET NX PX
Single-instance; needs Redlock or fencing for safety
Redlock
Multiple Redis instances; debated correctness
ZooKeeper recipe
Ephemeral sequential znode
etcd lease + lock
Strong, with revision as fencing token
Warning: Distributed locks are not safe without fencing tokens — GC pauses or network delays can cause two clients to think they hold the lock simultaneously.