Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

help me with synchronized stuff

 
Han Shu
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 371
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 371
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic