What is the memory visibility of variables accessed in static singletons in Java? -


i've seen type of code lot in projects, application wants global data holder, use static singleton thread can access.

public class globaldata {      // data-related code. anything; i've used simple string.     //     private string somedata;     public string getdata() { return somedata; }     public void setdata(string data) { somedata = data; }      // singleton code     //     private static globaldata instance;     private globaldata() {}     public synchronized globaldata getinstance() {         if (instance == null) instance = new globaldata();        return instance;      } } 

i hope it's easy see what's going on. 1 can call globaldata.getinstance().getdata() @ time on thread. if 2 threads call setdata() different values, if can't guarantee 1 "wins", i'm not worried that.

but thread-safety isn't concern here. i'm worried memory visibility. whenever there's memory barrier in java, cached memory synched between corresponding threads. memory barrier happens when passing through synchronizations, accessing volatile variables, etc.

imagine following scenario happening in chronological order:

// thread 1 globaldata d = globaldata.getinstance(); d.setdata("one");  // thread 2 globaldata d = globaldata.getinstance(); d.setdata("two");  // thread 1 string value = d.getdata(); 

isn't possible last value of value in thread 1 can still "one"? reason being, thread 2 never called synchronized methods after calling d.setdata("two") there never memory barrier? note memory-barrier in case happens every time getinstance() called because it's synchronized.

isn't possible last value of value in thread 1 can still "one"?

yes is. java memory model based on happens before (hb) relationships. in case, have getinstance exit happens-before subsequent getinstance entry, due synchronized keyword.

so if take example (assuming thread interleaving in order):

// thread 1 globaldata d = globaldata.getinstance(); //s1 d.setdata("one");  // thread 2 globaldata d = globaldata.getinstance(); //s2 d.setdata("two");  // thread 1 string value = d.getdata(); 

you have s1 hb s2. if called d.getdata() thread2 after s2, see "one". last read of d not guaranteed see "two".


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -