Raj Bopche
11/05/2023, 6:40 AMfun main() {
var state = 0
val t1 = thread {
repeat(10_000_000) {
++state
}
}
val t2 = thread {
repeat(10_000_000) {
++state
}
}
t1.join()
t2.join()
println(state)
}
I tried running it multiple times, but the output never matched 20,000,000, it was always less like 19549352, 19437846, etc.
Why the Kotlin code does not abide by Item 78, am I interpreting it incorrectly?ascii
11/05/2023, 9:59 AMmkrussel
11/06/2023, 3:58 PM++
is not a simple read or write, but instead a read, modify, and then write. That will not be atomic.
What that section of the book is saying is that if one thread assigns 10 and then 100 to state, another thread can only see 10 or 100 and never some other number.
The issue with longs and doubles are related to the number of bytes. Java does not guarantee that writing and reading all 8 bytes of a long and double will be atomic. So if a read happens while writing, the read may see the first four bytes from the write, but the last four bytes from some previous write. That will create a number that does not match either write.