Note that there are some explanatory texts on larger screens.

plurals
  1. POJava: Caching of non-volatile variables by different threads
    text
    copied!<p>The situation is the following:</p> <ol> <li>I have an object with lots of setters and getters.</li> <li>Instance of this object is created in a one particular thread where all values are set. Initially I create an "empty" object using new statement and only then I call some setters methods based on some complicated legacy logic.</li> <li>Only then this object became available to all other threads that use only getters.</li> </ol> <p><strong>The question:</strong> Do I have to make all variables of this class volatile or not?</p> <p>Concerns:</p> <ul> <li>Creation of a new instance of the object and setting all its values is separated in time. </li> <li>But all other threads have no idea about this new instance until all values are set. So other threads shall not have a cache of not fully initialized object. Isn't it?</li> </ul> <p><em>Note:</em> I am aware about builder pattern, but I cannot apply it there for several other reasons :(</p> <p><strong>EDITED:</strong> As I feel two answers from Mathias and axtavt do not match very well, I would like to add an example:</p> <p>Let's say we have a <code>foo</code> class:</p> <pre><code>class Foo { public int x=0; } </code></pre> <p>and two threads are using it as described above:</p> <pre><code> // Thread 1 init the value: Foo f = new Foo(); f.x = 5; values.add(f); // Publication via thread-safe collection like Vector or Collections.synchronizedList(new ArrayList(...)) or ConcurrentHashMap?. // Thread 2 if (values.size()&gt;0){ System.out.println(values.get(0).x); // always 5 ? } </code></pre> <p>As I understood Mathias, it can print out 0 on some JVM according to JLS. As I understood axtavt it will always print 5.</p> <p>What is your opinion?</p> <p>-- Regards, Dmitriy</p>
 

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