The use of the Lock

Reference:

  • ReentranLock detail, combat, and contrast Synchronized
  • Is lock.lock() written inside the try block?

1.LockThe 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:

  1. infinallyBlock to ensure that the lock will eventually be released after it is acquired, otherwise a deadlock will occur
  2. Do not write the lock acquisition process in a try block: Because if inlock.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 releasedIllegalMonitorStateExceptionThe exception.

1.2 commonly used API

  • lock.lock(): Obtains the lock and waits if the lock is temporarily used
  • lock.tryLock(): Retrieves the lock, returns immediately, without waiting: returns false if the lock was occupied at the time it was acquired, true otherwise
  • Lock.tryLock(long time, TimeUnit unit) throw InterruptedExceptionWith:lock.tryLock()It’s just the extra timeout to get the lock.
  • Lock.lockInterruptibly(): The lock acquisition can be interrupted accordingly
  • lock.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()