quote

riginally posted by Chandrakanth Dn:
---------------------------------------------------------------------------
Given:
1. public class SyncTest {
2. private int x;
3. private int y;
4. private synchronized void setX( int i ) { x = i; }
5. private synchronized void setY( int i ) { y = i; }
6. public void setXY( int i ) { setX(i); setY(i); }
7. public synchronized boolean check() { return x != y; }
8. }
Under which condition will check return true when called from a different class?
A. check can never return true.
B. check can return true when setXY is called by multiple threads.
C. check can return true when multiple threads call setX and setY separately.
D. check can return true only if SyncTest is changed to allow x and y to be set
separately.
What is the Answer?
-------------------------------------------------------------------------
Hi,
I understand that the answer will be (C). Please correct me if I am wrong.
SetX, SetY and check are all synchronized methods. A lock by 1 thread on any one of these methods will imply an implicit lock on the other 2 remaining synchronized methods.
For option (B) B. check can return true when setXY is called by multiple threads.
Any thread that comes to execute setXY will have to accquire a lock on SetX method and that will place an implicit lock on the SetY too. So, using SetXY, no 2 threads can simultaneouly access SetX and SetY. So, in effect, SetXY can be called only in sequence by the threads. And as SetXY sets the value of both x and y as same, so the correct will always return false for B.
For Option (C)
C. check can return true when multiple threads call setX and setY separately.
If 1 thread changes the value of just x, by calling setX and releases the lock after that, then any next thread can access SetY and change the value of Y to a different value. Hence (C) can return false for correct.
Please correct me if I am wrong. Hope this helps.
cheers,
Rajat Gupta