OCP Java SE 6 Programmer practice exam --> practice exam 4 --> Question No 28
I can't understand the answer F.
suppose if g.adjust(g2) runs first then it acquire the lock on g object , and g2.view(g) acquire the lock on g2 object , so in both method acquire lock on different object, and when g comes prints the values and then call the view method with reference to g2(which is y on it). as view method acquire lock on g2 object , that will run no matter.
You are right that when g.adjust(g2) runs then the lock is acquired on the g object. But within the adjust method when y.view(y) is called g2 gets locked.
Similarly, when g2.view(g) is called it tries to acquire the lock on g2 and the view method will try to lock g object.
So, it is possible that g waits to invoke view (as it needs lock on g2 and g2 is already locked by g2.view(g)) and g2 waits for invoking adjust (as it needs lock on g to invoke adjust method).
Replace adjust and view methods with the implementation code, g.adjust(g2) will be executed like this:
g2.view(g) will be executed like this:
In KB book, method1 acquires a and method 2 acquires b. Method 1 waits for b and method2 waits for a. If method2 does not release b, method 1 will wait for b forever.If method1 does not release a, method 2 will wait for a forever.