Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is addressed in this answer:</p> <blockquote> <p><a href="https://stackoverflow.com/questions/10301061/is-this-a-safe-publication-of-object/10301179#10301179">Is this a safe publication of object?</a></p> </blockquote> <p>To quote:</p> <blockquote> <p>The issue revolves around optimizations and reordering of instructions. When you have two threads that are using a constructed object without synchronization, it may happen that the compiler decides to reorder instructions for efficiency sake and allocate the memory space for an object and store its reference in the item field before it finishes with the constructor and the field initialization. Or it can reorder the memory synchronization so that other threads perceive it that way.</p> </blockquote> <p>If you mark a field as final it forces the compiler to complete initialization for that field before the constructor completes. Non-final fields have no such guarantees.</p> <p>This is part of the <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4" rel="nofollow noreferrer">Java language definition (17.4)</a>. Details about <code>final</code> fields are also in the <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.5" rel="nofollow noreferrer">JLS (17.5)</a>.</p> <p>More specifically, the <code>writer()</code> method constructs an instance of <code>FinalFieldExample</code> and stores in in a <code>static</code> field for other threads to consume. Because of instruction reordering, the <code>y</code> field may not have been initialized yet. If the <em>same thread</em> calls the <code>reader()</code> it will see <code>y</code> as <code>4</code> but other threads could see it as <code>0</code> because <code>f</code> was set and consumed possibly <em>before</em> <code>y</code> gets initialized and published.</p> <p>To make this code correct, you must make <code>f</code> be <code>volatile</code> as well.</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.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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