Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>On a single-CPU machine there is no such thing as <em>"at the same time"</em> - the operating system (OS) schedules each thread to be executed for a short period of time, before moving onto the next thread.</p> <p>On multi-CPU (SMP) machines, two CPUs can be executing code simultaneously, but the <a href="http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#36930" rel="nofollow">Java Language Specification</a> (JLS) provides guarantees about <code>volatile</code> fields so you can still write correct multi-threaded code.</p> <p>From the programmer's point of view, there's no lock involved when dealing with <code>volatile</code> fields. Ignoring the uninteresting case where both threads are reading the field (spoiler: they see the same value) we have two cases:</p> <ol> <li>one thread reads, the other updates: the reader will either see the old or the new value, depending on the order in which the two threads are scheduled by the OS</li> <li>both threads update: the field will end up holding the value of whichever thread was scheduled most recently</li> </ol> <p>It's important to note that:</p> <ul> <li>even if the field is of type <code>long</code>, occupying 8 bytes of memory, the JLS guarantees that, with <code>volatile</code> fields, readers will never see (for example) 4 bytes of the "old" value and 4 bytes of the "new" - it's all-or-nothing</li> <li><strong>all</strong> threads scheduled after the update will see the new value <strong>immediately</strong></li> </ul> <p>Neither of these are necessarily true for non-<code>volatile</code> fields.</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