java - Is synchronization needed while reading if no contention could occur -


consider code sniper below:

package sync;  public class lockquestion {     private string mutable;      public synchronized void setmutable(string mutable) {         this.mutable = mutable;     }      public string getmutable() {         return mutable;     }    } 

at time time1 thread thread1 update ‘mutable’ variable. synchronization needed in setter in order flush memory local cache main memory. @ time time2 ( time2 > time1, no thread contention) thread thread2 read value of mutable.

question – need put synchronized before getter? looks won’t cause issues - memory should date , thread2’s local cache memory should invalidated&updated thread1, i’m not sure.

rather wonder, why not use atomic references in java.util.concurrent?

(and it's worth, reading of happens-before not guarantee thread2 see changes mutable unless uses synchronized ... headache part of jls, use atomic references)


Comments

Popular posts from this blog

Add email recipient to all new Trac tickets -

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -