This week's giveaway is in the EJB and other Java EE Technologies forum. We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line! See this thread for details.
I have two objects that are monitors. A client calls a method on the first, which is synchronized so therefore gets ownership of the first objects lock. The client then enters a method from the second object, which is also synchronized, and so the thread now owns two locks. The client then calls wait on the second object.
The problem is that wait releases it's lock on the second object, but i don't think it does so on the first, this causes deadlock.
Is there a way to make the thread give up both locks on the wait method of the second object? I need both locks, but I only want to wait on the second object.
You are absolutely right, only the second lock is released... but put yourself into the position of the first object. How do you know that when you call the second object's method, that it will do a wait() that is thread safe? There is no way that the JVM can know that.
And if it is thread safe, why are you still synchronized? If at the time, you call the second object, you don't need the lock, you should release it -- use synchronized blocks, and get the method call out of the block.
And if you need the lock all the way to the point of the wait() method call, then unfortunately, you may have to refactor your algorithm. Consider using an external locking mechanism, that both objects can share.