• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Locking trouble...

 
Ranch Hand
Posts: 194
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.

Henry
 
Ranch Hand
Posts: 1170
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
No. Redesign so that you don't need both locks. Rarely should you consciously require 2 locks at the same time.
 
Space pants. Tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic