class OrderingTest {
var x = 0
var y = 0
fun test() {
thread {
x = 1
y = 1
}
thread {
val a = y
val b = x
println("$a, $b")
}
}
}
I had this piece of code to explains the compiler re-ordering and race conditions. It had all possible outcomes:
1,0
0,1
0,0
1,1
But now considering this code
class OrderingTest {
var x = 0
@Volatile var y = 0
fun test() {
thread {
x = 1
y = 1
}
thread {
val a = y
val b = x
println("$a, $b")
}
}
}
Can someone explain how does this adding volatile keyword to y makes 1,0 case impossible?