Posted By:
Robert_Lybarger
Posted On:
Wednesday, August 1, 2007 09:24 AM
The inability to access a 'synchronized' (locked) object is what tends to cause the deadlock. If you're just looking for a mental example, consider two objects objA and objB, and a common resource objC. Now, objC has a pair of methods that are synchronized on one variable while needing to refer to the other variable:
Object valA, valB;
...
public void methodA() {
synchronized(valA) {
//modify valA
//...time passes...
//modify valB
}
}
public void methodB() {
synchronized(valB) {
//modify valB
//...time passes...
//modify valA
}
}
This is rather highly contrived -- I'm making it up for sake of simple example. Now then, if objA runs in one thread and calls objC.methodA() while at nearly the same time objB runs in another thread and calls objC.methodB(), then both will be waiting for each other to exit the sync block so that they can complete and exit their own sync block. Neither will succeed... though it depends a bit on the timing of when the threads hit the methods, and how long it takes to complete said methods.