What is the meaning of “ReentrantLock” in Java?

后端 未结 6 1967
故里飘歌
故里飘歌 2020-11-30 22:18

Reentrancy means that locks are acquired on a per-thread rather than per-invocation basis.

Since an intrinsic lock is held by a thread, doesn\'t it mean that a threa

6条回答
  •  不知归路
    2020-11-30 22:35

    Imagine something like this:

    function A():
       lock (X)
           B()
       unlock (X)
    
    function B():
        A()
    

    Now we call A. The following happens:

    • We enter A, locking X
    • We enter B
    • We enter A again, locking X again

    Since we never exited the first invocation of A, X is still locked. This is called re-entrance - while function A has not yet returned, function A is called again. If A relies on some global, static state, this can cause a 're-entrance bug', where before the static state is cleaned up from the function's exit, the function is run again, and the half computed values collide with the start of the second call.

    In this case, we run into a lock we are already holding. If the lock is re-entrance aware, it will realize we are the same thread holding the lock already and let us through. Otherwise, it will deadlock forever - it will be waiting for a lock it already holds.

    In java, lock and synchronized are re-entrance aware - if a lock is held by a thread, and the thread tries to re-acquire the same lock, it is allowed. So if we wrote the above pseudocode in Java, it would not deadlock.

提交回复
热议问题