AtomicReference in Java - Need to set a link in a thread safe environment?

In Java, there is an AtomicReference class. Does this mean that setting the link is NOT the atomic operation itself?

for example, is it thread-safe (assuming the return value cannot be changed) ?:

public void someMethod()
{
   this.someList = Collections.unmodifiableList(new LinkedList<Object>());
}

public List<Object> getReadOnlyList()
{
   return someList;
}

How about in C #?

+5
source share
5 answers

According to Java Language Specification, Version 3.0, Section 17.7 :

Writes and reading links is always atomic, regardless of whether they are implemented as 32 or 64 bits.

AtomicReference allows you to perform a comparison and set as an atomic action.

This is not thread safe:

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;
}
+3
source

java.util.concurrent.atomic .

: , java.util.concurrent , JLS §17.

, Final Field Semantics, List , final.

+3

, ?

, . .

, () , , - . , , . ( @Tom, , .)

, , . , :

  • volatile
  • / .

, "AtomicXxx", , , , , " ".

, . , ..

+3

AtomicReference volatile, , , , , , .

. volatile AtomicReference ( set/get) -, , .

+1

#, . - Atomic 5.5 #.

"Read and write the following data types: atomic: bool, char, byte, sbyte, short, ushort, uint, int, float and reference. In addition, it reads and writes enumeration types with the base type in the previous list is also atomic. Reading and writing of other types, including long, oolong, double and decimal, as well as user types, is not guaranteed to be atomic. In addition to library functions designed for this purpose, there is no guarantee of atomic read-modify-write, for example, in case of increment or decrement. "

+1
source

All Articles