Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Not only should <code>variable</code> be <code>volatile</code>, but you also want to protect your <code>update</code> function with <a href="http://download.oracle.com/javase/tutorial/essential/concurrency/sync.html" rel="nofollow noreferrer">some sort of synchronization</a> since <code>++variable</code> is not an atomic call. It is, after all, just syntactic sugar for</p> <pre><code>variable = variable + 1; </code></pre> <p>which is not atomic.</p> <p>You should also wrap any calls that read variable in a <a href="http://download.oracle.com/javase/tutorial/essential/concurrency/newlocks.html" rel="nofollow noreferrer">lock</a> of some sort.</p> <p>Alternatively, use an <a href="http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/atomic/AtomicInteger.html" rel="nofollow noreferrer">AtomicInteger</a>. It was made for this sort of thing (for just integer operations).</p> <pre><code>public class A { // initially had said volatile wouldn't affect this variable because // it is not a primitive, but see correction in comments public final AtomicInteger variable; // see comments on this issue of why final public void update() { // Called by one thread constantly variable.getAndIncrement(); // atomically adds one } public int retrieveValue() { return variable.get(); // gets the current int value safely } } public class B { public A a; public void update() { // Called by another thread constantly int v = a.retrieveValue(); // Do algorithm with v... } } </code></pre> <p>For the more complex algorithms, as your recent edit assumes, use synchronization or locks.</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