I've wrote simple example of NasdaqIndex
calculation. For simplicity I declared it as int
and this is just sum of prices of 10
stocks.
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!
}
}
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).
So I just have to synchronize only one line of code nasdaqIndexValue += diff;
For example if one thread executes nasdaqIndexValue += 10;
and another thread executed nasdaqIndexValue += 3;
I need to be sure that tottally exactly 13
is added. Do I need synchronization in this case at all? If so how to do that using lock-free
code?
UPD 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.