public class EphemeralLocks extends Object
Balances parallelism with thread-safety by assigning different locks to different keys. This allows threads operating on different keys to simultaneously execute the critical section while threads operating on the same key execute the critical section serially. Memory usage grows with the number of active keys. Underlying lock instances are discarded when no longer needed.
Keys must implement Object.equals(Object) and Object.hashCode() correctly.
Example usage:
private final EphemeralLocks locks = new EphemeralLocks();
...
// The id for the thread-sensitive resource. E.g. directory name, document
// id, user id, etc.
String id = ...;
// try-with-resources recommended to ensure the unlock occurs.
try (Handle ignored = locks.lock(id)) {
// critical section - do sensitive operations here
...
}
// try-finally works, too.
Handle lockHandle = locks.lock(id);
try {
// critical section - do sensitive operations here
...
} finally {
lockHandle.close();
}
| Modifier and Type | Class and Description |
|---|---|
static interface |
EphemeralLocks.Handle
Handle to close the underlying lock for a given key.
|
| Constructor and Description |
|---|
EphemeralLocks() |
| Modifier and Type | Method and Description |
|---|---|
EphemeralLocks.Handle |
lock(Object key)
Acquires the lock for the given key and returns a handle to the lock, which must be
closed to release the underlying lock.
|
int |
size()
Returns the number of active locks.
|
public EphemeralLocks.Handle lock(Object key)
key - identifies the resource requiring a lockLock.lock()public int size()
Copyright © 2018. All rights reserved.