First class uses synchronized
keyword before setter while in second class , I simply mark String field to be volatile
.
public class MyBean{
private String strValue;
public synchronized void setStrValue(String strValue){
this.strValue=strValue;
}
public String getStrValue(){
return strValue
}
}
and
public class MyBean{
private volatile String strValue;
public void setStrValue(String strValue){
this.strValue=strValue;
}
public String getStrValue(){
return strValue
}
}
Are these two pieces of code equivalent as far as reading updated value is concerned from one thread which was updated by another thread?
e.g. if same instance of MyBean
is passed to two threads - thread - A & thread - B , if target is to have thread - A read updated value after modification is done by thread - B , will both codes be equivalent from that perspective?
Also, in second version ( i.e. when field is marked volatile ) - is it mandatory to place synchronized
before setter if more than one thread can be a writer? Will volatile
have any significance for the case of multiple writers for setter method?
Is my assumption correct that both codes are equivalent if there is only one writer thread?
For the case of multiple writers, will the correct version be to use synchronized
as well as volatile
both ( if don't wish to block readers ) ?