锁定 hazelcast 集群中的一个键

For*_*rin 1 caching jcache hazelcast jsr107

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

我有一个用例,我应该对集群中的特定键加锁,以防止更新期间调用。

  1. thread1:获取 item1 进行配置更改(加锁)
  2. thread2:获取 item1 进行更新。
  3. thread2:将 item1 放入更新和新时间戳。
  4. thread1:将 item1 放入旧值和时间戳

我知道 EhCache 有一个非常相似的东西,它叫做 acquireReadLockOnKey(Object key)。

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

noc*_*ius 5

我建议使用 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
}
Run Code Online (Sandbox Code Playgroud)

在大多数没有高争用率的情况下,这是真正锁定的最佳替代方案。它解决了大多数读取-修改-写入问题,并且不需要在集群上部署/可用 EntryProcessor 类。