Arthur Krukowski
10/15/2024, 3:29 PMcumulativeSum
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?
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}")
}
}
}
Joffrey
10/15/2024, 3:30 PM@Volatile
)Arthur Krukowski
10/15/2024, 3:43 PMDmitry Khalanskiy [JB]
10/15/2024, 3:47 PMJoffrey
10/15/2024, 3:47 PMJoffrey
10/15/2024, 3:47 PMArthur Krukowski
10/15/2024, 3:48 PMDmitry Khalanskiy [JB]
10/16/2024, 9:05 AMJoffrey
10/16/2024, 9:10 AMDmitry Khalanskiy [JB]
10/16/2024, 9:13 AMJoffrey
10/16/2024, 2:24 PM