jkl
jkl

Reputation: 49

java - calling synchronized method from inside synchronized while waiting

is it possible to call a synchronized method from inside a synchronized method while waiting for resource to become available (using wait())? thanks

Upvotes: 4

Views: 6418

Answers (2)

Jeeyoung Kim
Jeeyoung Kim

Reputation: 6078

No. there's no way to check whether a given object's monitor is currently on hold in java, or an atomic way to "check and grab" the object's lock.

You may want to check out the standard java package http://java.sun.com/javase/6/docs/api/java/util/concurrent/locks/package-summary.html though. the class Lock has the functionality tryLock(), which can try to gain the lock (so if your thread fails to get hold of the lock, then it can do something else depending on the return value of tryLock()).

Upvotes: 0

Michael Aaron Safyan
Michael Aaron Safyan

Reputation: 95489

Java's mutexes are recursive, so you can invoke a synchronized method recursively or invoke another synchronized method for which you already hold a lock. You will need to tell us what it is you are specifically trying to do, though.... lots of stuff with thread locking/synchronization, if done incorrectly, can lead to deadlock, and it isn't entirely clear from your question what you are attempting to do.

Upvotes: 9

Related Questions