简体   繁体   中英

Concurrency: Condition.awaitNanos() not releasing lock

In my program i am using a Condition object created from a

private static final Lock lock = new ReentrantLock();

like so:

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

Occasionally (as it is always happening with concurrency problems) i encounter following behavior:

  1. Thread1 aquires the lock
  2. Thread1 calls operationFinished.awaitNanos() - this should suspend Thread1 and release the lock.
  3. Thread2 tries to aquire the same lock, but debugging output shows that Thread1 is still holding the lock!

According to documentation this behavior is impossible, because upon awaitNanos() Thread1 first releases the lock and then suspends. If it didn't release the lock, then it would not suspend, therefore Thread2 could never even get a possibility to try to get hold on the lock.

Has anybody experienced something similar? This errors happens once in 100 times - but still it indicates that I am either not using the concurrency-utilities in a proper way, or that there is some kind of bug in the java.utils.concurrent.* package (which i doubt).

UPDATE:

In response to Peters answer:

I observe following behavior: Apparently the 2 threads deadlock each other. I can see that Thread2 blocks (waiting for the lock) and at the same time awaitNanos() in Thread1 never times out.

Depending on how you are viewing this information, I have seen many examples of where multiple threads wait() on an object still say they are all holding the same lock. It may be that the stack trace or monitoring is mis-leading.

Say you have thread1 which is holding the lock, but in awaitNanos(), you have Thread2 which is trying to obtain the lock(), but sometimes Thread3 is holding the lock as well....

I would do a jstack -l {pid} to check all the threads which might be holding the lock.

If a lock deadlocks, awaitLock (nor wait()) won't return as it must acquire the lock before doing so. (Unless it is interrupted)

Are you sure that the wait time hasn't finished? If you wait for a short period of time (a few hundred nanoseconds, for example), the wait time could expire before Thread2 can fully start, in which case Thread1 might be reactivated first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM