I've used coroutine frameworks in a few languages ...
# coroutines
m
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
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
aha, thanks - you mention the JVM specifically because Kotlin targets other platforms as well? (like Android)
o
no, android is JVM too
that is for things like Kotlin Native or JS (though for native, there's multithread in the works)
m
Android uses ART afaik - Google borrowed Java the language, but not the VM, unless you mean something else
o
I mean that it usually works similarly to the JVM -- kotlin in general doesn't do anything special for it iirc
m
Ah, get it
ok thanks for the help with my silly questions, it's a weird new world
s
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
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.