Package host.anzo.commons.concurrent
Class CloseableReentrantLock
java.lang.Object
java.util.concurrent.locks.ReentrantLock
host.anzo.commons.concurrent.CloseableReentrantLock
- All Implemented Interfaces:
Serializable,AutoCloseable,Lock
A CloseableReentrantLock is a specialized implementation of a ReentrantLock
that implements the AutoCloseable interface. This allows the lock to be used
in a try-with-resources statement, ensuring that the lock is properly released
when it is no longer needed.
Unlike the standard
Note: Fair locks are generally slower than non-fair locks, as they require more atomic operations to maintain strict ordering.
Unlike the standard
ReentrantLock, this implementation defaults to a
fair locking policy (FIFO order). This means threads will acquire the lock
in the order they requested it, but it may impact performance due to additional
synchronization overhead.
Note: Fair locks are generally slower than non-fair locks, as they require more atomic operations to maintain strict ordering.
- Since:
- 20.11.2016
- See Also:
-
Constructor Summary
ConstructorsConstructorDescriptionConstructs a CloseableReentrantLock with a fair locking policy (FIFO order).CloseableReentrantLock(boolean fair) Constructs a CloseableReentrantLock with the given fairness policy. -
Method Summary
Methods inherited from class java.util.concurrent.locks.ReentrantLock
getHoldCount, getOwner, getQueuedThreads, getQueueLength, getWaitingThreads, getWaitQueueLength, hasQueuedThread, hasQueuedThreads, hasWaiters, isFair, isHeldByCurrentThread, isLocked, lock, lockInterruptibly, newCondition, toString, tryLock, tryLock, unlock
-
Constructor Details
-
CloseableReentrantLock
public CloseableReentrantLock(boolean fair) Constructs a CloseableReentrantLock with the given fairness policy.
If the fairness policy is set totrue, threads will acquire the lock in the order they requested it (FIFO). Iffalse, the lock permits barging, allowing threads to acquire the lock out of order for better performance.
Warning: Fair locks may significantly reduce throughput under high contention.- Parameters:
fair-truefor a fair lock,falsefor a non-fair lock
-
CloseableReentrantLock
public CloseableReentrantLock()Constructs a CloseableReentrantLock with a fair locking policy (FIFO order).
This is a deviation from the standardReentrantLock, which defaults to non-fair mode.
-
-
Method Details
-
open
Acquires the lock, blocking until it is available.- Returns:
- this instance of CloseableReentrantLock, allowing for method chaining.
-
close
public void close()Releases the lock. This method is called automatically when the try-with-resources block is exited.
If the current thread does not hold the lock, anIllegalMonitorStateExceptionis thrown. This method is idempotent; calling it multiple times has no additional effect if the thread still holds the lock.- Specified by:
closein interfaceAutoCloseable- Throws:
IllegalMonitorStateException- if the current thread does not hold the lock.
-