Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Yes, it is guaranteed that thread 2 will print "done" . Of course, that is if the write to <code>b</code> in Thread 1 actually happens before the read from <code>b</code> in Thread 2, rather than happening at the same time, or earlier!</p> <p>The heart of the reasoning here is the <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4.5"><em>happens-before relationship</em></a>. Multithreaded program executions are seen as being made of events. Events can be related by happens-before relationships, which say that one event happens before another. Even if two events are not directly related, if you can trace a chain of happens-before relationships from one event to another, then you can say that one happens before the other.</p> <p>In your case, you have the following events:</p> <ul> <li>Thread 1 writes to <code>s</code></li> <li>Thread 1 writes to <code>b</code></li> <li>Thread 2 reads from <code>b</code></li> <li>Thread 2 reads from <code>s</code></li> </ul> <p>And the following rules come into play:</p> <ul> <li>"If x and y are actions of the same thread and x comes before y in program order, then hb(x, y)." (the <em>program order</em> rule)</li> <li>"A write to a volatile field (§8.3.1.4) happens-before every subsequent read of that field." (the <em>volatile</em> rule)</li> </ul> <p>The following happens-before relationships therefore exist:</p> <ul> <li><em>Thread 1 writes to <code>s</code></em> happens before <em>Thread 1 writes to <code>b</code></em> (program order rule)</li> <li><em>Thread 1 writes to <code>b</code></em> happens before <em>Thread 2 reads from <code>b</code></em> (volatile rule)</li> <li><em>Thread 2 reads from <code>b</code></em> happens before <em>Thread 2 reads from <code>s</code></em> (program order rule)</li> </ul> <p>If you follow that chain, you can see that as a result:</p> <ul> <li><em>Thread 1 writes to <code>s</code></em> happens before <em>Thread 2 reads from <code>s</code></em></li> </ul>
    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. 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