alex
08/26/2021, 6:21 PMephemient
08/26/2021, 6:26 PMCarter
08/26/2021, 6:33 PMalex
08/26/2021, 7:14 PMclass Action {
private var state = ...
suspend fun action() { ... }
}
ephemient
08/26/2021, 7:52 PMaction()
could be invoked by multiple coroutines at once, then you may have an issueCarter
08/26/2021, 8:58 PMvar
so you could be changing both).alex
08/26/2021, 10:13 PMephemient
08/26/2021, 10:15 PMTijl
08/27/2021, 7:51 AMprivate var state = ...
this can always have different values on different threads due to the way modern CPUs work (especially different threads can having different on die caches), regardless of whether you use coroutines or not.
for JVM you can use `@Volatile` to ensure that does not happen. Since you explicitly say you switch to a different thread and are not doing this, CPU cache is a very likely cause.ephemient
08/27/2021, 8:00 AMTijl
08/27/2021, 8:10 AMvar
somewhere.
Kotlin doesn’t even make assumptions about the underlying memory model (in this case JVM) or provide an abstraction to libraries (such as coroutines) to deal with this.
Also it’d be pretty terrible if coroutines made all your writes only to main memory, your program would be an order or magnitude slower just for using coroutines.
I think maybe you mean a var inside a suspend method, which effectively lives on a context under control of coroutines itself, like:
class Action {
suspend fun action() {
private var state = ...
...
}
}
ephemient
08/27/2021, 8:24 AMalex
08/27/2021, 3:33 PMthis can always have different values on different threads due to the way modern CPUs work (especially different threads can having different on die caches), regardless of whether you use coroutines or not.
for JVM you can use `@Volatile` to ensure that does not happen. Since you explicitly say you switch to a different thread and are not doing this, CPU cache is a very likely cause.I've spent few hours refreshing JMM and other topics, and as it seems, there is no need for volatile b.c. coroutines' atomics will put a fence anyway during suspend (it'll flush everything). And because there is no data race (e.g. only a single thread runs an action), there is no need to use atomics either.
elizarov
08/31/2021, 8:22 AM