aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question about sunchronized of thread Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question about sunchronized of thread " Watch "Question about sunchronized of thread " New topic
Author

Question about sunchronized of thread

dragon ji
Ranch Hand

Joined: Oct 31, 2002
Posts: 110
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!


scjp 1.4<br />challenge haven't limit!
Ken Krebs
Ranch Hand

Joined: Nov 27, 2002
Posts: 451
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


kktec<br />SCJP, SCWCD, SCJD<br />"What we observe is not nature itself, but nature exposed to our method of questioning." - Werner Heisenberg
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Question about sunchronized of thread