Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>A simple answer is as follows:</p> <ul> <li><p><code>synchronized</code> can always be used to give you a thread-safe / correct solution, </p></li> <li><p><code>volatile</code> will probably be faster, but can only be used to give you a thread-safe / correct in limited situations.</p></li> </ul> <p>If in doubt, use <code>synchronized</code>. Correctness is more important than performance.</p> <p>Characterizing the situations under which <code>volatile</code> can be used safely involves determining whether each update operation can be performed as a single atomic update to a single volatile variable. If the operation involves accessing other (non-final) state or updating more than one shared variable, it cannot be done safely with just volatile. You also need to remember that:</p> <ul> <li>updates to non-volatile <code>long</code> or a <code>double</code> may not be atomic, and </li> <li>Java operators like <code>++</code> and <code>+=</code> are not atomic.</li> </ul> <hr> <p><sub>Terminology: an operation is "atomic" if the operation either happens entirely, or it does not happen at all. The term "indivisible" is a synonym.</sub> </p> <p><sub>When we talk about atomicity, we <em>usually</em> mean atomicity from the perspective of an outside observer; e.g. a different thread to the one that is performing the operation. For instance, <code>++</code> is not atomic from the perspective of another thread, because that thread may be able to observe state of the field being incremented <em>in the middle of the operation</em>. Indeed, if the field is a <code>long</code> or a <code>double</code>, it may even be possible to observe a state that is neither the initial state or the final state!</sub></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.
    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