Lloyd95
Lloyd95

Reputation: 73

How immutable objects help to prevent race conditions

Below is an answer on how to prevent race conditions. What is a race condition?

The best thing would be to create side-effect free and stateless functions, use immutables as much as possible. But that is not always possible. So using java.util.concurrent.atomic, concurrent data structures, proper synchronisation, and actor based concurrency will help.

This answer says use immutables as much as possible. I'm confused on how immutable objects prevent race conditions.

Upvotes: 0

Views: 1352

Answers (3)

Harmlezz
Harmlezz

Reputation: 8068

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.

Upvotes: 1

David Conrad
David Conrad

Reputation: 16359

A data race occurs when "two or more threads ... access the same memory location concurrently, and at least one of the accesses is for writing, and the threads are not using any exclusive locks to control their accesses to that memory."

There can be no data race if the data is immutable, since there could be no write access.

Additionally, the Java Memory Model guarantees:

once an object is constructed, the values assigned to the final fields in the constructor will be visible to all other threads without synchronization.

Upvotes: 0

TheLostMind
TheLostMind

Reputation: 36304

Race conditions can occur only when at least one thread is allowed to write / change state of instances. Immutable instances are readonly, their state cannot be changed, hence all threads only read the state of an object and see the same value(s)

Upvotes: 3

Related Questions