本文介绍了使用iMap的Hazelcast分布式锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们当前正在使用Hazelcast 3.1.5.我有一个简单的分布式锁定机制,该机制应该在多个JVM节点之间提供线程安全性.代码很简单.

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);
         ..
    }

更早之前,我曾经直接调用HazelcastInstance.getLock(),尽管在涉及多个JVM的情况下我们从来没有发现任何错位的情况,但事情似乎仍然奏效.最近,我被要求调查块中的数据库死锁,经过数周的调查和日志分析,我能够确定这是由于多个线程能够获取针对同一密钥的锁所致.在第一个线程可以提交代码之前,第二个线程设法获得另一个锁,这时第二个线程被第一个线程的数据库锁阻止.

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.

是否存在针对分布式锁的Hazelcast实现的任何未解决的错误,我应该对我的配置做些不同的事情吗?而且,哦,我的配置已禁用多播并启用了tcp-ip

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

推荐答案

以下是将IMap用作锁定容器的方法.您无需为地图中存在的name输入条目即可将其锁定.

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);
}

这篇关于使用iMap的Hazelcast分布式锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-27 00:48