| Author |
Don't you get a deadlock in this example?
|
Dennis Zandvliet
Ranch Hand
Joined: Jun 19, 2008
Posts: 60
|
|
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
Sheriff
Joined: Sep 28, 2004
Posts: 16695
|
|
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
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Dennis Zandvliet
Ranch Hand
Joined: Jun 19, 2008
Posts: 60
|
|
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
Joined: Apr 15, 2009
Posts: 63
|
|
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
|
SCJP, SCWCD, SCBCD, SCDJWS
|
 |
Dennis Zandvliet
Ranch Hand
Joined: Jun 19, 2008
Posts: 60
|
|
|
Thanks. I was only focusing on the synchronized keyword.
|
 |
 |
|
|
subject: Don't you get a deadlock in this example?
|
|
|