What is the difference in using ReentrentLock and Synchronized (object)?

Possible duplicate:
Sync & Lock

I am wondering if there is a big difference in using ReentrentLock and Synchronized (object)?

Why is it called reentrentLock? allow recursive call from the same thread?

+6
source share
2 answers

I am wondering if there is a big difference in using ReentrantLock and synchronized (object) .

The main differences:

  • With synchronized locking / unlocking is tied to the block structure of the source code. A synchronized lock will be released when you exit the block, regardless of how you do it. For example, it will be released if the block exits due to an unexpected exception.

    With an explicit lock, this is not the case, so you can acquire ReentrantLock (or any other Lock ) in one way and release it in another. But the flip side is that you must remember to explicitly release the Lock at the appropriate time / place. If you do not, you will have a stuck castle and (possibly) dead ends. In short, ReentrantLock more complex and potentially more error prone.

  • The primitive lock you get with synchronized works with Object.wait() and Object.notify() . Lock no.

  • A ReentrantLock can be created as β€œfair”, which means that threads waiting to receive this lock will receive a fifo lock. Primitive castles are not fair.

  • The ReentrantLock API has methods that you can use to check whether a lock is used, find out the length of the lock queue, try to get a lock without a lock, and various other things. None of these features are available for primitive locks.

Why is it called a reentrant lock? allow recursive call from the same thread?

Retentate blocking allows the flow holding the lock to re-acquire it. One way this can happen is recursion, but there are others.

For recording, synchronized locks are reentrant, so you don’t have to worry about recursion or other scenarios when a thread can get a lock that it already has.

+7
source

Source: https://habr.com/ru/post/905426/


All Articles