Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In this case you need to use <em>safe publication idioms</em> when making your object available to other threads, namely (from <a href="http://jcip.net/" rel="noreferrer">Java Concurrency in Practice</a>):</p> <blockquote> <ul> <li>Initializing an object reference from a static initializer;</li> <li>Storing a reference to it into a volatile field or AtomicReference;</li> <li>Storing a reference to it into a final field of a properly constructed object; or</li> <li>Storing a reference to it into a field that is properly guarded by a lock.</li> </ul> </blockquote> <p>If you use safe publication, you don't need to declare fields <code>volatile</code>. </p> <p>However, if you don't use it, <strong>declaring fields <code>volatile</code> (theoretically) won't help</strong>, because memory barriers incurred by <code>volatile</code> are one-side: volatile write can be reordered with non-volatile actions after it.</p> <p>So, <code>volatile</code> ensures correctness in the following case:</p> <pre><code>class Foo { public int x; } volatile Foo foo; // Thread 1 Foo f = new Foo(); f.x = 42; foo = f; // Safe publication via volatile reference // Thread 2 if (foo != null) System.out.println(foo.x); // Guaranteed to see 42 </code></pre> <p>but don't work in this case:</p> <pre><code>class Foo { public volatile int x; } Foo foo; // Thread 1 Foo f = new Foo(); // Volatile doesn't prevent reordering of the following actions!!! f.x = 42; foo = f; // Thread 2 if (foo != null) System.out.println(foo.x); // NOT guaranteed to see 42, // since f.x = 42 can happen after foo = f </code></pre> <p>From the theoretical point of view, in the first sample there is a transitive happens-before relationship </p> <pre><code>f.x = 42 happens before foo = f happens before read of foo.x </code></pre> <p>In the second example <code>f.x = 42</code> and read of <code>foo.x</code> are not linked by happens-before relationship, therefore they can be executed in any order.</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