• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Question about sunchronized of thread

 
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!
 
Ranch Hand
Posts: 451
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic