java - stale reference to atomicintegerarray possible?

251 Views Asked by At

What happens when I assign a new instance of AtomicIntegerArray to a variable in a multithreaded environment?

AtomicIntegerArray array = new AtomicIntegerArray(...);
do some stuff
array = new AtomicIntegerArray(...);

Might some threads still access the stale reference to the old instance after the new assignment? If so, would I need to declare the atomic array as volatile as well?

2

There are 2 best solutions below

2
jtahlborn On BEST ANSWER

if array is visible to other threads (e.g. a class member variable) then yes, it would need to be volatile as well.

0
parsifal On

Your array variable appears to be a local variable, which by definition cannot be accessed by multiple threads.

However, if it's really an instance variable, then yes, other threads can see stale values, just like they can with any other instance variable. What an instance variable references does not affect how that instance variable is accessed.