Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>They are just totally different. Consider this example of a <code>volatile</code> integer:</p> <pre><code>volatile int i = 0; void incIBy5() { i += 5; } </code></pre> <p>If two threads call the function concurrently, <code>i</code> might be 5 afterwards, since the compiled code will be somewhat similar to this (except you cannot synchronize on <code>int</code>):</p> <pre><code>void incIBy5() { int temp; synchronized(i) { temp = i } synchronized(i) { i = temp + 5 } } </code></pre> <p>If a variable is volatile, every atomic access to it is synchronized, but it is not always obvious what actually qualifies as an atomic access. With an <code>Atomic*</code> object, it is guaranteed that every method is "atomic". </p> <p>Thus, if you use an <code>AtomicInteger</code> and <code>getAndAdd(int delta)</code>, you can be sure that the result will be <code>10</code>. In the same way, if two threads both negate a <code>boolean</code> variable concurrently, with an <code>AtomicBoolean</code> you can be sure it has the original value afterwards, with a <code>volatile boolean</code>, you can't. </p> <p>So whenever you have <em>more than one thread</em> modifying a field, you need to make it atomic or use explicit synchronization.</p> <p>The purpose of <code>volatile</code> is a different one. Consider this example</p> <pre><code>volatile boolean stop = false; void loop() { while (!stop) { ... } } void stop() { stop = true; } </code></pre> <p>If you have a thread running <code>loop()</code> and another thread calling <code>stop()</code>, you might run into an infinite loop if you omit <code>volatile</code>, since the first thread might cache the value of stop. Here, the <code>volatile</code> serves as a hint to the compiler to be a bit more careful with optimizations.</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