fbpx

How the Deadly Diamond of Death deadlock explained? Java interview question

(Last Updated On: May 14, 2010)

How the Deadly Diamond of Death deadlock explained? Java interview question
Deadlocks can be pretty common in software development. It does not matter if it is on Linux, Unix, Windows, or Mac OS X. They are all the same on any multi processing platform. There are a number of reasons why deadlocks can happen but it basically comes down to:
Thread 1 locks A, waits for B
Thread 2 locks B, waits for A
Both threads do the above at the exact time. So we could have code like (this does not really matter if it is Java or C++):
(this code sample is in Java)
public class TreeNode {

TreeNode parent = null;
List children = new ArrayList();

public synchronized void addChild(TreeNode child){
if(!this.children.contains(child)) {
this.children.add(child);
child.setParentOnly(this);
}
}
public synchronized void addChildOnly(TreeNode child){
if(!this.children.contains(child){
this.children.add(child);
}
}

public synchronized void setParent(TreeNode parent){
this.parent = parent;
parent.addChildOnly(this);
}

public synchronized void setParentOnly(TreeNode parent){
this.parent = parent;
}
}

So essential what happens in pseudo code, Thread 1 will call parent.addChild(child) (locks the parent) which then calls child.Set|ParentOnly(parent). Thread 2 will call child.setParent(parent) (locks child) by calling parent.addChildOnly().

First thread 1 calls parent.addChild(child). Since addChild() is synchronized thread 1 effectively locks the parent object for access from other treads.
Then thread 2 calls child.setParent(parent). Since setParent() is synchronized thread 2 effectively locks the child object for acces from other threads.
This becomes known as the Deadly Diamond of Death. Both parent and child objects are blocked from each other. Essentially, Thread 1 will try to child.setParentOnly() but the child object is locked by Thread 2. Thread 2 will try call the parent.addChildOnly() but the parent is blocked by thread 1.Both threads are blocked from each other as each await to obtain the lock the other holds.

This can even become more complicated as more threads become involved. This can also happen in databases as well so becareful with this huh?

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

Subscribe For Latest Updates

Sign up to best of business news, informed analysis and opinions on what matters to you.
Invalid email address
We promise not to spam you. You can unsubscribe at any time.

NOTE!

Check NEW site on stock forex and ETF analysis and automation

Scroll to Top