com.hazelcast.util

## Class ContextMutexFactory

- java.lang.Object
- - com.hazelcast.util.ContextMutexFactory

-     public final class ContextMutexFactory
      extends Object

  Provides reference-counted mutexes suitable for synchronization in the context of a supplied 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 ConcurrentMap<String, String> mapToSync = new ConcurrentHashMap<String, String>();

              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();
                  }
              }
          }

- - ### Nested Class Summary

    Nested Classes
    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 Summary

    Constructors
    Constructor and Description
    `ContextMutexFactory()`

  - ### Method Summary

    All Methods Instance Methods Concrete Methods
    Modifier and Type | Method and Description
    --- | ---
    `ContextMutexFactory.Mutex` | `mutexFor(Object mutexKey)`

    - ### Methods inherited from class java.lang.Object

      `clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

- - ### Constructor Detail

    - #### ContextMutexFactory

          public ContextMutexFactory()

  - ### Method Detail

    - #### mutexFor

          public ContextMutexFactory.Mutex mutexFor(Object mutexKey)

Copyright © 2019. All rights reserved.