https://kotlinlang.org logo
Title
a

allan.conda

03/16/2022, 9:23 AM
Trying to understand thread safety in coroutines… Will there be threading issues with this piece of 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

gildor

03/16/2022, 10:03 AM
There is a race condition on access mutableList, it’s not thread safe and there is a chance of ArrayIndexOutOfBoundsException or other errors
:kotlin-intensifies: 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

allan.conda

03/16/2022, 10:11 AM
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

Zach Klippenstein (he/him) [MOD]

03/16/2022, 3:09 PM
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.
:thank-you: 1
g

gildor

03/18/2022, 4:04 PM
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