Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is the memory visibility of variables accessed in static singletons in Java?
    primarykey
    data
    text
    <p>I've seen this type of code a lot in projects, where the application wants a global data holder, so they use a static singleton that any thread can access.</p> <pre><code>public class GlobalData { // Data-related code. This could be anything; I've used a 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; } } </code></pre> <p>I hope it's easy to see what's going on. One can call <code>GlobalData.getInstance().getData()</code> at any time on any thread. If two threads call setData() with different values, even if you can't guarantee which one "wins", I'm not worried about that.</p> <p>But thread-safety isn't my concern here. What I'm worried about is memory visibility. Whenever there's a memory barrier in Java, the cached memory is synched between the corresponding threads. A memory barrier happens when passing through synchronizations, accessing volatile variables, etc.</p> <p>Imagine the following scenario happening in chronological order:</p> <pre><code>// Thread 1 GlobalData d = GlobalData.getInstance(); d.setData("one"); // Thread 2 GlobalData d = GlobalData.getInstance(); d.setData("two"); // Thread 1 String value = d.getData(); </code></pre> <p>Isn't it possible that the last value of <code>value</code> in thread 1 can still be <code>"one"</code>? The reason being, thread 2 never called any synchronized methods after calling <code>d.setData("two")</code> so there was never a memory barrier? Note that the memory-barrier in this case happens every time <code>getInstance()</code> is called because it's synchronized.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload