The use of the Lock
Reference:
- ReentranLock detail, combat, and contrast Synchronized
- Is lock.lock() written inside the try block?
1.Lock
The basic use
1.1 grammar
Lock interface, ReentranLock is the implementation of the Lock interface class.
// Instantiate an object (default is unfair lock)
Lock lock = new ReentrantLock();
lock.lock();
try {
// ..
} finally {
// Must release the lock in finally
lock.unlock();
}
Copy the code
Note:
- in
finally
Block to ensure that the lock will eventually be released after it is acquired, otherwise a deadlock will occur - Do not write the lock acquisition process in a try block: Because if in
lock.lock()
When an exception occurs (that is, when an exception is thrown ina try), it occurs in finallylock.unlock()
. In this case, because the lock failed to be acquired, the lock will be releasedIllegalMonitorStateException
The exception.
1.2 commonly used API
lock.lock()
: Obtains the lock and waits if the lock is temporarily usedlock.tryLock()
: Retrieves the lock, returns immediately, without waiting: returns false if the lock was occupied at the time it was acquired, true otherwiseLock.tryLock(long time, TimeUnit unit) throw InterruptedException
With:lock.tryLock()
It’s just the extra timeout to get the lock.Lock.lockInterruptibly()
: The lock acquisition can be interrupted accordinglylock.unlock()
: the lock is released
1.2.1 the Lock Condition
Public Condition Condition = lock.newCondition()
It is used to replace the traditional wait() and notify() of Object.
Condition | Object | describe |
---|---|---|
await() | wait() | blocking |
signal() | notify() | Wake up the |
signalAll() | notifyAll() |