Class CloseableReentrantLock

java.lang.Object
java.util.concurrent.locks.ReentrantLock
host.anzo.commons.concurrent.CloseableReentrantLock
All Implemented Interfaces:
Serializable, AutoCloseable, Lock

public class CloseableReentrantLock extends ReentrantLock implements AutoCloseable
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 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 Details

    • CloseableReentrantLock

      public CloseableReentrantLock(boolean fair)
      Constructs a CloseableReentrantLock with the given fairness policy.

      If the fairness policy is set to true, threads will acquire the lock in the order they requested it (FIFO). If false, 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 - true for a fair lock, false for a non-fair lock
    • CloseableReentrantLock

      public CloseableReentrantLock()
      Constructs a CloseableReentrantLock with a fair locking policy (FIFO order).

      This is a deviation from the standard ReentrantLock, which defaults to non-fair mode.
  • Method Details

    • open

      public CloseableReentrantLock 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, an IllegalMonitorStateException is thrown. This method is idempotent; calling it multiple times has no additional effect if the thread still holds the lock.
      Specified by:
      close in interface AutoCloseable
      Throws:
      IllegalMonitorStateException - if the current thread does not hold the lock.