public final class ContextMutexFactory extends Object
Context objects and their associated mutexes are stored in a Map
. Client code is responsible to invoke
ContextMutexFactory.Mutex.close()
on the obtained ContextMutexFactory.Mutex
after having synchronized on the mutex; failure to do so
will leave an entry residing in the internal Map
which may have adverse effects on the ability to garbage
collect the context object and the mutex.
The returned ContextMutexFactory.Mutex
es implement Closeable
, so can be conveniently used in a try-with-resources statement.
Typical usage would allow, for example, synchronizing access to a ConcurrentMap
on a
per-key basis, to avoid blocking other threads which could perform updates on other entries of the Map
.
class Test { private final ContextMutexFactory mutexFactory = new ContextMutexFactory(); private final ConcurrentMapmapToSync = new ConcurrentHashMap (); public String getValueForKey(String key) { ContextMutexFactory.Mutex mutex = mutexFactory.mutexFor(key); try { synchronized (mutex) { // critical section - this thread is the only one trying to add value under this key String value = mapToSync.get(key); if (value == null) { value = ...; // compute the value mapToSync.put(key, value); } return value; } } finally { mutex.close(); } } }
Modifier and Type | Class and Description |
---|---|
class |
ContextMutexFactory.Mutex
Reference counted mutex, which will remove itself from the mutexMap when it is no longer referenced.
|
Constructor and Description |
---|
ContextMutexFactory() |
public ContextMutexFactory.Mutex mutexFor(Object mutexKey)
Copyright © 2018 Hazelcast, Inc.. All Rights Reserved.