Thread.sleep and coroutine delay


I’m trying to make the most lightweight possible “wait for a state to happen, then continue” - so I actually do want to block.

Is there any particular advantage of Coroutine delay over Thread.sleep? Does it chew up less CPU? The IDE was throwing out “inappropriate blocking” warnings when I used Thread.sleep(5), so I thought I might be doing it wrong.

fun waitForMoveToEnd(vararg motors: BaseMotor) = runBlocking(Dispatchers.Default) {
    while (motors.any { it.isMoving }) {
        delay(5) // or better to try { Thread.sleep(5) } catch (ie: InterruptedException) { }

The question is not actually about kotlin since you are referring to core java methods. The first reference in google answers it.

As for your code, you are trying to use blocking sleep method inside the coroutine which kills the idea of coroutines. Please read documentation on delay method.


I thought I did - maybe the wrong documentation? From the intro docs

We are using the delay() function that’s like Thread.sleep(), but better: it doesn’t block a thread, but only suspends the coroutine itself. The thread is returned to the pool while the coroutine is waiting, and when the waiting is done, the coroutine resumes on a free thread in the pool.

Which made me think that in general “delay” is less resource intensive than Thread.sleep, because it doesn’t eat an entire thread.

Great! Which reference do you mean? (What Google Search were you doing?)


You asked for wait and sleep -

As for delay, it does something different. It does not block or suspend a thread, it suspends a coroutine and yields the thread to the next task in line. There is no CPU work involved in either of them, they just handle threading differently.


D’oh. I did say that didn’t I. Corrected to match the code, which is what I meant to say:
"How does Thread.sleep work differently than Coroutine’s delay"

This post goes into detail how it may free up the thread to do other work. Maybe that is the only difference, and it isn’t more lightweight, or finer-grained time slices, or anything useful in a small IoT device.


You should read comments to the post as well. Thread.sleep blocks the thread so if you call it, say, ten times in line in different coroutines that run on Dispatchers.Default, you will block the whole thread pool and stop the world. If you call it on UI, you will freeze UI thread and the block display loop. The delay could be called thousand times and still will work on the thread pool of 8 threads.


So it sounds like I should go with delay for my use case, esp on a lightweight (single underpowered core) IoT device. Thanks!