CodeGym /Courses /Kotlin SELF /suspend and delay vs Thread.sleep — how to “wait properly...

suspend and delay vs Thread.sleep — how to “wait properly”

Kotlin SELF
Level 52, Lesson 2
Available

1. suspend and delay: waiting without blocking

When you start programming, waiting seems like the simplest action in the world: “I’ll just pause for 200 ms and that’s it.” But the computer is not meditating at that moment—it’s holding resources. If the waiting is done in a blocking way, you occupy a thread and prevent the program from doing something else (sometimes—even from rendering the UI or processing input).

Imagine a thread as a waiter in a cafe. If the waiter walks away and stands by the wall waiting exactly 5 minutes while you finish your soup, then they won’t take new orders or bring dishes to other tables. That’s blocking: the thread is busy waiting and provides no value.

Kotlin coroutines were invented precisely so that waiting could be expressed differently: a coroutine is “put on pause,” while the thread at that moment can do other work. In the official Kotlin materials, this is described as the ability to suspend execution without blocking system resources.

suspend: an honest “I can wait” marker

The word suspend often scares beginners because it looks like a “magic mode.” In reality it’s almost like a sticker on a box: “careful, there may be waiting inside.” suspend does not promise speedups, does not promise a separate thread, and does not promise parallelism. It promises only one thing: this function is allowed to be suspended (meaning it may contain suspension points).

A practical rule follows immediately: if your function performs “proper waiting” via coroutine mechanisms, it almost certainly should be suspend. And then the compiler starts protecting you: it will not allow calling such a function from regular code “any old way.”

Let’s look at a minimal example of a “function with an honest contract”:

import kotlinx.coroutines.delay

suspend fun loadGreeting(): String {
    delay(200)
    return "Hello!"
}

What matters here is not the string "Hello!", but the fact that delay(200) requires a coroutine context. Which means the function must be suspend.

If you try to call it directly from a regular main, the compiler won’t allow it:

fun main() {
    val text = loadGreeting() // Compilation error: suspend function...
    println(text)
}

This is not “Kotlin being annoying,” but protection from unpredictable waiting in the wrong place.

delay(...): a “pause” without blocking a thread

Now let’s move on to the hero of the lecture—delay. At the level of how it feels, delay(200) looks like Thread.sleep(200): “wait 200 milliseconds.” But the meaning is different. delay is a suspend function from kotlinx.coroutines that suspends a coroutine, not a thread. That’s why it can only be called inside coroutine code.

The simplest skeleton (which we already had in the lecture about runBlocking) looks like this:

import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    println("A")      // A
    delay(200)
    println("B")      // B
}

The key point for a beginner: yes, visually the program “stands still” between "A" and "B". But this waiting is expressed in a way that lets the coroutine yield execution instead of holding the thread “hostage.”

Suspension point: where a coroutine is allowed to “go on pause”

delay(...) is a classic example of a suspension point. This is a place where a coroutine can stop its execution and continue later. In the Kotlin documentation, coroutines are described exactly like this: code can be suspended and resumed in a natural sequential style via suspending functions.

A small diagram for intuition:

flowchart TD
    A["The coroutine executes code"] --> B["Encounters delay(...)"]
    B --> C["Coroutine is suspended"]
    C --> D["Time passes"]
    D --> E["Coroutine continues after delay"]

Important: this diagram is about a coroutine, not a thread. A thread is a separate entity, and it can be free to do other work while the coroutine “sleeps.”

3. Thread.sleep(...): a pause that truly “freezes” a thread

Now let’s compare with a Java classic—Thread.sleep. This function does exactly what it says: it puts the current thread to sleep. In waiter terms, the waiter actually goes into the back room and locks the door.

And here a common trap appears: “But I’m inside runBlocking, so it’s coroutines, so Thread.sleep is kind of ‘OK’.” No. Coroutines don’t cancel physics. If you call Thread.sleep, the thread is blocked for real.

import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    println("Before sleep")   // Before sleep
    Thread.sleep(200)
    println("After sleep")   // After sleep
}

From the outside, the behavior looks similar to delay, but semantically it’s completely different. delay means “the coroutine will wait,” Thread.sleep means “the thread will wait.”

To lock in the difference, a small table is useful:

What we do How we wait What is “paused” Need suspend Can it be called from a regular function
Pause in coroutine code
delay(ms)
Coroutine Yes No
Pause anywhere
Thread.sleep(ms)
Thread No Yes

4. Practical pattern: waiting inside a suspend function

In this section we’ll take the most useful step: we won’t just look at delay, we’ll embed it into a programming style that doesn’t fall apart in a week. Courses often show delay(100) right in main, but real projects don’t live like that. A good style is to wrap “long operations” into separate functions and make their contract honest.

Suppose we have our console mini-project (the one we were building the other day in the lecture about collections and commands): a simple expense tracker with commands add, list, total. Now we want to add a sync command that “pretends” to sync data with a server. Our server is imaginary for now, so we’ll simulate the delay.

Let’s make a suspend function:

import kotlinx.coroutines.delay

suspend fun syncExpenses(): String {
    delay(500)
    return "Sync completed"
}

And now use it in a coroutine scenario via runBlocking:

