Lock on a key in a hazelcast cluster

2.9k views Asked by At

I am writing a distributed application using Hazelcast(JCache standard) for caching.

I have an use case where I should put a lock on specific key in a cluster to prevent from calls during updating.

  1. thread1: get item1 for a config change(put a lock)
  2. thread2: get item1 for an update.
  3. thread2: put item1 with update and a new timestamp.
  4. thread1: put item1 with an old value and timestamp

I know EhCache has something very similar, it's called acquireReadLockOnKey(Object key).

How can I achieve that kind of lock using JCache and/or Hazelcast?

2

There are 2 answers

3
Mikhail Baksheev On

Look at Entry Processor which performs update operations on cache entries in an atomic and lock-free manner.

0
noctarius On

I would suggest to use CAS (Compare And Set) alike operations (like ConcurrentMap::replace) and utilize an optimistic locking pattern which is not a real lock in itself.

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
}

In most situation where there is no high contention rate, this is the best alternativ over real locking. It solves most of the read-modify-write problems and doesn't need EntryProcessor classes to be deployed/available on the cluster.