Concurrency: Condition.awaitNanos () does not release the lock

In my program, I am using a Condition object created with

private static final Lock lock = new ReentrantLock();



private static final Condition operationFinished = MyClass.lock.newCondition();


Sometimes (since this always happens with concurrency issues), I run into the following behavior:

  • Thread1 maintains locking
  • Thread1 calls operationFinished.awaitNanos()

    - this should suspend Thread1 and release the lock.
  • Thread2 is trying to acquire the same lock, but the debug output shows that Thread1 is still holding the lock!

According to the documentation, this behavior is not possible because at awaitNanos()

Thread1 it first releases the lock and then suspends. If it does not release the lock, then it will not suspend, so Thread2 can never get an attempt to grab the lock.

Has anyone experienced something similar? These errors happen once every 100 times, but it still indicates that I am either not using concurrency -utilities correctly, or that there is some kind of bug in the java.utils.concurrent package. * (Which I doubt).


In response, Peters replies:

I observe the following behavior: Apparently 2 threads are locking each other. I see that Thread2 blocks (waiting for locks) and at the same time awaitNanos()

in Thread1 never fail.


source to share

2 answers

Depending on how you are viewing this information, I've seen many examples of where multiple threads wait()

on an object still say they all have the same lock. It is possible that the stack trace or monitoring is incorrect.

Let's say you have thread1 that holds a lock, but while waiting for Nanos (), you have Thread2 that is trying to acquire lock (), but sometimes Thread3 also holds a lock ....

I would do jstack -l {pid}

to check all threads that might be holding a lock.

If the lock is blocking, awaitLock (or wait ()) will not return because it must acquire the lock before doing so. (Unless it interrupts)



Are you sure the waiting time is not over yet? If you are waiting for a short period of time (for example, a few hundred nanoseconds), it may time out before Thread2 can fully start, in which case Thread1 may be activated first.



All Articles