public final class ContextMutexFactory extends Object
Map
. Client code is responsible to invoke
ContextMutexFactory.Mutex.close()
on the obtained 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 non-thread-safe Map
on a per-key basis,
to avoid blocking other threads who would perform updates on other entries of the Map
.
class Test { private static final ContextMutexFactory mutexFactory = new ContextMutexFactory(); private Map<String, String> mapToSync = new HashMap<String, String>(); public void test(String key, String value) { // critical section ContextMutexFactory.Mutex mutex = mutexFactory.mutexFor(key); try { synchronized (mutex) { if (mapToSync.get(key) == null) { mapToSync.put(key, 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 © 2016 Hazelcast, Inc.. All Rights Reserved.