how to synchronize addition from different threads using lock-free code?
<p>I've wrote simple example of <code>NasdaqIndex</code> calculation. For simplicity I declared it as <code>int</code> and this is just sum of prices of <code>10</code> stocks.</p>

<pre><code>class NasdaqIndex {

private int[] stockValue = new int[10]; // for simplicity let's assume they are already initialized

// just sum from 1 to 10 of stockValue
private int nasdaqIndexValue; // for simplicity let's assume that already initialized

public void StockValueUpdated(int stockValueIndex, int newValue) {
    int diff = newValue - stockValue[stockValueIndex];
    stockValue[stockValueIndex] = newValue;
    nasdaqIndexValue += diff;               // THIS NEED TO BE SYNCHRONIZED!
}

}
</code></pre>

<p>But in real life StockValueUpdated may (and will) be called parallel from different threads for different stockValueIndex (it will not be called parallel for the same stockValueIndex).</p>

<p>So I just have to synchronize only one line of code <code>nasdaqIndexValue += diff;</code></p>

<p>For example if one thread executes <code>nasdaqIndexValue += 10;</code> and another thread executed <code>nasdaqIndexValue += 3;</code> I need to be sure that tottally exactly <code>13</code> is added. Do I need synchronization in this case at all? If so how to do that using <code>lock-free</code> code?</p>

<p><strong>UPD</strong> oooops I just realized that using such code I introduce small "delta" to nasdaqIndex every time if I'm using doubles. So I have either use decimal or I have to "recalculate completely" nasdaqIndex sometimes, otherwise it will not be equal to sum of stocks after a while.</p>
