This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Threads and Synchronization and the fly likes Please help explain the deadlock. Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "Please help explain the deadlock." Watch "Please help explain the deadlock." New topic
Author

Please help explain the deadlock.

Allan Stone
Greenhorn

Joined: Oct 21, 2005
Posts: 24
Hi all,

Please help explain the following program.
Why it might cause a deadlock? And how to fix it?
Thx in advance.


With multiple threads calling create() and remove() we are getting a Java deadlock, how would you fix ?

class A{
public static Object create(){
Object obj = new Object();

synchronized( list){
list.add( obj);

callCount();
}

return obj;
}

public synchronized static void remove(Object obj){
synchronized( list){
list.remove( obj);
callCount();
}
}

public static synchronized int callCount(){
return count++;
}
private static int count;
private static ArrayList list = new ArrayList();
}


Practice make perfect.<br /> <br />SC-(JP/WCD/BCD/EA)
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24057
    
  13

If you make create() synchronized, you'll fix the deadlock situation.

Deadlocks happen when multiple threads are all trying to lock the same two objects, but they try to lock them in a different order. In your code, the create() method locks "list", and then locks A.class (via the call to the static callCount() method.) On the other hand, the remove() method is synchronized so it locks A.class first, then locks "list". A deadlock occurs when two threads have each locked one of the two objects, and are waiting for the other one -- but they never get it, as another thread has the object each one wants.

I"m moving this to our "Threads and Synchronization" forum for any further discussion.


[Jess in Action][AskingGoodQuestions]
Allan Stone
Greenhorn

Joined: Oct 21, 2005
Posts: 24
Thanks a lot, Ernest.
Your explanation was very clear. I understand the problem now.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Please help explain the deadlock.
 
Similar Threads
Singleton produce how many object?
XMLEncoder - Stackoverflowerror - overriding equals
deadlock
Producer-Consumer
problem with advance for loop