Java memory model question

David Holmes david.holmes at oracle.com
Fri Mar 6 02:09:36 UTC 2020


Hi Luke,

Probably a question better asked on concurrency-interest at cs.oswego.edu

On 6/03/2020 11:03 am, Luke Hutchison 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.)

No. Theoretically you could inline the entire program into a single 
"method". Method entry/exit don't in themselves define synchronization 
points.

> 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 would have expected this to be explicitly stated somewhere in the 
streams documentation, but I don't see it. My expectation is that 
terminal operations would act as synchronization points.

> 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);
>      }

I would expect that code to be fine. parallel() would not be usable 
otherwise.

Cheers,
David


More information about the jdk-dev mailing list