javamemory-barriersinstruction-reordering

Does StoreStore memory barrier in Java forbid the read-write reordering?


Now we have

Load A
StoreStore
Store B

Is it possible that the actual execution order is as follows

StoreStore
Store B
Load A

If it is possible, how to explain a situation which seems to violate the The Java volatile Happens-Before Guarantee.

As far as I know, the volatile semantic is implemented using the following JMM memory barrier addition strategy

insert a StoreStore before volatile variable write operation
insert a StoreLoad after volatile variable write operation
insert a LoadLoad after volatile variable read operation
insert a LoadStore after volatile variable read operation

Now if we have two java threads as follows

thread 1

Load A
StoreStore
Store volatile B

thread 2

Load volatile B
Load C

Accoring to "The Java volatile Happens-Before Guarantee",Load A should happens-before Load C when Load volatile B is after Store volatile B, but if Load A can be reordered to "after Store volatile B",how to guarantee Load A is before Load C?


Solution

  • Technically speaking, the Java language doesn't have memory barriers. Rather the Java Memory Model is specified in terms of happens before relations; see the following for details:

    The terminology you are discussing comes from The JSR-133 Cookbook for Compiler Writers. As the document says it is a guide for people who are writing compilers that implement the Java Memory Model. It is interpreting the implications of the JMM, and is clearly not intended to be an official specification. The JLS is the specification.

    The section in the JSR-133 Cookbook on memory barriers classifies them in terms of the way that they constrain specific sequences of loads and stores. For StoreStore barriers it says:

    The sequence: Store1; StoreStore; Store2 ensures that Store1's data are visible to other processors (i.e., flushed to memory) before the data associated with Store2 and all subsequent store instructions. In general, StoreStore barriers are needed on processors that do not otherwise guarantee strict ordering of flushes from write buffers and/or caches to other processors or main memory.

    As you can see, a StoreStore barrier only constrains the behavior of store operations.

    In your example, you have a load followed by a store. The semantics of a StoreStore barrier says nothing about load operations. Therefore, the reordering that you propose is allowed.