Do I need to declare AtomicReference as mutable?

The same for all other atomic objects? It is easier to explain the question for AtomicInteger. Since more than 1 thread accesses a reference to myInt, is it possible that one thread sees the registered cached value, for example null, for this object, if it is also not declared mutable? If not?

+5
source share
2 answers

Not only is this not necessary, it is actually semantically incorrect. AtomicReferencecontains a “real” link within itself and controls access to it using its own synchronization constructs. Native JVM synchronization constructs ( synchronized, volatileetc.) And are not used. The object AtomicReferenceitself should not be considered volatile. If anything, think about it final.

Also consider this question - volatileit can be considered an alternative to use AtomicReferenceif you only need get and set operations.

+9
source

"" , , . , - , volatile.

volatile AtomicInteger counter = // initialize counter

int harvest(){
    AtomicInteger old = counter;
    counter = new AtomicInteger();
    return old.get();
}

volatile , . , AtomicInteger, , undefined.

, ? . , , , ( , ). .

+2

All Articles