Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AtomicReference in Java - necessary for setting a reference in a thread-safe environment?

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#?

like image 484
Cornelius Avatar asked Mar 05 '10 03:03

Cornelius


2 Answers

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;
}
like image 69
Stephen Denne Avatar answered Sep 28 '22 05:09

Stephen Denne


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.

like image 42
trashgod Avatar answered Sep 28 '22 06:09

trashgod