Skip to content
Tutorials Center
My learning

Topics

Lesson 93 of 134 ยท Coroutines

Introduction to Coroutines

A beginner-friendly introduction to Kotlin coroutines - why waiting is wasteful, suspend functions, launch and runBlocking, how coroutines differ from threads, and how to run them with kotlinx.coroutines.

Think about what a program does while it waits. It asks a server for data and then does nothing until the answer arrives. It reads a file and sits idle while the disk works. If the program does only one thing at a time, every wait is wasted time, and if it is a server with thousands of users, wasted threads. Coroutines are Kotlin's answer: a way to write code that waits without blocking, in a plain, top-to-bottom style.

This lesson explains the idea in everyday words, then runs your first coroutines. The library behind them, kotlinx.coroutines, is available in our runner, so every example here executes. The next lessons go deeper: suspend functions, builders and structured concurrency.

The problem: waiting blocks threads

A thread is a path of execution managed by the operating system. Each thread costs memory (often around a megabyte of stack space) and switching between thousands of them is slow. The classic way to do two things at once is to start more threads, but a thread that waits for the network still occupies all of its resources while doing nothing.

Compare two ways of waiting. Thread.sleep(1000) blocks: the thread is held for a second and nobody else can use it. The coroutine function delay(1000) suspends: the coroutine says "wake me in a second" and gives its thread back, so the thread can run other coroutines in the meantime. When the second is over, the coroutine continues exactly where it stopped, with all its local variables intact.

A coroutine is not a thread. It is a lightweight task that runs on top of threads and can pause and resume. You can start 100,000 coroutines on a laptop; you cannot start 100,000 threads.

Your first coroutine

A coroutine needs a place to live. The simplest is runBlocking, which starts a coroutine and blocks the current thread until it finishes. It is the bridge between ordinary code and coroutines and is mostly used in main and in tests. Inside it, launch starts a new child coroutine that runs concurrently.

Kotlin launch and delay

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is Hello, followed by world, although launch appears first in the code. The reason is that launch does not wait: it schedules the child and returns immediately, so println("Hello,") runs first. The child then runs delay(100), which suspends it for 100 ms, and prints when it wakes up. runBlocking does not return until all of its children have finished, so the program does not end early.

Read the first line carefully. fun main() = runBlocking { ... } is a function whose body is one expression, and the lambda's last expression becomes its result. If that last expression is a launch, the result is a Job and main no longer returns Unit, which is not a valid entry point. Write runBlocking<Unit> { ... } when in doubt, or end the block with a println.

Why it feels like normal code

Without coroutines, asynchronous code needs callbacks: do A, and when A is done, call this function to do B. Nested callbacks quickly become unreadable. With coroutines, you write steps one after another, and a suspend function can pause in the middle.

Kotlin Sequential code that waits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The code reads like a blocking program, yet the thread is free during both delay calls. The keyword suspend marks a function that may pause. The compiler turns such a function into a small state machine behind the scenes, which is why coroutines are cheap.

Doing work at the same time

The real payoff is concurrency. Five tasks that each wait about 100 ms do not need half a second when they wait at the same time. To see that the coroutines really overlap, we collect their results and print them in the order they finish. A Job is a handle to a started coroutine, and joinAll waits for several of them.

Kotlin Order follows the delays, not the start order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Task 4 sleeps for 20 ms and task 0 for 100 ms, so they finish in reverse order, whatever the start order was. All five ran on one thread (the one of runBlocking), and each delay handed the thread over to the others. As a stress test, here are 100,000 coroutines that each suspend briefly and then add to a counter. Try that with threads and the JVM would run out of memory.

Kotlin One hundred thousand coroutines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The counter is safe only because all coroutines of this runBlocking run on one thread; with several threads you would need synchronization (see shared mutable state). Do not copy the habit of mutating shared variables from coroutines running on different threads.

Calling suspend functions: the rule

A suspend function may only be called from a coroutine or from another suspend function, because only then is there something that can pause. Violating the rule is a compile error:

Kotlin Calling suspend from normal code (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler stops with an error about calling a suspend function from a non-suspend context. There are two ways out: make the caller suspend as well (suspend fun main() is allowed), or start a coroutine with a builder such as runBlocking:

Kotlin Two valid ways to call suspend code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Coroutines versus threads, callbacks and Java

Threads Callbacks Coroutines
Cost high (memory, scheduling) low very low
Readability simple but blocking nested and hard sequential
Error handling per thread scattered normal try/catch
Cancellation awkward manual built in

Coroutines run on top of a pool of threads called dispatchers (see dispatchers and context). They do not remove concurrency problems; they make waiting cheap and the code readable. CPU-heavy work still needs real cores.

When to use coroutines

  • Network, file or database calls where the program mostly waits.
  • Several independent jobs that should run at the same time and be combined.
  • Code that must be cancellable, such as an operation the user can abandon.
  • Streams of values over time (see flows).

When to skip them

  • A short, simple, purely sequential program. A main that calls three functions needs no coroutine.
  • Parallelising pure computation on a fixed number of cores: Java's executors or parallel streams may be simpler.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between Thread.sleep(1000) and delay(1000) inside a coroutine?

    delay is a suspend function. The coroutine pauses and the thread can run other work. Thread.sleep holds the thread.
  2. 2. What does runBlocking do?

    runBlocking is the bridge from ordinary code into coroutines. It waits until the coroutine and all its children finish.
  3. 3. Why can't an ordinary function call a suspend function directly?

    Suspending needs a coroutine to suspend. An ordinary function has no such context, so the compiler reports an error.
  4. 4. In the example with five launch calls and delays of 100, 80, 60, 40 and 20 ms, which task prints first?

    Each coroutine wakes up after its own delay. The shortest delay finishes first, regardless of the start order.

Summary

  • A coroutine is a lightweight task that can suspend and resume; it is not a thread.
  • delay suspends and frees the thread; Thread.sleep blocks it.
  • runBlocking bridges normal code and coroutines; launch starts a concurrent child.
  • A suspend function may only be called from a coroutine or another suspend function.
  • Coroutine code reads top to bottom, uses normal try/catch, and supports cancellation.
  • You can run huge numbers of coroutines, but they do not remove the need for synchronization.

Next: Suspend Functions