public void function(object a, object b){
synchronized(a){
synchronized (b){
a.performAction(b);
b.performAction(a);
}
}
}
Deadlock with 2 Threads? Thanks for the answers!
Four conditions that must hold for a deadlock to be possible: Mutual exclusion: processes require exclusive control of its resources (not sharing). Hold and wait: process may wait for a resource while holding others. irreversible: unable to reset to an earlier state where resources not held.
A deadlock occurs when the first process locks the first resource at the same time as the second process locks the second resource. The deadlock can be resolved by cancelling and restarting the first process.
Sure,
Suppose we have two objects,
Object one = ...;
Object two = ...;
And suppose thread 1 calls:
function(one, two);
While thread 2 calls:
function(two, one);
In thread 1, a == one
and b == two
, but in thread 2, a == two
and b == one
.
So while thread 1 is obtaining a lock on object one, thread 2 can be obtaining the lock on object two. Then when each of the threads tries to take the next step, they will be deadlocked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With