import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    val result = syncExpenses()
    println(result) // Sync completed
}

This is a very important architectural habit: you don’t smear waiting across the whole codebase—you collect it where it logically belongs to the operation.

For comparison: a “blocking version” of the same operation

Sometimes it’s useful to make an analogue so your brain notices the difference more clearly:

fun syncExpensesBlocking(): String {
    Thread.sleep(500)
    return "Sync completed (blocking)"
}

And the call:

fun main() {
    val result = syncExpensesBlocking()
    println(result) // Sync completed (blocking)
}

Externally, it looks similar. But the first version integrates into the coroutine world and plays nicely with other suspend operations, while the second one is always about blocking a thread.

5. Why delay doesn’t “speed things up,” and how to debug waiting

Why delay doesn’t “make the program faster,” but is still more correct

This section usually triggers an internal debate: “If my console program has a single main, and I’m just waiting 500 ms, what’s the difference—delay or Thread.sleep? Either way, 500 ms will pass.” And that’s a good question: in the minimal example it really does seem like there’s no difference. At the “time between A and B” level—yes, it’s the same.

The difference shows up when the program becomes more complex and contains more work than a single linear sequence. Then blocking a thread starts getting in the way: the thread is busy waiting and cannot service other tasks. Coroutines, on the other hand, are designed as lightweight units of execution that can be suspended without blocking system resources.

It’s important to phrase the idea carefully without getting ahead of ourselves: delay doesn’t do magic by itself; it simply makes waiting “compatible” with the coroutine model. Even if you’re not launching multiple coroutines right now, you’re already writing code so it won’t become a “blocking brick” in the future.

Another practical reason to like delay: it forces you to keep waiting in the suspend layer. And that automatically makes code cleaner: the function signature tells you that waiting may happen inside.

Mini debugging skill: “check who is waiting, and how”

In this section we’ll practice understanding waiting not only with our eyes, but also with numbers. When you start writing coroutine code, you’ll often feel like “it kind of works, but it’s mysterious.” The simplest way to remove the mystique is to measure time and print intermediate steps.

Let’s create a utility that prints elapsed time (this isn’t specific to coroutines, but it helps a lot):

fun log(startMs: Long, message: String) {
    val delta = System.currentTimeMillis() - startMs
    println("[+$delta ms] $message")
}

Now let’s use it with delay:

import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    val start = System.currentTimeMillis()

    log(start, "Started")      // [+0 ms] Started
    delay(200)
    log(start, "After delay") // [+200..250 ms] After delay
}

And with Thread.sleep:

import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    val start = System.currentTimeMillis()

    log(start, "Started")       // [+0 ms] Started
    Thread.sleep(200)
    log(start, "After sleep")  // [+200..250 ms] After sleep
}

Again: externally it looks similar. But now you can clearly see where the waiting is, and you can start moving it in a disciplined way into suspend functions.

6. Common mistakes when working with suspend, delay, and Thread.sleep

Mistake #1: trying to call delay() from a regular function and “somehow bypass the compiler.”
Beginners sometimes start looking for workarounds: “can I do delay without suspend?” Technically you can (via bad tricks), but you break the main idea of coroutines: the waiting contract must be visible in the signature. The correct fix is almost always the same: either mark the function as suspend, or move the waiting to a place that already has a coroutine context (for example, inside a runBlocking block).

Mistake #2: using Thread.sleep() inside coroutine code “because it’s simpler.”
This is the most common habit brought over from Java: put in Thread.sleep and live happily. The problem is that this code blocks the thread. While you’re learning, it might not blow up, but as soon as there’s a lot of waiting, or other tasks appear, the program will start “lagging” in a non-obvious way. If you specifically want to “wait” in a coroutine scenario—use delay.

Mistake #3: adding suspend “just in case,” while it’s unclear why.
Sometimes students start putting suspend everywhere, as if it were a “coroutine mode.” But suspend is not decoration and not a speed booster—it changes the function contract: it can’t be called directly from regular code. A good criterion is simple: add suspend when the function actually contains delay (or other suspend operations), or when you intentionally want to allow it to be suspended.

Mistake #4: expecting delay to make execution parallel by itself.
delay is waiting, not launching additional work. If your program does one operation after another, it will keep doing one after another—just with waiting expressed correctly. That’s fine: right now we’re learning “how to wait properly,” not “how to do everything at once.”

Mistake #5: mixing blocking and non-blocking waiting in the same logic without clear boundaries.
When in one place you have delay, in another you have Thread.sleep, and around that you also have I/O and commands, the behavior becomes hard to predict. It’s better to follow discipline: if you’re already in a coroutine scenario, use coroutine waiting tools; if you’re writing completely regular synchronous code, then at least be consciously aware that Thread.sleep blocks the thread.

1
Task
Kotlin SELF, level 52, lesson 2
Locked
Soft pause
Soft pause
1
Task
Kotlin SELF, level 52, lesson 2
Locked
Service status
Service status
1
Task
Kotlin SELF, level 52, lesson 2
Locked
Log timecode
Log timecode
1
Task
Kotlin SELF, level 52, lesson 2
Locked
Two Types of Waiting
Two Types of Waiting
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION