Trying to understand thread safety in coroutines… ...
# coroutines
a
Trying to understand thread safety in coroutines… Will there be threading issues with this piece of code:
Copy code
coroutineScope {
    var count = 0
    val mutableList = mutableListOf<Int>()
    launch {
        while(isActive) {
            mutableList.add(count++)
            delay(1000)
        }
    }
    launch {
        while(isActive) {
            delay(10000)
            mutableList.take(10).also(mutableList::removeAll)
        }
    }
}
g
There is a race condition on access mutableList, it’s not thread safe and there is a chance of ArrayIndexOutOfBoundsException or other errors
K 1
on practice it may have no problems, if this scope has only one thread and both launched coroutines run on it, but it’s too brittle to rely on this
so you should use the same global mutable state syncronoization techniques as with threads (thread-safe list implementations, locks, mutexes etc)
a
I see. I’m trying to have a batched flow actually but want to understand instead of copy pasting the gist here https://github.com/Kotlin/kotlinx.coroutines/issues/1290#issuecomment-776239880 Won’t this be the same problem with channels? Perhaps it has thread-safety code for
poll()
and
send()
(
poll
is deprecated though)
z
I'm not sure which comment you linked to (mobile app doesn't handle the link great) so not sure which code you're referring to, but channels are definitely thread safe - cross-thread communication is one of their main purposes.
🙏 1
g
Additionally to Zach's message, Flow also can be used for safe cross-thread communication, it has more predictable and safe API, but it's not direct replacement in terms of how you use it