This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
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

Question about sunchronized of thread

 
dragon ji
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the code as follows:
public class SyncTest{
private int x;
private int y;
private synchronized void setX (int i) {x=1;}
private synchronized void setY (int i) {y=1;}
public void setXY(int i)
{
setX(i);
setY(i);
}
public synchronized boolean check()
{ return x !=y; }
}
when the setXY was invoked by multiple threads, can the method check return true?
I think it should never return true,but can't confirm.please help me!
 
Ken Krebs
Ranch Hand
Posts: 451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I assume you meant for the setX and setY methods to set x and y to i not 1, but even if you didn't I think it is possible, though not likely, for check to return true. If you did mean them to set x and y to i it is even more possible.
Suppose threadA creates aSyncTest and then hands a reference to it to threadB. threadA starts threadB and at some later point in time calls setXY(5). setXY(5) calls setX(5), acquires the aSyncTest lock, setX(5) then sets x to 1 and then returns to setXY releasing the lock. At this point in time x == 1 and y == 0. The thread scheduler then comes along and switches the CPU over to threadB which calls check which returns true. If setXY were synchronized this could not happen as threadA would still own the lock on aSyncTest. Holding the lock will not prevent threadA from being switched out but threadB will not be able to acquire the lock and will block.
Happy trails
---So far as the laws of mathematics refer to reality, they are not certain. And so far as they are certain, they do not refer to reality.---
Albert Einstein
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic