• Post Reply Bookmark Topic Watch Topic
  • New Topic

How To Avoid Deadlock?

 
JiaPei Jen
Ranch Hand
Posts: 1309
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do we avoid deadlock?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24213
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's a fairly complicated topic; there's no single short answer. I think every Java programmer should read Doug Lea's book on the topic, which gives an excellent overview.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Um.... Don't use multiple threads or processes.
Moving this to the Threads and Synchronization forum...
[ January 16, 2004: Message edited by: Dirk Schreckmann ]
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A typical deadlock occurs where two threads do something like:
I lock A and wait for B
You lock B and wait for A
We both wait forever
One prevention guideline is: If you're going to lock two or more objects, always lock them in the same order. This is tough if you don't own all the code or if developers are not disciplined. I saw one utility that obtained locks on a collection of objects. It sorted the objects on their hashcodes or toString() values or something that you could trust to be invariant. Now it works more like:
I do getLock( { A, B } );
You do getLock( { B, A } );
the utility sorts the two lists
I get A
You wait for A
I get B
I release B
I release A
You get A
...
Take a look at Doug Lea's stuff mentioned above. That utility might have been in his things.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!