3

Problem statement:

Garden variety of distributed locking.

Implement a distributed locking for a service, which has multiple instances running.

The lock is to be taken on 'redis' running on 1 master and 2 slaves.

Implementation:

Service Instance 1

    RLock lock11 = redisson.getLock("lock11");
    RLock lock12 = redisson.getLock("lock12");
    RLock lock13 = redisson.getLock("lock13");

    RedissonRedLock lock = new RedissonRedLock(lock11, lock12, lock13);
    lock.lock();

    //...

    lock.unlock();

Service Instance 2

    RLock lock21 = redisson.getLock("lock21");
    RLock lock22 = redisson.getLock("lock22");
    RLock lock23 = redisson.getLock("lock23");

    RedissonRedLock lock = new RedissonRedLock(lock21, lock22, lock23);
    lock.lock();

    //...

    lock.unlock();

Expected behavior :

If service instance 1 takes the lock, then service instance 2 should NOT be able to take the lock. ( for Distributed locking - this should be the normal behaviour )

Question:

How would Redis know that the object "lock11" is to be created exclusive to the object "lock21" ?

Do we ( as developers ) need to program something for hash collision ?

Note : The two objects will have different hashCodes ( service instance 1 will NOT know the hashcode of the service instance 2's object )

Deep
  • 673
  • 1
  • 10
  • 23
  • 1
    If you have only one master then I would recommend to use single lock without RedissonRedLock object. Just get it by `redisson.getLock` method. – Nikita Koksharov Apr 10 '19 at 07:27
  • You don't need to manage hash codes. Redisson does it for you in cluster environment. – Nikita Koksharov Apr 10 '19 at 07:28
  • Thanks @NikitaKoksharov, your inputs help. But, my question still stands .. when both service instance 1 and 2 execute redisson.getLock("FixedString"), then the server knows that only one of the 2 instances should be granted the lock ( by being able to use "FixedString". From the example above : How would Redis know that out of object "lock11" and object "lock21", only one is to be granted the lock ( how would it be able to compare the two lock names against each other ? – Deep Apr 10 '19 at 07:42
  • 2
    Redis is a single-threaded and blazing-fast server. So if one client set value other one won't do that due to atomicity. Redisson Lock uses this feature to gurantee that only single Java thread will acquire lock by the same name. In your case `lock11` and `lock21` are different locks since they have different names, so could be aquired by two different threads. – Nikita Koksharov Apr 10 '19 at 11:34
  • Got it ! This means two different server instances, need to somehow use a unique name ... to stay mutually exclusive. – Deep Apr 10 '19 at 13:23
  • 2
    In the same Redis cluster you don't need to bother about this. Just use a single name – Nikita Koksharov Apr 11 '19 at 17:14

0 Answers0