0

Why java reentrant lock does not cause dead lock?

I was studying Reentrant lock, and did realize that a thread failed to try acquire will be placed in a sync queue, and before it parks, it set its prev node's waitStatus to SIGNAL, and recheck if the prev node has set its stat to 0, if not, it might be sure that the prev node has not unparked it, because it has not cleared the SIGNAL state, so it parks. But what if the interval between shoudParkAFterFailedAcquire and parkAndCheckInterrrupt takes, say 1 second or 1 minute long, so unpark arrives first before parking. Would this cause a deadlock? enter image description here

user207421
  • 305,947
  • 44
  • 307
  • 483
goodGuy
  • 51
  • 1
  • 6
  • 1
    Deadlock is where you have two or more threads that own locks and each thread is trying to acquire the other's locks. The situation you describe would not be a deadlock. Don't misuse standard terminology. – user207421 Jun 08 '21 at 00:44
  • OK, thanks, but what should I call this, maybe, never-waken-up parking? – goodGuy Jun 08 '21 at 00:53
  • Not sure actually. Bug? – user207421 Jun 08 '21 at 00:55
  • I didn't run into this but, I was just wondering why this would not happen. – goodGuy Jun 08 '21 at 01:02
  • Any time the outcome of a program depends on how the execution of different threads is interleaved, you can call that a "race condition." Some people prefer to say "data race" if any of the possible outcomes is acceptable, and they only say "race condition" if one or more of the possible outcomes is bad/wrong. – Solomon Slow Jun 08 '21 at 13:42

1 Answers1

4

park and unpark don't work like you seem to think they do. They are based on a permit-like system:

  • When a thread is unparked, it is granted a "permit" if it doesn't already have one.
  • When a thread calls park, it blocks until it has a permit and the permit is revoked. If it already has a permit when park is called, then it doesn't block at all.

So it doesn't matter if it takes a minute or more for acquireQueued to get to the park, because the preceding call to unpark has already provided the thread with a permit. The permit will be revoked without blocking.

Matt Timmermans
  • 53,709
  • 3
  • 46
  • 87