I am trying to understand if `MutableStateFlow.val...
# coroutines
a
I am trying to understand if
MutableStateFlow.value
is thread-safe. The documentations does say so (documentation) but I see inconsistencies in the code below
Copy code
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

fun main():Unit = runBlocking {
    val stateFlow = MutableStateFlow<Int>(0)
    GlobalScope.launch {
        for (i in 1..50000) {
            stateFlow.value += 1
            //stateFlow.update { curr -> curr + 1 }
        }
    }
    GlobalScope.launch {
        for (i in 1..50000) {
            stateFlow.value += 1
            //stateFlow.update { curr -> curr + 1 }
        }
    }
    Thread.sleep(6000)
    println(stateFlow.value)
}
The final value is not always 100,000. What am I missing? Can some one please help.
j
Setting the value is thread-safe and reading the value is thread-safe, yes. But reading and setting the value like you did (with
+=
) is not an atomic operation: this operator will first read the value, then write an updated value. What happens in between is anyone's guess. This is what
update
is for.
s
Thread-safe != atomic
I remember a similar question about this in the past: https://kotlinlang.slack.com/archives/C1CFAFJSK/p1660135391669929
Maybe it would be worth updating the docs to clarify the difference between thread-safety and atomic updates?
5