A race condition occurs only if two threads access the same resource at the same time, and one or more threads write to this resource. If multiple threads read the same resource, a race condition will not occur.
We can be sure that objects shared between threads are thread-safe by making the shared object immutable and not updated by any thread. Here is an example:
public class ImmutableValue{ private int value = 0; public ImmutableValue(int value){ this.value = value; } public int getValue(){ return this.value; } }
Note how the value for the ImmutableValue instance is passed to this constructor. Also note that there is no set method here. Once this instance is created, you cannot change its value. It is immutable. However you can use the get method to read it.
If you need to perform an operation on this instance, you can return a new instance with the value from the operation result. Here's an example too:
public class ImmutableValue{ private int value = 0; public ImmutableValue(int value){ this.value = value; } public int getValue(){ return this.value; } <strong>public ImmutableValue add(int valueToAdd){ return new ImmutableValue(this.value + valueToAdd); }</strong> }
Note that the add method returns a new instance with the result of the add operation, rather than adding the value to itself .
This reference is not thread-safe
It is important to remember this, even if an object is immutable, and thus thread-safe, references to this object may not be thread-safe. Look at this example:
public class Calculator{ private ImmutableValue currentValue = null; public ImmutableValue getValue(){ return currentValue; } public void setValue(ImmutableValue newValue){ this.currentValue = newValue; } public void add(int newValue){ this.currentValue = this.currentValue.add(newValue); } }
This Calculator class holds a reference to the above object. Note that it may change that reference through the setValue method and the add method. Therefore, even if this class uses an immutable object internally, it itself is not immutable and therefore not thread-safe. In other words: this ImmutableValue class is thread-safe, but its usage is not. This is something to keep in mind when trying to achieve thread safety through immutability.
In order to make the Calculator class thread-safe, you should use the synchronized keyword on the getValue(), setValue(), and add() methods. That will do the trick.
The above is the content of java thread safety and immutability. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!