https://kotlinlang.org logo
#coroutines
Title
# coroutines
m

Manuel Pérez Alcolea

08/11/2020, 3:44 AM
I've used coroutine frameworks in a few languages but they worked exclusively in a single thread. I noticed a dispatcher can have a pool of many threads (instead of a single one) - that makes me think that "regular" synchronization from my part is required (if there's a race condition) which feels unusual to me (being single threaded, you only need to worry about race conditions only if a function is suspended somewhere.) Not really technical question: how often do you use these "multi-threaded" dispatchers? Is it common?
o

octylFractal

08/11/2020, 4:10 AM
mutli-threaded is pretty common on JVM, the
Dispatchers.Default
is multi-thread and (clearly) is the default
in general you're encouraged to use patterns that don't require synchronization, I tend not to have many times where I need to think about it
m

Manuel Pérez Alcolea

08/11/2020, 4:41 AM
aha, thanks - you mention the JVM specifically because Kotlin targets other platforms as well? (like Android)
o

octylFractal

08/11/2020, 4:42 AM
no, android is JVM too
that is for things like Kotlin Native or JS (though for native, there's multithread in the works)
m

Manuel Pérez Alcolea

08/11/2020, 4:45 AM
Android uses ART afaik - Google borrowed Java the language, but not the VM, unless you mean something else
o

octylFractal

08/11/2020, 4:46 AM
I mean that it usually works similarly to the JVM -- kotlin in general doesn't do anything special for it iirc
m

Manuel Pérez Alcolea

08/11/2020, 4:46 AM
Ah, get it
ok thanks for the help with my silly questions, it's a weird new world
s

streetsofboston

08/11/2020, 12:15 PM
For local variables, you don't need to worry about race conditions. Even though a dispatcher may use more than one thread, your suspend calls will happen sequentially, never in parallel. However, if you modify shared mutable state from multiple coroutines that use the same dispatcher, then you may run into race conditions.
m

Manuel Pérez Alcolea

08/13/2020, 1:28 AM
Oh I didn't notice there's an entire section in the docs about this. https://kotlinlang.org/docs/reference/coroutines/shared-mutable-state-and-concurrency.html#thread-confinement-fine-grained
Thread confinement
is what I was used to from the others frameworks I mentioned (they didn't offer ways to have multiple threads). So what I needed to read is everything else. I dunno how I missed this.
3 Views