Java memory model question
Brian Goetz
brian.goetz at oracle.com
Fri Mar 6 07:46:31 UTC 2020
No, but this is a common myth. Method boundaries are not part of the JMM, and the JIT regularly makes optimizations that have the effect of reordering operations across method boundaries.
Sent from my iPad
> On Mar 6, 2020, at 1:04 AM, Luke Hutchison <luke.hutch at gmail.com> wrote:
>
> 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