https://kotlinlang.org logo
Title
r

Rainer Schlonvoigt

01/04/2021, 11:06 AM
really stupid question, but i can’t find an answer by googling… Are there any guarantees on order of execution when using a single threaded coroutine dispatcher? e.g.:
val dispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher()
val scope = CoroutineScope(dispatcher)

for (i in 1..5) {
    scope.launch {
        println(i)
    }
}
are they guaranteed to be executed in order?
or is the dispatcher randomly picking work?
t

tseisel

01/04/2021, 12:44 PM
Because your
CoroutineDispatcher
is based on a Java single thread executor, coroutines are executed sequentially, in the order of submission. Note that this is not guaranteed for all
CoroutineDispatcher
implementations.
r

Rainer Schlonvoigt

01/04/2021, 1:16 PM
okay, thank you 🙂
i assumed that was the case but i couldn’t find any documentation anywhere stating that that was the case
a

Adam Powell

01/04/2021, 6:47 PM
people often will be really cagey about answering this question because if you find yourself relying on the order of resumed continuation execution instead of more explicitly controlling your desired ordering, you're likely to be in for some headaches down the road
g

gildor

01/05/2021, 12:01 AM
It's easier to assume that there is no guarantee of sequential execution rather than rely on dispatcher implementation
2
b

bdawg.io

01/05/2021, 5:29 AM
Agreed, if you don't want your code to be asynchronous from each other, you should write your code to be sequential in the first place.