Race conditions occur when the result of a computation depends on the order at which expressions and statements are evaluated.
The result may differ if the evaluation of expressions and statements alter state, producing side-effects.
If everything in your code is immutable, there are no alteration of the state, no side-effects while evaluating expressions and statements. Hence the order of evaluation does not effect the final result.
Consider the following code:
Map<String, Integer> map = Collections.singletonMap("key", 0);
public void increment() {
int val = map.get("key);
map.put("key", val + 1);
}
If two threads execute every statement of the method increment()
concurrently, both read the same value 0
and both put the same incremented value 1
into the map
. Hence the result would be 1
.
If both threads (by chance) would execute all statements consecutively one thread would read the value 0
and put the value 1
while the other thread would read the value 1
and put the value 2
.
Now if the map would be immutable and the both thread would execute the following method:
public void logMap() {
System.out.println("Key has value " + map.get("key"));
}
the result would always be the same, because there are no side-effects (besides of the changes made by System.out.println) which effects the computation.