0

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 ) ?

Sabir Khan
  • 9,826
  • 7
  • 45
  • 98
  • 1
    Can you share example code that uses the bean? – Mick Mnemonic Sep 14 '17 at 09:54
  • Possible duplicate of [When to use volatile vs synchronization in multithreading in java?](https://stackoverflow.com/questions/8698285/when-to-use-volatile-vs-synchronization-in-multithreading-in-java) –  Sep 14 '17 at 09:57
  • @MickMnemonic: am still in design phase and no codes are ready yet so asked the question to clarify my doubts. Writers will be setting different values on different conditions & times , including `EOF` value when a writer would stop reading. – Sabir Khan Sep 14 '17 at 09:57
  • @Paul- Thanks , I will go through that. – Sabir Khan Sep 14 '17 at 09:58
  • 1
    http://www.javaperformancetuning.com/news/qotm051.shtml Found this link and this https://stackoverflow.com/a/8698401/2931410 for your reference – Karthik R Sep 14 '17 at 10:00
  • 1
    The version using `synchronized` is not thread safe as the getter also needs to be synchronized. (see Effective Java item 66) – bowmore Sep 14 '17 at 10:28

0 Answers0