About Question enthuware.ocpjp.v7.2.1276 :

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
Posts: 42
Joined: Mon Jan 20, 2014 2:26 pm

About Question enthuware.ocpjp.v7.2.1276 :

Post by Nisim123 »

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:

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


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


resourceA.value = a ;
resourceB.value = b ;

}// End synchronized(resourceA)

}// End synchronized(resourceB)

}// End public void write(int a, int b){...........

}// End class
Anyhow they say there out of the flow that:
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.

Posts: 1
Joined: Sat Oct 24, 2015 4:33 am

Re: About Question enthuware.ocpjp.v7.2.1276 :

Post by flee98 »

I thought the static members are sharing the same class lock, so there is no deadlock in this case.

Post Reply

Who is online

Users browsing this forum: No registered users and 4 guests