【Lock】1 Lock advantages and characteristics

Lock and synchronized are the most common locks used to control access to shared resources. Lock is not used to replace synchronized, but to provide more advanced functions when synchronized does not meet the requirements. Common implementation classes of the Lock interface are ReentrantLock and ReadWriteLock.

For the disadvantages of synchronized, see the previous section.

  1. Low lock efficiency
  • There are few lock releases. The synchronized monitor lock releases the lock when the method or code block exits normally and abnormally.
  • You cannot set a timeout when trying to acquire a lock,You cannot interrupt a thread that is trying to acquire a lock.
  1. Not flexible enough
    Compared with read-write locks, the timing of locking and releasing is single, and each lock has only a single condition (locking an object), which may not be enough.
  2. There is no way to know whether the lock was successfully acquired.
    For example, the tryLock method of Lock

1 Lock interface analysis

public interface Lock {
    
    
    // 获取锁
    void lock();
    // 获取锁时可以被中断
    void lockInterruptibly() throws InterruptedException;
    boolean tryLock();
    // 超时就放弃
    boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
    // 解锁
    void unlock();
    Condition newCondition();
}
  • Lock does not release the lock when it is abnormal like synchronized, so unlock finally needs to be called to ensure that the lock is released.
  • The lock() method cannot be interrupted. Once deadlocked, it will fall into a permanent wait.
  • tryLock() is used to try to acquire the lock. If the current lock is not occupied by other threads, the lock is acquired and returns true; otherwise, it returns false. The method returns immediately, and will wait even if the lock is not available.

tryLock code specification, refer to comments

Lock lock = new ReentrantLock();
if(lock.tryLock()) {
    try {
    } finally {
        lock.unlock();
    }
}

The thread is in the WAITING state while waiting for the Lock, and it cannot be BLOCKED.

2 Lock's visibility guarantee

The visibility of Lock is the same as that of synchronized, you can refer to the happens-before principle. The unlock operation is visible to the subsequent lock operation.

Lock and unlock align the lock and unlock operations in the memory interaction operation.

3 Demonstration example

The case code location of this article: https://gitee.com/dtyytop/advanced-java

Guess you like

Origin blog.csdn.net/LIZHONGPING00/article/details/113927950