wood burning stoves
The moose likes Threads and Synchronization and the fly likes Locking trouble... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Locking trouble..." Watch "Locking trouble..." New topic

Locking trouble...

James Turner
Ranch Hand

Joined: May 10, 2004
Posts: 194
Hi All,

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.

Is there any way to do this?

Any help is appreciated..


James<br />SCJP 1.4 - 92%<br />SCJD - 93%<br />SCWCD 1.4 - 95%<br />SCBCD 1.3 - 100%<br />SCEA - 92%
Henry Wong

Joined: Sep 28, 2004
Posts: 20531

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.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Mr. C Lamont Gilbert
Ranch Hand

Joined: Oct 05, 2001
Posts: 1170

No. Redesign so that you don't need both locks. Rarely should you consciously require 2 locks at the same time.
I agree. Here's the link: http://aspose.com/file-tools
subject: Locking trouble...
It's not a secret anymore!