aspose file tools*
The moose likes Threads and Synchronization and the fly likes Don't you get a deadlock in this example? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Don Watch "Don New topic
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: 18138
    
  39

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Don't you get a deadlock in this example?
 
Similar Threads
Datasource and connection
connection problem
Datasource
DBUtility for closing connections
Database Connection Pool Not Releasing Connection to pool