public class AutoCloseableReentrantLock extends Object
ReentrantLock lock that can be unlocked using an AutoCloseable. This allows for easy locking of
resources, using a specific class as a namespace. Typical usage:
try (final AutoCloseableReentrantLock.AutoCloseableLock ignored = new AutoCloseableReentrantLock(Clazz.class, user.getUsername()).lock()) {
user.performNonThreadSafeTask();
}
This essentially has the same effect as:
synchronised ((Clazz.class.getName() + user.getUsername()).intern()) {
user.performNonThreadSafeTask();
}
but has advantages in that the current status of the lock can interrogated, the lock can be acquired interruptibly, etc.
| Modifier and Type | Class and Description |
|---|---|
static class |
AutoCloseableReentrantLock.AutoCloseableLock |
| Constructor and Description |
|---|
AutoCloseableReentrantLock(Class clazz,
String resource)
Create a class and resource specific lock.
|
| Modifier and Type | Method and Description |
|---|---|
boolean |
isHeldByCurrentThread()
Queries if this lock is held by the current thread.
|
boolean |
isLocked()
Queries if this lock is held by any thread.
|
AutoCloseableReentrantLock.AutoCloseableLock |
lock()
Acquires the lock, blocking indefinitely.
|
AutoCloseableReentrantLock.AutoCloseableLock |
lockInterruptibly()
Acquires the lock, blocking until the lock is acquired or the thread is interrupted.
|
Optional<AutoCloseableReentrantLock.AutoCloseableLock> |
tryLock()
Tries to acquire the lock, returning immediately.
|
public AutoCloseableReentrantLock(Class clazz, String resource)
clazz - The class for which the lock should be created.resource - The resource for which the lock should be created.public AutoCloseableReentrantLock.AutoCloseableLock lock() throws IllegalStateException
IllegalStateException - if this lock has already been released by the last thread to hold itpublic Optional<AutoCloseableReentrantLock.AutoCloseableLock> tryLock()
IllegalStateException - if this lock has already been released by the last thread to hold itpublic AutoCloseableReentrantLock.AutoCloseableLock lockInterruptibly() throws InterruptedException, IllegalStateException
InterruptedException - if the thread was interrupted before the lock could be acquiredIllegalStateException - if this lock has already been released by the last thread to hold itpublic boolean isHeldByCurrentThread()
true if current thread holds this lock and false otherwiseReentrantLock.isHeldByCurrentThread()public boolean isLocked()
true if any thread holds this lock and false otherwiseReentrantLock.isLocked()Copyright © 2003–2019 Ignite Realtime. All rights reserved.