search

Home  >  Q&A  >  body text

java - ReentrantLock和Synchronized

When resource competition is not very intense, Synchronized's performance is better than ReetrantLock's. However, when resource competition is intense, Synchronized's performance will drop dozens of times, but ReetrantLock's performance can remain normal

(1) Why is this?
(2) Is ReentrantLock a lightweight lock? What are lightweight locks? I have only heard of this name, but I have never seen a concrete implementation

When using synchronized, if the program runs incorrectly, an exception will be thrown, but no cleanup work will be done. Using ReentrantLock allows you to try to acquire a lock but ultimately not acquire it, so that if someone else has acquired the lock, you can leave to perform other things (but what I want to do now is to perform certain operations after acquiring the lock) , it doesn't seem to make much sense to switch to performing other things now), instead of waiting until the lock is released.

天蓬老师天蓬老师2748 days ago825

reply all(2)I'll reply

  • 仅有的幸福

    仅有的幸福2017-05-17 10:05:59

    First of all, the situation you mentioned only existed when ReentrantLock was first introduced in Java 1.5. Java 1.6 has modified the Synchronized implementation algorithm, which is basically consistent with the implementation of ReentrantLock, so the performance difference between the two is already very small.
    Regarding lightweight locks, this is a way to improve lock performance introduced in Java 1.6. It belongs to the JVM level and there is no specific implementation.
    If you want to wait until the lock is released, you can use Lock.lock() to obtain the lock. Using Lock.tryLock() is trying to obtain the lock and may not be able to obtain the lock.

    reply
    0
  • ringa_lee

    ringa_lee2017-05-17 10:05:59

    It can be understood simply that synchronized read and write pages are mutually exclusive, but ReentrantLock has read and write locks. Read locks can be shared, but write locks are mutually exclusive. If you look at it from here, ReentrantLock will read more and write less. The performance will be much higher, but the code is more complicated than synchronized, and it is easy to cause problems if the control is not good.

    reply
    0
  • Cancelreply