Package org.apache.hadoop.util
Class AutoCloseableLock
java.lang.Object
org.apache.hadoop.util.AutoCloseableLock
- All Implemented Interfaces:
AutoCloseable
This is a wrap class of a ReentrantLock. Extending AutoCloseable
interface such that the users can use a try-with-resource syntax.
-
Constructor Summary
ConstructorsConstructorDescriptionCreates an instance ofAutoCloseableLock, initializes the underlying lock instance with a newReentrantLock.AutoCloseableLock(Lock lock) Wrap provided Lock instance. -
Method Summary
Modifier and TypeMethodDescriptionacquire()A wrapper method that makes a call tolock()of the underlyingReentrantLockobject.voidclose()Attempts to release the lock by making a call torelease().voidrelease()A wrapper method that makes a call tounlock()of the underlyingReentrantLockobject.booleantryLock()A wrapper method that makes a call totryLock()of the underlyingLockobject.
-
Constructor Details
-
AutoCloseableLock
public AutoCloseableLock()Creates an instance ofAutoCloseableLock, initializes the underlying lock instance with a newReentrantLock. -
AutoCloseableLock
Wrap provided Lock instance.- Parameters:
lock- Lock instance to wrap in AutoCloseable API.
-
-
Method Details
-
acquire
A wrapper method that makes a call tolock()of the underlyingReentrantLockobject. 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
ReentrantLockobject itself. This is to support try-with-resource syntax.
-
release
public void release()A wrapper method that makes a call tounlock()of the underlyingReentrantLockobject. 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, thenIllegalMonitorStateExceptionis thrown. -
close
public void close()Attempts to release the lock by making a call torelease(). This is to implementclose()method fromAutoCloseableinterface. This allows users to user a try-with-resource syntax, where the lock can be automatically released.- Specified by:
closein interfaceAutoCloseable
-
tryLock
public boolean tryLock()A wrapper method that makes a call totryLock()of the underlyingLockobject. If the lock is not held by another thread, acquires the lock, set the hold count to one and returnstrue. If the current thread already holds the lock, the increment the hold count by one and returnstrue. If the lock is held by another thread then the method returns immediately withfalse.- Returns:
trueif the lock was free and was acquired by the current thread, or the lock was already held by the current thread; andfalseotherwise.
-
newCondition
- Returns:
- the Condition object
-