https://kotlinlang.org logo
#android
Title
# android
r

Raj Bopche

11/05/2023, 6:40 AM
Item 78 of Joshua Bloch’s Effective Java say’s Java guarantees that reading or writing a variable is atomic unless the variable is of type long or double. (JLS 17.4, JLS 17.7) Reading a variable other than a long or double is guaranteed to return a value that was stored into that variable by some thread, even if multiple threads modify the variable concurrently & without synchronisation. I wanted to test this out and hence wrote the following kotlin snippet
Copy code
fun 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?
Book SS:
Kotlin Snippet:
a

ascii

11/05/2023, 9:59 AM
This has nothing to do with #android. Perhaps #getting-started would be a better place.
☝️ 2
m

mkrussel

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.