Class KeyBasedLocksMap

java.lang.Object
com.cumulocity.microservice.context.scope.KeyBasedLocksMap

public class KeyBasedLocksMap extends Object
A locking mechanism based on keys, where a lock is created per given key.
  • Constructor Details

    • KeyBasedLocksMap

      public KeyBasedLocksMap()
  • Method Details

    • createLockKey

      public static Object createLockKey(Object... keyElements)
    • lockForKeyElements

      public KeyBasedLocksMap.KeyBasedLock lockForKeyElements(Object... keyElements)
      Acquires the lock constructing the key from given elements. Each key element must implement Object.hashCode() and Object.equals(Object) properly!
      Parameters:
      keyElements - the elements of the key.
      Returns:
      the lock.
      See Also:
    • lockForKey

      public KeyBasedLocksMap.KeyBasedLock lockForKey(Object lockKey)
      Acquires the lock for the given key. To acquire a lock for current thread means to successfully putIfAbsent() a lock locked for current thread into locks map.

      Acquires the lock if it is not held by any thread and returns immediately, setting the lock hold count to one.

      If the lock is held by any thread then the current thread becomes disabled for thread scheduling purposes and lies dormant until the lock has been acquired, at which time the lock hold count is set to one.

      The algorithm of obtaining a lock is:

      1. One thread can obtain a lock only once at a time, so first we validate that if there already is a lock for given key than it's not the current threads lock.
      2. Then current thread creates a new myLock object and locks it.
      3. Then current thread tries to put it's myLock to the locks map under given key.
      4. If putIfAbsent() operation is successful, then the current thread successfully acquired a lock for given key and the method returns.
      5. Otherwise putIfAbsent() returns the currently held otherLock for given key by another thread, so current thread tries to acquire it - using lock() method it waits until it succeeds in acquiring the lock for itself.
      6. When current thread finally acquired the lock from different thread it unlocks previously created myLock object and uses the otherLock in it's place and goes back to step 2.
      Parameters:
      lockKey - the key to acquire lock for.
      Returns:
      key based lock
      See Also: