aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes help me with synchronized stuff Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "help me with synchronized stuff" Watch "help me with synchronized stuff" New topic
Author

help me with synchronized stuff

Han Shu
Greenhorn

Joined: Sep 03, 2001
Posts: 9
Given:

public class SyncTest{
private int x;
private int y;
private synchronized setX (int i) {x=i;}
private synchronized setY (int i ){ y=i;}
public void setXY (int i ) {setX(i);setY(i);}
public synchronized boolean check() { return x!= y;}
}
Under which conditions 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 seperately.
d. check() can only return true if SynchTest is changed to allow x and y to be set seperately.
Which is the answer? I am always confused by synchronized stuff. Please help to explain the condition in this question. Thank so much.
Cameron Park
Ranch Hand

Joined: Apr 06, 2001
Posts: 371
The question really has nothing to do with synchonized methods. The only possible way for check() to return true is when x!=y, and that can happen only when x and y are set SEPARATELY.
So, the answer to your question is C.
Han Shu
Greenhorn

Joined: Sep 03, 2001
Posts: 9
Sorry, but I still cannot figure it out.
Is there any possibility like this: after one thread just finishes setX(), it will release the monitor, and meanwhile the other thread can get the monitor and grasp CPU in turn, which runs check() at once, then it seems that x and y are not equal at that time.
Thank you for helping me!
Cameron Park
Ranch Hand

Joined: Apr 06, 2001
Posts: 371
If you call setX() and setY() in identical manners in 2 separate Threads, yes, it is possible when check() is called, catching the two Threads in a non-equivalent progress, and x !=y.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: help me with synchronized stuff