0
votes

The comment in example code says delay() is non-blocking. Should it be suspending ?

https://kotlinlang.org/docs/reference/coroutines/basics.html

fun main() {
    GlobalScope.launch { // launch new coroutine in background and continue
        delay(1000L) // non-blocking delay for 1 second (default time unit is ms)
        println("World!") // print after delay
    }
    println("Hello,") // main thread continues while coroutine is delayed
    Thread.sleep(2000L) // block main thread for 2 seconds to keep JVM alive
}
1
It is a correct description because it does not block any thread, it just suspends the current coroutine. - Moira
non-blocking is a well defined term in Computer Science. The println("World!") would be run immediately, instead of waiting for 1 second, based on the definition. Don't use this term if your meaning is different. - user1443721
My meaning is definitely not different, I don't see what you're trying to say. Delay is not a blocking call, as I just explained. - Moira
@Moira: delay is suspending and non-blocking. Joffrey has answered it. it is not "non-blocking" only. - user1443721
@Moira: as you said, "it just suspends the current coroutine". Why does the comment for the delay call not say so? Instead, the comment is "non-blocking". Is it not misleading? - user1443721

1 Answers

9
votes

delay is suspending and non-blocking.

TL;DR: delay does have the effect of "waiting" before executing the statement that follows it in the current coroutine. Non-blocking simply means that during this wait, the current thread can do something else.


The Kotlin documentation often says "non-blocking" for suspending functions to make it clear that they don't block the current thread, but instead simply suspend the current coroutine.

It may be misleading sometimes because "non-blocking" places the emphasis on the fact that nothing is blocked, while it should still be made clear that suspending functions do suspend the current coroutine (so at least something is kinda blocked, even if the thread itself carries on).

The fact that they suspend the current coroutine make these functions appear synchronous from the point of view of the current coroutine, because the coroutine needs to wait for these functions to complete before executing the rest of the code. However, they don't actually block the current thread because their implementation uses asynchronous mechanisms under the cover.