How do I ensure that after the worker threads have completed processing the stream in the following code, i.e. at point (*)
, the content of the strValues
array is consistent, i.e. that the main thread at (*)
does not see a stale null
value in any of the strValues
array entries?
int N = 50;
String[] strValues = new String[N];
IntStream.range(0, N)
.parallel()
.forEach(i -> strValues[i] = Integer.toString(i));
// (*) Is strValues consistent here?
for (String strValue : strValues) {
System.out.println(strValue);
}
(Of course I could return the Integer.toString(i)
using .map(...)
rather than .forEach(...)
, but that is not what I'm trying to illustrate here, and it's not always an available option, for efficiency reasons or because you have to have workers set or return many different values.)
In practice, I have never seen the equivalent of a strValues
array entry being null
when an array entry is set from one thread then read from another. However, I know that Java's memory model does not guarantee this, hence the existence of AtomicInteger
etc.
But there is no AtomicArray
equivalent in Java. The best you can do is initialize an AtomicReference[]
array with empty AtomicReference
objects, and set them from a worker thread. But this is very inefficient on CPU resources and memory.
There is also no way to reliably flush all the caches of a CPU, either from Java, or potentially at all.
I know that fences exist to prevent memory operation reordering, but I don't think they change memory flushing semantics. Or is memory operation reordering the only issue that causes the Java memory model to require the Atomic*
classes?
My main question: what can be done to set the values in an array from one thread (or a set of worker threads), then try to read them from another thread, without running into stale values? In particular I'm interested to know if an appropriate memory fence or similar is put in place when worker threads reach the end of a stream. (I don't see how that could be done automatically, so I'm guessing it doesn't happen.)