Class AutoCloseableLock

java.lang.Object
org.apache.hadoop.util.AutoCloseableLock
All Implemented Interfaces:
AutoCloseable

public class AutoCloseableLock extends Object implements AutoCloseable
This is a wrap class of a ReentrantLock. Extending AutoCloseable interface such that the users can use a try-with-resource syntax.
  • Constructor Details

    • AutoCloseableLock

      public AutoCloseableLock()
      Creates an instance of AutoCloseableLock, initializes the underlying lock instance with a new ReentrantLock.
    • AutoCloseableLock

      public AutoCloseableLock(Lock lock)
      Wrap provided Lock instance.
      Parameters:
      lock - Lock instance to wrap in AutoCloseable API.
  • Method Details

    • acquire

      public AutoCloseableLock acquire()
      A wrapper method that makes a call to lock() of the underlying ReentrantLock object. Acquire teh lock it is not held by another thread, then sets lock held count to one, then returns immediately. If the current thread already holds the lock, increase the lock help count by one and returns immediately. If the lock is held by another thread, the current thread is suspended until the lock has been acquired by current thread.
      Returns:
      The ReentrantLock object itself. This is to support try-with-resource syntax.
    • release

      public void release()
      A wrapper method that makes a call to unlock() of the underlying ReentrantLock object. Attempts to release the lock. If the current thread holds the lock, decrements the hold count. If the hold count reaches zero, the lock is released. If the current thread does not hold the lock, then IllegalMonitorStateException is thrown.
    • close

      public void close()
      Attempts to release the lock by making a call to release(). This is to implement close() method from AutoCloseable interface. This allows users to user a try-with-resource syntax, where the lock can be automatically released.
      Specified by:
      close in interface AutoCloseable
    • tryLock

      public boolean tryLock()
      A wrapper method that makes a call to tryLock() of the underlying Lock object. If the lock is not held by another thread, acquires the lock, set the hold count to one and returns true. If the current thread already holds the lock, the increment the hold count by one and returns true. If the lock is held by another thread then the method returns immediately with false.
      Returns:
      true if the lock was free and was acquired by the current thread, or the lock was already held by the current thread; and false otherwise.
    • newCondition

      public Condition newCondition()
      Returns:
      the Condition object