Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>To keep all the variables in sync and to avoid synchronization, you can put the variables inside an immutable object and update it as a whole. When reading the state, keep hold of one such state object as local variable, and you will be guaranteed that nobody else updates it while you are reading it.</p> <p>Here is some sample code (not tested etc.). If the old values are not read in <code>setState</code> or it is accessed only from one thread, then a volatile field would be enough. But in the general case (multiple threads calling setState and the new state depends on the value of the old state), using AtomicReference makes sure that the no updates will be missed.</p> <pre><code>class Foo { private final AtomicReference&lt;State&gt; state = new AtomicReference&lt;State&gt;(new State(0, 0, 0)); private void setState(float x1, float x2, float x3) { State current; State updated; do { current = state.get(); // modify the values float sh1 = current.sh1 + x1; float sh2 = current.sh2 + x2; float sh3 = current.sh3 + x3; updated = new State(sh1, sh2, sh3); } while (!state.compareAndSet(current, updated)); } public void run() { while (true) { State snapshot = state.get(); // then do tons of stuff that uses sh1, sh2, sh3 over and over... } } private class State { public final float sh1, sh2, sh3; State(float sh1, float sh2, float sh3) { this.sh1 = sh1; this.sh2 = sh2; this.sh3 = sh3; } } } </code></pre> <p>Here is sample code for the special case that updating the state does not depend on the old values of the state:</p> <pre><code>class Foo { private volatile State state = new State(0, 0, 0); private void setState(float sh1, float sh2, float sh3) { state = new State(sh1, sh2, sh3); } public void run() { while (true) { State snapshot = state; // then do tons of stuff that uses sh1, sh2, sh3 over and over... } } private class State { public final float sh1, sh2, sh3; State(float sh1, float sh2, float sh3) { this.sh1 = sh1; this.sh2 = sh2; this.sh3 = sh3; } } } </code></pre>
    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. 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