I have a class as follows
public MyClass{
Boolean flag = false;
public Boolean getflag(){
synchronized(flag){
//BLOCK 1
return flag;
}
}
public Boolean setflag(){
synchronized(flag){
//BLOCK 2
this.flag = flag;
}
}
}
Both methods are synchronized on object flag.Now my doubt is can two different threads can simultaniously executed the synchronized blocks (1&2).
Can the following situation arise?
1)Thread 1 is setting flag value and thread 2 getting its value at same time?
Yes it can. Note that you are synchronizing on the same object you are setting. So the setter can change the object reference to something different, then the getter can synchronize on the new object while the setter is still inside the synchronized block.
But there is more:
flagis (usually) a reference to one of the system-wide singletonsBoolean.TRUEandBoolean.FALSE, so it is (at least theoretically) possible to lock on these outside of your class, even without referring to your class in any way. In which case you can end up with a deadlock and you can have a hard time figuring out why.(Note also that the code in its current form is wrong, since the setter has no parameter, thus
this.flag = flagassigns the reference to itself – but above I assume that you meant it to behave like a normal setter 🙂The fix is to use a dedicated,
private finallock object (in case you want to absolutely ensure that noone outside can synchronize on the same lock you are using within your class – which I suppose your original intention was):If you aren’t worried so much about other synchronizing on the same lock you internally use, you can simply make your methods
synchronized(in which case they lock onthis).