2

I am doing as follows, there's only 2 threads in my program.

// Thread 1
write a = 0
write a = 1
write volatile b = 1

// Thread 2
read volatile b // this I always do after write volatile b in the 1st thread
read a

I've read on Java Memory Model and from what I understand in thread 2 read a will ALWAYS give me 1.

I would like to know if this my understanding is correct or not.

In particular CAN A REORDERING still HAPPEN so I see a = 0 in the 2nd thread?

Alexander Kulyakhtin
  • 47,782
  • 38
  • 107
  • 158

1 Answers1

2

Your assumptions are mostly correct. However, i would restate it slightly to match what the JMM guarantees.

If Thread 2 reads b and sees value 1, then the subsequent read of a will be 1. Like you said, if Thread 2 always reads b "after" Thread 1 finishes writing it, then Thread 2 will see the value 1 and the read of a will be as you expect.

jtahlborn
  • 52,909
  • 5
  • 76
  • 118
  • I still don't understand why a reordering can not happen in the thread 1. Why a can not be 0? Oh alas, I just don't get it, could you, please, refer me to the JLS spec where it says so? – Alexander Kulyakhtin Aug 28 '14 at 13:14
  • @Alex - the answer to the linked question references the JLS. basically, you can't move any writes to after a volatile write and you can't move any reads to before a volatile read. – jtahlborn Aug 28 '14 at 13:16