I have a reader and writer thread in java and below is the code snippet.
int volatile ready = false;
int var1;
int var2;
int var3;
T1:
while(!ready);
print var1;
print var2;
print var3;
T2:
var1 = 1;
var2 = 2;
var3 = 3;
ready = true;
Is it possible that var1, var2 and var3 are allocated in a register in T2. In C++, this is prevented by marking var1, var2 and var3 as volatile. But in Java, do these variable need to be marked as volatile too?
If you only care about whether their values will become visible to T1, no, they don't need to be
volatile
.Due to
ready
beingvolatile
, JSR 133 guarantees a happens-before relationship between T2's writes and T1's reads.See the detailed explanation in the FAQ: https://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#volatile