Java memory model question

Luke Hutchison luke.hutch at gmail.com
Fri Mar 6 01:03:35 UTC 2020


Under the Java memory model, is it fair to assume that memory reads and
writes can only be reorderered within a method, but not across method
boundaries? (Define "method" here as what's left after any inlining has
taken place.)

Specifically I'm wondering: if a thread X launches a parallel stream that
writes at most once to each independent element of an array, can it be
assumed that when the stream processing ends, X will always read the value
of all written array elements? In other words, can the termination of the
stream be seen as a memory ordering barrier (in a weak sense)?

I'm not asking whether the following code is advisable, only whether
there's any chance of the main thread reading an old value from the array.

    int N = 50;
    String[] strValues = new String[N];
    IntStream.range(0, N)
            .parallel()
            .forEach(i -> strValues[i] = Integer.toString(i));
    // (*) Are the new strValues[i] all guaranteed to be visible here?
    for (String strValue : strValues) {
        System.out.println(strValue);
    }


More information about the jdk-dev mailing list