Does delay(Long) automatically yield the thread pool?

Maybe this is obvious given the design of Coroutines, but I want to be sure. When you call delay(Long) in a Coroutine, does that implicitly yield() the thread pool?

I’ve got a system where there are a lot of parallel things going on – some things which depend on others finishing first – and strong ordering of tasks cannot be guaranteed due to the black-box behavior of dispatchers when scheduling Coroutines. I’m writing some retry logic sort of like the following:

suspend fun doSomeComputationWithRetry(): Int? {
    var result: Int?
    var retryCount = 0

    do {
        result = someComputationWhichMayNotSucceedYet()

        // Allow other workers to finish so this computation can succeed:
        if (result == null) {
            yield() // Do I need this?
            delay(100)
        }
    } while (retryCount++ < 3 && result == null)

    return result
}

Do I need both yield() and delay(100) in there? It would defeat the purpose of the delay(100) if the thread pool wasn’t freed up to do other work. I want to say I don’t need both, but I’m paranoid lol.

Thanks!

2 Likes

If the delay is greater than zero, yes

The coroutines library makes strong ordering of tasks pretty straightforward actually. When writing suspend methods, the async code runs in sequence just like you’d expect. I suggest reading the Coroutines Guide

If the computation may need to be shared by multiple calls, you can track it using a Deferred (instead of some Int? var) and then call result.await() to know that it is done.

4 Likes