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.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description class
KeyBasedLocksMap.KeyBasedLock
-
Constructor Summary
Constructors Constructor Description KeyBasedLocksMap()
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description static Object
createLockKey(Object... keyElements)
KeyBasedLocksMap.KeyBasedLock
lockForKey(Object lockKey)
Acquires the lock for the given key.KeyBasedLocksMap.KeyBasedLock
lockForKeyElements(Object... keyElements)
Acquires the lock constructing the key from given elements.
-
-
-
Method Detail
-
lockForKeyElements
public KeyBasedLocksMap.KeyBasedLock lockForKeyElements(Object... keyElements)
Acquires the lock constructing the key from given elements. Each key element must implementObject.hashCode()
andObject.equals(Object)
properly!- Parameters:
keyElements
- the elements of the key.- Returns:
- the lock.
- See Also:
lockForKey(Object)
-
lockForKey
public KeyBasedLocksMap.KeyBasedLock lockForKey(Object lockKey)
Acquires the lock for the given key. To acquire a lock for current thread means to successfullyputIfAbsent()
alock
locked for current thread intolocks 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:
- 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.
- Then current thread creates a new
myLock
object and locks it. - Then current thread tries to put it's
myLock
to the locks map under given key. - If
putIfAbsent()
operation is successful, then the current thread successfully acquired a lock for given key and the method returns. - Otherwise
putIfAbsent()
returns the currently heldotherLock
for given key by another thread, so current thread tries to acquire it - usinglock()
method it waits until it succeeds in acquiring the lock for itself. - When current thread finally acquired the lock from different thread it unlocks previously created
myLock
object and uses theotherLock
in it's place and goes back to step 2.
- Parameters:
lockKey
- the key to acquire lock for.- Returns:
- key based lock
- See Also:
Lock.lock()
-
-