About Question enthuware.ocpjp.v7.2.1276 :
Posted: Mon Feb 15, 2016 10:07 am
Well, the classic question on deadlock... I recalled reading about it in the KS & BB guide
where they give there a slightly different example for a deadlock, but the principle stays the same,
I thought of sharing it here since nobody wrote nothing about this question as yet....
So this is the sample code they brought on p. 754, so FYI:
where they give there a slightly different example for a deadlock, but the principle stays the same,
I thought of sharing it here since nobody wrote nothing about this question as yet....
So this is the sample code they brought on p. 754, so FYI:
Anyhow they say there out of the flow that:
public class DeadlockRisk{
private static class Resource{
public int value ;
} // End static class Resource
private Resource resourceA = new Resource() ;
private Resource resourceB = new Resource() ;
public int read(){
synchronized(resourceA){// May deadlock here #LINE 8
synchronized(resourceB){
return resourceB.value + resourceA.value ;
}// End synchronized(resourceB)
}// End synchronized(resourceA)
}// End read()
public void write(int a, int b){
synchronized(resourceB){// May deadlock here #LINE 16
synchronized(resourceA){
resourceA.value = a ;
resourceB.value = b ;
}// End synchronized(resourceA)
}// End synchronized(resourceB)
}// End public void write(int a, int b){...........
}// End class
Assume that read() is started by one thread and write() is started by another. If
there are two different threads that may read and write independently, there is a risk
of deadlock at line 8 or 16. The reader thread will have resourceA , the writer
thread will have resourceB , and both will get stuck waiting for the other.
Code like this almost never results in deadlock because the CPU has to switch
from the reader thread to the writer thread at a particular point in the code, and the
chances of deadlock occurring are very small. The application may work fine 99.9
percent of the time.