The Programming Shortcut: Kotlin
Part of The Programming Shortcut, a series that teaches one programming idea per article to people who already program. This one is about structured concurrency.
Java, with the sharp edges filed off
Kotlin is what happens when the people who build tools for Java programmers spend years watching Java programmers trip over the same things, and then write the language they wish those programmers had.
That’s not far from the real story. Kotlin comes from JetBrains, the company behind the IntelliJ IDEA editor. The project started in 2010 and reached 1.0 in February 2016. It runs on the same Java Virtual Machine (the JVM, the program that runs Java code on every major operating system), it can call any Java library, and Java can call it back. Android supports it as a first-class language, which is where many people first meet it.
So Kotlin isn’t trying to be exotic. It takes a platform that already runs nearly everywhere and removes the parts that cost Java programmers the most time: the missing values nobody checked, the pages of boilerplate, the ceremony around simple things.
Kotlin’s coroutine library came along after many languages had already spent years trying to do several things at once, and it settled on an answer called structured concurrency, one of the clearest ideas in modern programming. Once you’ve seen it, you’ll notice when a language has it, and you’ll miss it when one doesn’t.
What you already have
Most of Kotlin will look familiar. Here’s what carries over:
| What you know | lux | Kotlin |
|---|---|---|
| a name you can’t reassign | let | val |
| a name you can | var | var |
| a function | func add(a: int, b: int) -> int | fun add(a: Int, b: Int): Int |
| a record | struct | data class |
| a value that might be missing | Option<int> | Int? |
| errors you expect | Result | exceptions, with try, catch and finally |
| matching on a value | match | when |
| a function that can pause | (none) | suspend fun |
The first seven rows are things you already know, under a new spelling or as a near
relative, so we won’t stop on them. If Int? is new to you, it means “an Int, or nothing at all”, and
the Rust article gives that idea its full treatment.
Kotlin handles errors with exceptions: an error that jumps out of the function
where it happened and up through every caller until a catch stops it. A finally
block runs on the way out, whether things went well or not. The Java
article is where exceptions get their full story.
The last row is the one that’s new. It’s where we’re headed.
One file, one command
You’ll use one tool: the kotlin command, running a script. A script is a single
file of Kotlin that runs from top to bottom, with no main function and no project
around it. Scripts whose names end in .main.kts get one extra power: a line at the
top can pull in a library, and Kotlin downloads it for you the first time.
If you use SDKMAN, one command installs Kotlin:
sdk install kotlin
Kotlin runs on the JVM, so you’ll need a JDK (Java Development Kit) too. The command-line page covers that and the other ways to install.
Now make a file called breakfast.main.kts and put this in it:
@file:DependsOn("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
import kotlinx.coroutines.*
runBlocking {
launch {
delay(1000)
println("tea is ready")
}
launch {
delay(500)
println("toast is ready")
}
println("breakfast started")
}
println("breakfast served")
Run it:
kotlin breakfast.main.kts
The first run takes a few seconds while Kotlin fetches the library named on the first line, kotlinx.coroutines, the official coroutine library from the Kotlin team. After that it comes from a cache on your disk. You should see:
breakfast started
toast is ready
tea is ready
breakfast served
Edit the file, run kotlin on it, read what it printed: that’s all the tooling
this article needs. Every coroutine example below is a complete script you can paste into a file and run
the same way.
Look at the order. “breakfast started” came first, even though it’s the last line in the block. The tea and the toast were both waiting at the same time, and the toast won because its wait was shorter. And “breakfast served” didn’t print until both were done. That last part is the idea this article is about.
A function that can wait
Before the big idea, the small one it rests on.
A coroutine is a piece of work that can pause partway through and pick up again later, without holding anything up while it’s paused. A thread, the operating system’s own unit of “something running”, is the heavier relative you may have met: each one needs its own reserved memory for its function calls and its own place in the operating system’s schedule. Coroutines are much lighter. Many of them can share one thread, taking turns: while one is paused, another runs.
In Kotlin, a function that’s allowed to pause is marked suspend. That’s the new
row in the table. Suspending is Kotlin’s word for pausing in this polite way, and
a suspension point is a place where it can happen, such as a call to delay.
@file:DependsOn("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
import kotlinx.coroutines.*
import kotlin.system.measureTimeMillis
suspend fun brew(): String {
delay(1000)
return "tea"
}
suspend fun toast(): String {
delay(500)
return "toast"
}
runBlocking {
val ms = measureTimeMillis {
println(brew())
println(toast())
}
println("one after the other: about $ms ms")
}
That takes about 1,500 milliseconds, because the calls run in order, just like any
function calls you’ve written. suspend doesn’t make anything happen at the same
time. It only says that this function is allowed to pause, so that other work can
run while it waits.
A suspend function can only be called from another suspend function or from
inside a coroutine. runBlocking is the doorway between the two worlds: ordinary
code on the outside, coroutines on the inside. It holds the program at that point
until everything started inside it has finished.
To make things happen at once, you start new coroutines. launch starts one and
moves straight on to the next line without waiting. That’s what the breakfast
script did twice.
Starting things is easy; stopping them is the hard part
Every language that runs several things at once has some way to say “start this,
and don’t wait for it”. In Go it’s go f(), which starts a goroutine and returns at
once (the Go article teaches goroutines and the channels that connect
them). In many languages it’s creating a thread. In JavaScript it’s calling an
async function and not waiting for its answer.
Starting is the easy half. The hard half is three questions. When the function that started a task returns, is the task finished? If the task fails, who hears about it? And if you change your mind, how do you stop it?
With a plain “start and forget”, the answers are: maybe not, maybe nobody, and
good luck. The task has come loose from the code that started it. Kotlin still has
a way to start work like that, called GlobalScope, so you can see it happen:
@file:DependsOn("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
import kotlinx.coroutines.*
@OptIn(DelicateCoroutinesApi::class)
fun startUpload() {
GlobalScope.launch {
delay(100)
println("upload finished")
}
}
runBlocking {
startUpload()
println("main is done")
}
This prints main is done, and that’s all. The upload never finishes, and nothing
tells you. startUpload returned right away, runBlocking had nothing of its own
left to wait for, and the program ended with the upload still in progress. The
library labels GlobalScope a delicate API for this reason, and that @OptIn
line is you signing for it.
If lux was your first language, you already know the promise this idea keeps. A lux program does one thing at a time, top to bottom, and when its last line runs, everything is over. Structured concurrency keeps that promise while letting several things happen at once.
The programmer Nathaniel J. Smith compared a bare “start this” to goto, the old
jump-anywhere instruction, in an essay called Notes on structured
concurrency.
Languages got rid of goto by giving every block a clear beginning and end: you
enter an if or a loop at the top and leave at the bottom. Structured concurrency
does the same for tasks.
Every task has a parent
Here is the rule Kotlin builds everything on:
A coroutine is started inside a scope, and a scope doesn’t end until every coroutine started inside it has ended.
A scope is a block of code that owns the tasks started in it. runBlocking makes
one. So does coroutineScope, which you can use inside any suspend function:
@file:DependsOn("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
import kotlinx.coroutines.*
suspend fun makeBreakfast() {
coroutineScope {
launch {
delay(1000)
println(" tea is ready")
}
launch {
delay(500)
println(" toast is ready")
}
println(" both started")
}
}
runBlocking {
println("making breakfast")
makeBreakfast()
println("breakfast served")
}
making breakfast
both started
toast is ready
tea is ready
breakfast served
From the outside, makeBreakfast looks like any other function call. You call it,
it does its work, it returns. Inside, two tasks ran at the same time. And the
moment it returns, you know both are done, because the scope wouldn’t let it
return any sooner.
That answers the first question. When the function returns, its tasks are finished.
Each launch inside a scope makes a child of that scope, and children can start
children of their own. So the tasks in a program form a family tree, and the tree
has the same shape as your code: a task lives inside the block that started it,
the way a variable lives inside the block that declared it. You can see every
task’s lifetime by looking at the indentation.
Compare that with GlobalScope. A task launched there has no parent. It’s an
orphan, and nobody waits for orphans.
Getting answers back
launch is for work that doesn’t hand anything back. When you want a result, use
async, which starts a coroutine and gives you a handle to its answer. Calling
await() on the handle suspends until the answer is ready.
Some readers know async and await from another language, where they mean “a
function that can pause” and “pause here until the answer arrives”; the
JavaScript article is their home. In Kotlin the pausing part is
suspend, and async is something narrower: a way to start a task that has an
answer.
@file:DependsOn("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
import kotlinx.coroutines.*
import kotlin.system.measureTimeMillis
suspend fun brew(): String {
delay(1000)
return "tea"
}
suspend fun toast(): String {
delay(500)
return "toast"
}
runBlocking {
val ms = measureTimeMillis {
val drink = async { brew() }
val food = async { toast() }
println("${drink.await()} and ${food.await()}")
}
println("at the same time: about $ms ms")
}
These are the same two functions as before, unchanged. This time it takes about
1,000 milliseconds instead of 1,500, because both waits overlap. Notice that
nothing about brew or toast had to change. Whether work runs in sequence or at
once is decided by the caller, not by the function.
An async task is a child too, so the same rule holds. If you start one and never
call await, its scope still waits for it to finish.
When one task fails
Now the second question: if a task fails, who hears about it?
In a scope, a failure goes up to the parent, and the parent does two things. It cancels all of the failed task’s brothers and sisters, because the job they were part of can’t succeed anymore. Then, once they’ve stopped, it throws the original exception out of the scope, so the code that called it sees the error, like any other function that failed.
@file:DependsOn("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
import kotlinx.coroutines.*
suspend fun makeBreakfast() {
coroutineScope {
launch {
try {
delay(1000)
println("tea is ready")
} finally {
println("tea: stopped, kettle off")
}
}
launch {
delay(300)
throw IllegalStateException("toast caught fire")
}
}
}
runBlocking {
try {
makeBreakfast()
} catch (e: IllegalStateException) {
println("no breakfast: ${e.message}")
}
}
tea: stopped, kettle off
no breakfast: toast caught fire
The tea never finished. When the toast failed, the scope cancelled the tea, the
tea’s finally block ran, and only then did the exception come out of
makeBreakfast, where an ordinary try and catch caught it.
That’s the second answer. A failure goes to the parent, and from there to the caller, the same path an exception takes through ordinary function calls. Nothing fails silently in a background corner.
Sometimes you want the opposite, where one child’s failure leaves the others alone.
Kotlin has supervisorScope for that. It’s a deliberate choice you make, not the
default.
Stopping on purpose
The third question: if you change your mind, how do you stop it?
Cancelling a coroutine means asking it to stop early. launch returns a Job,
a handle on the task, and job.cancel() asks the task to stop:
@file:DependsOn("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
import kotlinx.coroutines.*
runBlocking {
val job = launch {
try {
repeat(10) {
println("chunk $it")
delay(100)
}
} finally {
println("cleaning up")
}
}
delay(350)
job.cancel()
println("cancelled")
}
chunk 0
chunk 1
chunk 2
chunk 3
cancelled
cleaning up
Cancelling a task cancels its children too, and theirs, all the way down the tree. You don’t have to keep a list of everything a task started. Cancel the parent and the family stops.
Kotlin cancels a task by throwing a special exception inside it, called
CancellationException, at its next suspension point. That’s why the finally
block ran: as far as the task could tell, an exception was passing through. It’s
also why finally is the place for cleanup in coroutine code, such as closing a
file or deleting a half-written one.
The most common reason to cancel is time. withTimeoutOrNull runs a block and
cancels it if it takes too long:
@file:DependsOn("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
import kotlinx.coroutines.*
suspend fun slowAnswer(): Int {
delay(2000)
return 42
}
runBlocking {
val quick = withTimeoutOrNull(500) { slowAnswer() }
println("with half a second: $quick")
val patient = withTimeoutOrNull(3000) { slowAnswer() }
println("with three seconds: $patient")
}
with half a second: null
with three seconds: 42
A timeout is just a scope with a clock attached. When time runs out, everything
inside it is cancelled, children included, and null comes back instead of an
answer. Its sibling withTimeout throws an exception instead of returning null.
Cancellation is a request
Here’s where Kotlin asks for your help. In many places, “stop” means stop. In Kotlin, cancellation is cooperative: a coroutine stops only at a suspension point, or when it checks for itself. Code that never pauses never notices it was asked.
Thread.sleep waits without suspending. It’s the old Java way to pause, and it
holds the thread the whole time. Watch what happens under a timeout:
@file:DependsOn("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
import kotlinx.coroutines.*
runBlocking {
val result = withTimeoutOrNull(300) {
repeat(5) {
Thread.sleep(100)
println("step $it")
}
"finished"
}
println(result)
}
You asked for 300 milliseconds. You got five steps, 500 milliseconds, and
finished, as if the timeout weren’t there. The request to stop arrived, but the
code never paused long enough to hear it.
The same thing happens to any long calculation, a loop that crunches numbers with
no delay in it. The fix is to check. ensureActive() throws the cancellation
exception if the coroutine has been asked to stop, and does nothing otherwise:
@file:DependsOn("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
import kotlinx.coroutines.*
runBlocking {
val result = withTimeoutOrNull(300) {
repeat(5) {
ensureActive()
Thread.sleep(100)
println("step $it")
}
"finished"
}
println(result)
}
Now it stops after step 2 and prints null. A good habit for long loops is one
ensureActive() at the top of each pass.
Beware of catch (e: Exception) inside a coroutine. Since cancellation travels
as an exception, a catch-everything block catches it too, and quietly throws the
cancellation away:
@file:DependsOn("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
import kotlinx.coroutines.*
runBlocking {
val job = launch {
repeat(5) {
try {
delay(100)
println("chunk $it")
} catch (e: Exception) {
println("chunk $it failed, trying the next one")
}
}
println("still here")
}
delay(250)
job.cancel()
println("cancelled")
}
chunk 0
chunk 1
cancelled
chunk 2 failed, trying the next one
chunk 3 failed, trying the next one
chunk 4 failed, trying the next one
still here
The task was cancelled and kept right on going. In a real program, this is the
download that won’t stop, or the screen that updates after it’s been closed. My
advice is to never catch Exception in coroutine code. Catch the specific thing you
expect, such as an IOException for a network error. If you truly must catch
everything, catch CancellationException first and throw it again, which is what
the Kotlin documentation tells you to do.
Several downloads, one deadline
Time to put the three answers together. The project is a pretend downloader: four
files downloading at the same time, a deadline for the whole batch, and an
optional broken connection. Nothing touches the network. Each “chunk” is a short
delay, so the timing is predictable and you can watch the structure work.
Make a folder, and save this as tasks.main.kts. You’ll also find it in
projects/kotlin, with a few extra things to try
at the bottom.
@file:DependsOn("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
import kotlinx.coroutines.*
data class Download(val name: String, val chunks: Int, val msPerChunk: Long)
val downloads = listOf(
Download("notes.txt", 2, 100),
Download("photo.jpg", 4, 150),
Download("song.mp3", 5, 200),
Download("movie.mkv", 10, 250),
)
val deadline = args.getOrNull(0)?.toLong() ?: 1200
val broken = args.getOrNull(1)
suspend fun fetch(d: Download): Int {
var received = 0
try {
repeat(d.chunks) {
delay(d.msPerChunk)
received++
if (d.name == broken && received == d.chunks / 2) {
throw IllegalStateException("${d.name} lost its connection")
}
}
println("${d.name}: done")
return received
} finally {
if (received < d.chunks) {
println("${d.name}: stopped at $received of ${d.chunks}, partial file deleted")
}
}
}
runBlocking {
val start = System.currentTimeMillis()
try {
val total = withTimeoutOrNull(deadline) {
downloads.map { d -> async { fetch(d) } }.awaitAll().sum()
}
if (total == null) {
println("deadline of $deadline ms reached")
} else {
println("all $total chunks received")
}
} catch (e: IllegalStateException) {
println("gave up: ${e.message}")
}
println("finished in ${System.currentTimeMillis() - start} ms, nothing left running")
}
A script can read words typed after its name on the command line. They arrive in a
list called args. Here the first is the deadline in milliseconds, and the second
is the name of a file whose connection should break halfway.
Run it with the default deadline of 1,200 milliseconds:
kotlin tasks.main.kts
notes.txt: done
photo.jpg: done
song.mp3: done
movie.mkv: stopped at 4 of 10, partial file deleted
deadline of 1200 ms reached
finished in 1205 ms, nothing left running
The three small files made it. The movie was cancelled at the deadline, its
finally block cleaned up after it, and the program ended on time with nothing
left running.
Now give it three seconds:
kotlin tasks.main.kts 3000
Everything finishes, 21 chunks in about 2,500 milliseconds. One after the other, the same downloads would take 4,300 (add up each file’s chunks times its delay), so the overlap is doing its job. The batch takes as long as its slowest file.
Finally, break the song:
kotlin tasks.main.kts 3000 song.mp3
notes.txt: done
song.mp3: stopped at 2 of 5, partial file deleted
photo.jpg: stopped at 2 of 4, partial file deleted
movie.mkv: stopped at 1 of 10, partial file deleted
gave up: song.mp3 lost its connection
finished in 410 ms, nothing left running
When the song failed, its brothers and sisters were cancelled, every one of them
cleaned up, and only then did the error reach the catch at the top. Your exact
millisecond counts may differ by a few.
Look at where the concurrency lives in that file: one line, the map with async
inside withTimeoutOrNull. The scope around it is what guarantees that every
async it starts has finished, failed or been cancelled before the next line runs.
That’s all three questions answered by the shape of the code.
What’s left out
Dispatchers, which decide which threads your coroutines run on, are the next thing you’ll meet, especially for work that keeps the processor busy. Channels and Flow move streams of values between coroutines. Android adds scopes tied to screens, which cancel their work when the screen closes, so the structure you learned here runs right through an app. And there’s Gradle, Kotlin’s usual build tool, which a real project will hand you. You can mostly leave it alone and change only what you need.
When you’re ready for more, the Kotlin team’s own coroutines guide picks up from here, and the Kotlin documentation covers the rest of the language.
Ask the compiler what suspend means
You’ve been told that a suspend function can pause and pick up where it left off.
But the JVM underneath knows nothing about pausing. So where does the pausing
happen?
Put this in a file called Fetch.kt:
suspend fun fetch(): Int {
return 42
}
Compile it with kotlinc, which came with the kotlin command, and then look at
what it made with javap, a tool that came with Java:
kotlinc Fetch.kt -d out
javap -cp out FetchKt
Compare the function you wrote with the one javap describes. Count the
parameters. Check the return type. Then ask yourself what that extra parameter
might be carrying, and how a function could “pick up where it left off” if
someone handed it one.
Related
- Go: concurrency by message passing, with goroutines and channels.
- JavaScript:
asyncandawait, and code that waits for things to happen. - Java: exceptions, which carry both failures and cancellations here.
- Rust: values that might be missing, like Kotlin’s
Int?.
Tested with Kotlin 2.4.21 and kotlinx.coroutines 1.11.0, November 2026.