Note that there are some explanatory texts on larger screens.

plurals
  1. POHappens-before relationships with volatile fields and synchronized blocks in Java - and their impact on non-volatile variables?
    text
    copied!<p>I am still pretty new to the concept of threading, and try to understand more about it. Recently, I came across a blog post on <a href="http://jeremymanson.blogspot.co.uk/2008/11/what-volatile-means-in-java.html" rel="noreferrer">What Volatile Means in Java</a> by Jeremy Manson, where he writes: </p> <blockquote> <p>When one thread writes to a volatile variable, and another thread sees that write, the first thread is telling the second about <strong>all</strong> of the contents of memory up until it performed the write to that volatile variable. [...] <strong>all</strong> of the memory contents seen by Thread 1, before it wrote to <code>[volatile] ready</code>, must be visible to Thread 2, after it reads the value <code>true</code> for <code>ready</code>. [emphasis added by myself]</p> </blockquote> <p>Now, does that mean that all variables (volatile or not) held in Thread 1's memory at the time of the write to the volatile variable will become visible to Thread 2 after it reads that volatile variable? If so, <strong><em>is it possible to puzzle that statement together from the official Java documentation/Oracle sources? And from which version of Java onwards will this work?</em></strong></p> <p>In particular, if all Threads share the following class variables:</p> <pre><code>private String s = "running"; private volatile boolean b = false; </code></pre> <p>And Thread 1 executes the following first:</p> <pre><code>s = "done"; b = true; </code></pre> <p>And Thread 2 then executes afterwards (after Thread 1 wrote to the volatile field):</p> <pre><code>boolean flag = b; //read from volatile System.out.println(s); </code></pre> <p>Would this be guaranteed to print "done"?</p> <p><strong><em>What would happen if instead of declaring <code>b</code> as <code>volatile</code> I put the write and read into a <code>synchronized</code> block?</em></strong></p> <p>Additionally, in a discussion entitled "<a href="https://stackoverflow.com/questions/4934913/are-static-variables-shared-between-threads">Are static variables shared between threads?</a>", @TREE <a href="https://stackoverflow.com/questions/4934913/are-static-variables-shared-between-threads#comment5502155_4934966">writes</a>:</p> <blockquote> <p>Don't use volatile to protect more than one piece of shared state.</p> </blockquote> <p><strong><em>Why?</em></strong> (Sorry; I can't comment yet on other questions, or I would have asked there...)</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