In Java there exists an AtomicReference class. Does this mean that setting a reference is NOT an atomic operation in and of itself?
e.g., is this not thread-safe (assuming that the value returned cannot be modified)?:
public void someMethod()
{
this.someList = Collections.unmodifiableList(new LinkedList<Object>());
}
public List<Object> getReadOnlyList()
{
return someList;
}
How about in C#?
According to the Java Language Specification, version 3.0, Section 17.7:
Writes to and reads of references are always atomic, regardless of whether they are implemented as 32 or 64 bit values.
AtomicReference enables performing a compare and set as an atomic action.
This isn't threadsafe:
public boolean changeList(List<Object> oldValue, List<Object> newValue) {
if (this.someList == oldValue) {
// someList could be changed by another thread after that compare,
// and before this set
this.someList = newValue;
return true;
}
return false;
}
The sometimes overlooked package description for java.util.concurrent.atomic
elaborates on some common uses.
Addendum: Similarly, the package description for java.util.concurrent
conveniently summarizes several essential points detailed in JLS §17.
Also, consider the potential benefit of Final Field Semantics if your List
is meant to be immutable and a reference to it can be made final
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With