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: flag
is (usually) a reference to one of the system-wide singletons Boolean.TRUE
and Boolean.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 = flag
assigns 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 final
lock 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):
public MyClass{
private final Object lock = new Object();
private Boolean flag = false;
public Boolean getflag(){
synchronized(lock){
//BLOCK 1
return flag;
}
}
public void setflag(Boolean flag){
synchronized(lock){
//BLOCK 2
this.flag = flag;
}
}
}
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 on this
).