简体   繁体   English

使用iMap的Hazelcast分布式锁

[英]Hazelcast Distributed Lock with iMap

We are currently using Hazelcast 3.1.5. 我们当前正在使用Hazelcast 3.1.5。 I have a simple distributed locking mechanism that is supposed to provide thread safety across multiple JVM nodes. 我有一个简单的分布式锁定机制,该机制应该在多个JVM节点之间提供线程安全性。 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. 早些时候,我曾经直接调用HazelcastInstance.getLock(),尽管在涉及多个JVM的情况下我们从未见过任何异常,但事情似乎仍然奏效。 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? Hazelcast分布式锁的实现是否存在任何突出的错误,我应该对我的配置做些不同的事情吗? And, Oh my configuration has multicast disabled and tcp-ip enabled 而且,哦,我的配置已禁用多播并启用了tcp-ip

Here is how you can use IMap as a lock container. 这是将IMap用作锁定容器的方法。 You don't need to have entry for the name present in the map in order to lock it. 您无需为地图中存在的name输入任何内容即可将其锁定。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM