Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>What are you trying to do? The <code>synchronized</code> and <code>volatile</code> keywords are mechanisms in Java which can be used to ensure that consistent values are observed by different threads reading the same data. In particular they allow you to reason about <em>happens-before</em> relations in your programs.</p> <p>You simply cannot avoid using one of <code>volatile</code> or <code>synchronized</code> in order to properly access non-<code>final</code> fields in a multi-threaded program. That said, the main reason that you are likely to require <code>synchronized</code> over <code>volatile</code> is the requirement for using atomic <em>compare and set</em> operations (i.e. <strong>it will not be any performance consideration</strong>). For example, in a multi-threaded program:</p> <pre><code>volatile int i = 0; public void foo() { if (i == 0) i = i + 1; } </code></pre> <p>The above code is inherently unsafe, even though the variable's declaration as being volatile means that reads and writes are flushed to main memory - the only safe implementation of such a method would be something like:</p> <pre><code>int i = 0; public synchronized void foo() { if (i == 0) i = i + 1; } </code></pre> <p>So which should you prefer? Well, if you have multiple threads modifying a field dependent on that field's value (i.e. compare-and set), then <code>synchronized</code> is the only safe solution.</p> <p>It's also worth saying: <strong>the performance overhead of <code>synchronized</code> is not a problem</strong> (in the overwhelming majority of cases). Synchronization-performance issues are usually due to unnecessary code bottlenecks, deadlocks or livelocks and can be mitigated if necessary. Any <em>pure clock-cycles</em> overhead will be dwarfed by other things you application does: file IO, database queries, remoting etc.</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