Does Java guarantee that updates to array elements performed by thread A , before storing an array reference in AtomicReference will always be displayed in thread B that receives this link
In other words, what are the possible outcomes of doing this:
class References { AtomicReference<String[]> refs = new AtomicReference<>(new String[]{"first"}); public void add(String s) { refs.updateAndGet(oldRefs -> { String[] newRefs = new String[oldRefs.length + 1]; System.arraycopy(oldRefs, 0, newRefs, 0, oldRefs.length); newRefs[oldRefs.length] = s; return newRefs; }); } public static void main(String[] args) { References r = new References(); new Thread(() -> r.add("second")).start(); System.out.println(Arrays.toString(r.refs.get())); } }
can only output those that are [first] or [first, second] , or can you also get results such as [first, null] or [null, null] ?
The javadoc for java.util.concurrent.atomic states:
compareAndSet and all other read and update operations, such as getAndIncrement , have memory effects for both reading and writing volatile variables.
which, it seems, does not provide any guarantees for non-volatile array elements, only the array reference itself.
source share