Reputation: 1
I am trying to understand how deadlocks works. I know that deadlock is when 2 or more threads are blocked forever, and they are waiting for each other to exit from the block state, but it never happens. I have the following code and i want to modify it to make it safe from deadlock. Can someone tell me how to do it and explain it to me to understand it?
public class CList extends Thread {
private int item;
private Clist next;
private int updateCount=0;
public synchronized void replace(int old, int neww, Clist startedAt) {
if(item==old) {
item=neww;
updateCount++;
}
if(next!=startedAt)
next.replace(old, neww, startedAt);
}
public void run() {
for(int i=0; i<100; i++)
replace(i, i-1, this);
}
public Clist(int item, Clist next) {
this.item=item;
this.next=next;
}
public static void main(String args[]) {
Clist clist3 = new Clist(60, null);
Clist clist2 = new Clist(40, clist3);
Clist clist1 = new Clist(20, clist2);
clist3.next = clist1;
clist1.start();
clist2.start();
clist3.start();
}
}
Upvotes: 0
Views: 69
Reputation: 298539
This depends on the intended logic.
For a consistent update on a single object, there is no need to hold a lock for a different object, so the deadlock can be prevented by not holding the lock when invoking next.replace(…)
:
public void replace(int old, int neww, Clist startedAt) {
synchronized(this) {
if(item==old) {
item=neww;
updateCount++;
}
}
if(next!=startedAt)
next.replace(old, neww, startedAt);
}
On a higher level, the application may require holding the lock of a different object, to ensure that the updates to multiple objects happen in a certain way. E.g. in your example code where three threads do entirely redundant work, the actual purpose seems to be, to produce a deadlock, so there is no way to eliminate the deadlock and retain the original purpose.
Upvotes: 1