Search code examples
javamultithreadingvolatilejls

Is 'program order' in Java allows reordering?


In one thread I have

write a = 0
write a = 1
write volatile flag = 1

In 2nd thread I have

read volatile flag // This always happens after I write volatile flag in thread 1
read a

Can a reordering happen so I see read a returning 0 in the 2nd thread?

If not, could someone, please, explain in detail why?

I'm asking becuase I'm puzzled by this definition from the JLS:

Among all the inter-thread actions performed by each thread t, the program order of t is a total order that reflects the order in which these actions would be performed according to the intra-thread semantics of t.

It looks as if allows for reordering in this situation?


Solution

  • Can a reordering happen so I see read a returning 0 in the 2nd thread?

    No, not if your assertion is correct, "This always happens after I write volatile flag in thread 1"

    The last update that thread 1 made to the variable a before it updated the volatile flag will be visible to thread 2 after thread 2 has read the volatile flag.

    See section 3.1.4 of Java Concurrency in Practice by Brian Goetz for a more detailed explanation: http://www.amazon.com/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601


    But note! It can be considered to be bad practice to depend on reads and writes of a volatile variable to synchronize other variables. The problem is, the relationship between the volatile variable and the other variables may not be obvious to other programmers who work on the same code.