锁定hazelcast集群中的密钥

时间:2017-06-01 09:00:08

标签: caching hazelcast jcache jsr107

我正在编写一个使用Hazelcast(JCache标准)进行缓存的分布式应用程序。

我有一个用例,我应该锁定群集中的特定密钥,以防止在更新期间进行调用。

  1. thread1:获取配置更改的项目1(放置锁定)
  2. thread2:获取更新的item1。
  3. thread2:将item1与update和新时间戳放在一起。
  4. thread1:将item1放入旧值和时间戳
  5. 我知道EhCache有一些非常相似的东西,它叫做acquireReadLockOnKey(Object key)。

    如何使用JCache和/或Hazelcast实现这种锁定?

2 个答案:

答案 0 :(得分:3)

我建议使用CAS(比较和设置)相似的操作(如ConcurrentMap :: replace)并使用乐观锁定模式,这种模式本身并不是真正的锁定。

while(true) {
  // Get the old value
  T oldValue = map.get(key);
  // Create the new value based on the "known old state"
  T newValue = createNewValue(oldValue);
  // Try to atomically exchange to the new value, if oldValue is still valid
  if (map.replace(key, oldValue, newValue) break;
  // If oldValue isn't valid anymore, retry
}

在大多数没有高争用率的情况下,这是实际锁定的最佳选择。它解决了大多数读 - 修改 - 写问题,并且不需要在集群上部署/提供EntryProcessor类。

答案 1 :(得分:2)

查看Entry Processor,它以原子和无锁方式对缓存条目执行更新操作。

相关问题