Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Don't you get a deadlock in this example?

 
Dennis Zandvliet
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was looking at this example How to use wait() and notify()



Now I'm wondering if this code isn't causing a deadlock, because both methods synchronize on the same object 'connections'?

If not, why?
 
Henry Wong
author
Marshal
Pie
Posts: 21413
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dennis Zandvliet wrote:
Now I'm wondering if this code isn't causing a deadlock, because both methods synchronize on the same object 'connections'?

If not, why?


Well, can you explain to us, why you think it is so? Synchronizing on the same lock is common when two methods need to work on the same thing, and isn't enough to say that something is a deadlock.

Henry
 
Dennis Zandvliet
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry Wong wrote:
Well, can you explain to us, why you think it is so? Synchronizing on the same lock is common when two methods need to work on the same thing, and isn't enough to say that something is a deadlock.


You're competely right! :-)


Well, if the getConnection() method holds a lock on the connection object, how can the returnConnection() method enter the synchronize block to send a notify, because it's also locked on the same object?
 
Adam Smolnik
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey.

You are not precise. You hold the lock on the "connections" object not "connection".
Please, take look at the explanation of "wait" method:

http://java.sun.com/javase/6/docs/api/java/lang/Object.html#wait()

Especially:

...
The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until either of the following two conditions has occurred:

Another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method.
The timeout period, specified by timeout milliseconds plus nanos nanoseconds arguments, has elapsed.

Adam
 
Dennis Zandvliet
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks. I was only focusing on the synchronized keyword.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic