Hi, guys! Could you help me understand if the `cum...
# coroutines
a
Hi, guys! Could you help me understand if the
cumulativeSum
field should be marked as volatile in this example? I'd suspect that the consumer reading messages from the channel might be resumed on a different thread after being suspended, which could lead to reading stale data of
cumulativeSum
that was previously cached by that thread. However, I haven't been able to confirm this. Is this possible, or am I being paranoid?
Copy code
object ChannelTest {
    private val scope = CoroutineScope(CoroutineName("ChannelTest") + SupervisorJob())
    private val channel = Channel<Int>()

    private var cumulativeSum = 0
    private var N = 1_000_000

    @JvmStatic
    fun main(args: Array<String>) = runBlocking {
        runConsumer()
        delay(50)

        repeat(N) {
            scope.launch {
                channel.send(1)
            }
            if (it % 5000 == 0) {
                delay(250)
            }
        }

        delay(50)
        channel.close()
        delay(50)
    }

    private fun runConsumer() {
        scope.launch {
            for (i in channel) {
                cumulativeSum += i
            }

            println("sum: $cumulativeSum; ${cumulativeSum == N}")
        }
    }
}
j
Don't take my word for it, but I believe the coroutines machinery ensures the happens-before relationships so that you don't have to worry about this (meaning, if the variable is updated from a single coroutine, it should work without
@Volatile
)
a
Yes, this is exactly what I'm trying to understand: if the data is updated solely by the same coroutine, could it still read stale mutable data when the coroutine is moved to a different thread. I’ll try to google about happens-before relationships to get more clarity. Thanks for your thoughts!
d
You can take my word for it: if data is only accessed in one coroutine, happens-before is established between accesses.
thank you color 2
j
I tried to find something official, but at least I found this post which can act as reference 🙂: https://discuss.kotlinlang.org/t/coroutine-actors-and-thread-safety/2356/3
Ah thanks Dima
🙂 1
a
Thank you, guys.
d
For the record, here's an authoritative widely available article: https://proandroiddev.com/what-is-concurrent-access-to-mutable-state-f386e5cb8292
thank you color 1
👍 1
j
@Dmitry Khalanskiy [JB] it would be nice to mention that the single-coroutine case is safe and doesn't require synchronization in this page of the docs: https://kotlinlang.org/docs/shared-mutable-state-and-concurrency.html
d
j
Thanks! ❤️