Win a copy of Five Lines of Code this week in the OO, Patterns, UML and Refactoring forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

Please help explain the deadlock.

 
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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();
}
 
author and iconoclast
Posts: 24203
43
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Allan Stone
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot, Ernest.
Your explanation was very clear. I understand the problem now.
 
sunglasses are a type of coolness prosthetic. Check out the sunglasses on this tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic