0

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?

Alexander Kulyakhtin
  • 47,782
  • 38
  • 107
  • 158
  • can you post a code? – Andrey E Aug 28 '14 at 13:16
  • possible duplicate of [Reorder normal field around volatile field](http://stackoverflow.com/questions/4919392/reorder-normal-field-around-volatile-field) – Joe Aug 28 '14 at 13:25
  • Repetition of http://stackoverflow.com/questions/25548547/can-a-reordering-happen-in-the-presence-of-a-volatile-variable ? – Joe Aug 28 '14 at 13:28

2 Answers2

1

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.

Solomon Slow
  • 25,130
  • 5
  • 37
  • 57
0

As said here

The old memory model allowed for volatile writes to be reordered with nonvolatile reads and writes, which was not consistent with most developers intuitions about volatile and therefore caused confusion.

So such behavior is obsolete for now (since JSR-133 was introduced and took effect in Java 5.0).

And, secondly, as said here

The actions linked together in program order do not preclude being "reordered"

Johnny
  • 1,966
  • 17
  • 24