Hazelcast Distributed Lock with iMap

7.3k views Asked by At

We are currently using Hazelcast 3.1.5. I have a simple distributed locking mechanism that is supposed to provide thread safety across multiple JVM nodes. Code is pretty simple.

 private static HazelcastInstance hInst = getHazelcastInstance();

 private IMap<String, Integer> mapOfLocks = null;
  ...
  ...

   mapOfLocks = hInst.getMap("mapOfLocks");
        if (mapOfLocks.get(name) == null) {
            mapOfLocks.put(name,1);
            mapOfLocks.lock(name);
        }
        else {
            mapOfLocks.put(name,mapOfLocks.get(name)+1);
        }
         ...
         <STUFF HAPPENS HERE>
         mapOfLocks.unlock(name);
         ..
    }

Earlier, I used to call HazelcastInstance.getLock() directly and things seemed to work, though we never saw anything out of place when multiple JVMs were involved. Recently, I was asked to investigate a database deadlock in block, and after weeks of investigation and log analysis, I was able to determine this was caused by multiple threads being able to acquire the lock against the same key. Before the first thread can commit the code, second thread manages to get another lock, at which point the second thread is blocked by the Database lock from the first thread.

Is there any outstanding bug against Hazelcast implementation of distributed locks, should I be doing anything differently with my configuration? And, Oh my configuration has multicast disabled and tcp-ip enabled

1

There are 1 answers

0
ali On

Here is how you can use IMap as a lock container. You don't need to have entry for the name present in the map in order to lock it.

HazelcastInstance instance = Hazelcast.newHazelcastInstance();
IMap<Object, Object> lockMap = instance.getMap("lockMap");
lockMap.lock(name);
try {
    //do some work
} finally {
    lockMap.unlock(name);
}