The use of Lock lock and the difference between Lock and Synchronized

What is Lock? Why do I need Lock?

锁是用来控制多个线程访问共享资源的方式,一般来说,一个锁能够防止多个线程同时
访问共享资源(但是有些锁可以允许多个线程并发的访问共享资源,比如读写锁).

在Lock接口出现之前,Java程序是靠synchronized关键字实现锁功能的,而Java SE 5之后,并发包中新增
了Lock接口(以及相关实现类)用来实现锁功能,它提供了与synchronized关键字类似的同步功
能,只是在使用时需要显式地获取和释放锁.

虽然它缺少了(通过synchronized块或者方法所提供的)隐式获取释放锁的便捷性,
但是却拥有了锁获取与释放的可操作性、可中断的获取锁以及超时获取锁等多种synchronized关键字所不具备的同步特性.

使用synchronized关键字将会隐式地获取锁,但是它将锁的获取和释放固化了,也就是先获取再释放,
当然,这种方式简化了同步的管理,可是扩展性没有显示的锁获取和释放来的好

The use of Lock:

Lock lock = new ReentrantLock();
lock.lock(); // 加锁
try{
    // do something
}finally{
    lock.unlock(); // 解锁
}

Why is it not recommended to put lock.lock() locking code in try?

Because the lock operation may throw an exception

Normal situation (recommended): The lock operation is before the try block, then the try-finally block will not be executed when an exception occurs, and the program will be interrupted directly due to the exception.

Not recommended: the lock operation is in the try block. Since the try block has been executed, the finally will still be executed when an exception occurs in the try. If at this time, the lock operation in the try is abnormal, the finally will still perform the unlock operation. At this time, the lock is not acquired, so another exception will be thrown when the unlock operation is performed. Although all exceptions are thrown, the exception information thrown by finally unlocking will overwrite the locked exception information, resulting in loss of information

Can lock.lock() be added in front of the code block before try-finally? Yes, give reasons, no, give reasons.

No, the reason is that if there is an exception in the code block before try-finally, the program will not go to the try-finally area, and the lock.lock() operation is performed before the abnormal code block. Due to the exception, the program ends. At this time, the lock added before is not released normally in finally, then a deadlock may occur

Lock's new features compared to Synchronized

Methods provided by the Lock API

Guess you like

Origin blog.csdn.net/weixin_43562937/article/details/107225970