Question: Should variable in coroutine body be synchronized with AtomicReference or Channel if only one inner coroutine changes it?
See original GitHub issueHaving simple variable in coroutine block and only one producer coroutine changes the state of the variable and another coroutine consumes it, should this variable be synchronized somehow with AtomicReference or Channel to be visible in reader coroutine or reader coroutine automatically fetches new data from the memory?
fun main() = runBlocking<Unit>(Dispatchers.Default) {
var state: State? = null
launch {
data0Flow.collect { newState ->
state = newState
}
}
launch {
data1Flow.collect { someData ->
// Will the state be visible immediately when first coroutine updated it ?
if (state != null) {
// do something
}
}
}
}
Issue Analytics
- State:
- Created 4 years ago
- Comments:7 (4 by maintainers)
Top Results From Across the Web
Shared mutable state and concurrency - Kotlin
The main problem being synchronization of access to shared mutable state. Some solutions to this problem in the land of coroutines are ...
Read more >Coroutines answer to the problem with the mutable state
This solution works, but there are a few problems. The biggest one is, that inside synchronized block you cannot use suspending functions. The...
Read more >Suspending function can only be called within coroutine body
A Firestore snapshot listener is effectively an asynchronous callback that runs on another thread that has nothing to do with the coroutine ......
Read more >Shared mutable state with Coroutines | by Nazar Ivanchuk
CoroutineContext represents common pool of shared threads. Body is a suspend function which will be called inside the coroutine.
Read more >C++ coroutines: Initial implementation pushed to master
C++ coroutines, defined by C++20 standard is nothing but a syntax ... uses of this object should you decide to change the nested...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Yes, absolutely.
Local variables are not thread safe.
Yes, on JVM you can get worse than you expect (see JVM Memory Model).
Yes, this is my experience.