Programming languages · Intermediate · 24 min
Run concurrent tasks with Kotlin coroutines
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Kotlin 2.4.21 · kotlinx.coroutines 1.11.0 · Gradle 9.9.2 · Eclipse Temurin JDK 25
You will build a Gradle console app that loads three slow services at once with Kotlin coroutines, cancels cleanly on failure and timeout, streams values with a Flow and tests it all in virtual time.
On this page
A coroutine is a piece of work that can pause and resume. When a coroutine waits for a network reply it gives its thread back, so one thread can carry thousands of coroutines that are mostly waiting. Kotlin's language gives you one keyword, suspend, which marks a function that is allowed to pause. Everything else, launch, async, timeouts, dispatchers and Flow, comes from the kotlinx.coroutines library.
In this tutorial you build a small console app that loads a dashboard from three slow services: the weather, an exchange rate and some headlines. The services are stand-ins written with delay, so nothing touches the internet and every timing is predictable. You load them one after another, then all at once, see what happens when one fails or is too slow, move work onto the right threads, stream a changing value with a Flow, and finish with tests that skip the waiting entirely.
You use Gradle to build, because that is how real Kotlin projects, including Android apps and Ktor or Spring servers, pull in kotlinx.coroutines.
Step 1 · Install Gradle and create the project
Gradle ships as one zip with a SHA-256 checksum beside it. The zip is about 135 MB, and the first build then downloads the Kotlin compiler and libraries, so on prepaid mobile data do this step over Wi-Fi. Install curl and unzip, then download Gradle 9.9.2 into a fresh temporary folder and check it:
sudo apt update
sudo apt install -y curl unzip ca-certificates
GRADLE_VERSION=9.9.2
cd "$(mktemp -d)"
curl -fsSLO "https://services.gradle.org/distributions/gradle-${GRADLE_VERSION}-bin.zip"
curl -fsSLO "https://services.gradle.org/distributions/gradle-${GRADLE_VERSION}-bin.zip.sha256"
echo "$(cat "gradle-${GRADLE_VERSION}-bin.zip.sha256") gradle-${GRADLE_VERSION}-bin.zip" | sha256sum -c -The checksum line must print gradle-9.9.2-bin.zip: OK. If it prints FAILED, delete the files and download again. Unpack Gradle under your home folder and put it on your path:
mkdir -p ~/.local/opt
unzip -q "gradle-${GRADLE_VERSION}-bin.zip" -d ~/.local/opt
export PATH="$HOME/.local/opt/gradle-${GRADLE_VERSION}/bin:$PATH"
echo "export PATH=\"\$HOME/.local/opt/gradle-${GRADLE_VERSION}/bin:\$PATH\"" >> ~/.bashrc
rm "gradle-${GRADLE_VERSION}-bin.zip" "gradle-${GRADLE_VERSION}-bin.zip.sha256"
gradle --versionA Gradle you unpack yourself gets no apt updates. To upgrade, repeat this step with a newer GRADLE_VERSION, change the line at the end of ~/.bashrc and delete the old folder in ~/.local/opt. SDKMAN (sdk install gradle 9.9.2) and, on macOS, brew install gradle are other ways to get the same thing.
Now create the project by hand. It has two build files and a source folder:
mkdir -p ~/coroutines-demo/src/main/kotlin ~/coroutines-demo/src/test/kotlin
cd ~/coroutines-demo
cat > settings.gradle.kts <<'KTS'
rootProject.name = "coroutines-demo"
KTS
cat > build.gradle.kts <<'KTS'
plugins {
kotlin("jvm") version "2.4.21"
application
}
repositories {
mavenCentral()
}
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.11.0")
testImplementation(platform("org.junit:junit-bom:6.1.3"))
testImplementation("org.junit.jupiter:junit-jupiter")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
kotlin {
jvmToolchain(25)
}
// Choose which demo to run with -Pdemo=Name; each one is a file with its own main.
application {
mainClass = providers.gradleProperty("demo")
.map { "demo.${it}Kt" }
.orElse("demo.SequentialKt")
}
tasks.test {
useJUnitPlatform()
testLogging { events("passed", "failed") }
}
KTSkotlinx-coroutines-core is the library itself and kotlinx-coroutines-test is only for tests. From Gradle 9 you must declare junit-platform-launcher yourself; the JUnit BOM keeps every JUnit part on the same version. Each demo in this tutorial is a separate file with its own main, and the application block picks one from the -Pdemo property: -Pdemo=Concurrent runs Concurrent.kt.
Check it worked
gradle --version prints a block that starts with Gradle 9.9.2 and names a JVM 25 under Launcher JVM. ls ~/coroutines-demo shows build.gradle.kts, settings.gradle.kts and src.
Step 2 · Write suspend functions and call them in order
Create the three fake services. delay pauses the coroutine for the given number of milliseconds without blocking the thread, which is exactly what a well-behaved network client does while it waits. Because delay can pause, every function that calls it must be marked suspend:
cd ~/coroutines-demo
cat > src/main/kotlin/Services.kt <<'KT'
package demo
import kotlinx.coroutines.delay
data class Weather(val city: String, val celsius: Int)
data class Rate(val pair: String, val value: Double)
// Stand-ins for three slow network services. The values are made up.
class Services(private val failRate: Boolean = false) {
suspend fun weather(city: String): Weather {
delay(1_000)
return Weather(city, 29)
}
suspend fun rate(pair: String): Rate {
delay(800)
if (failRate) throw IllegalStateException("rate service returned 503")
return Rate(pair, 1530.0)
}
suspend fun headlines(): List<String> {
delay(1_200)
return listOf("Rain expected this afternoon", "Market opens higher")
}
}
KT
cat > src/main/kotlin/Sequential.kt <<'KT'
package demo
import kotlinx.coroutines.runBlocking
import kotlin.time.measureTime
fun main() = runBlocking {
val services = Services()
val took = measureTime {
val weather = services.weather("Lagos")
val rate = services.rate("USD/NGN")
val news = services.headlines()
println("$weather | $rate | ${news.size} headlines")
}
println("sequential: ${took.inWholeMilliseconds} ms")
}
KT
gradle -q run -Pdemo=Sequential | tee sequential.txtA plain main cannot call a suspend function, because there is no coroutine for it to pause. runBlocking bridges the two: it starts a coroutine and blocks the main thread until that coroutine and everything it started have finished. Use it at the top of a console program or a test, and nowhere else; inside coroutine code it would block a thread that other coroutines need.
Inside the block, each call waits for the previous one. Suspend functions run in order by default, like ordinary functions.
Check it worked
The first run takes a minute or two while Gradle downloads the Kotlin compiler and libraries. Then you see two lines, something like:
Weather(city=Lagos, celsius=29) | Rate(pair=USD/NGN, value=1530.0) | 2 headlines
sequential: 3027 msThe time is a little over 3,000 ms: 1,000 + 800 + 1,200, one after another.
Step 3 · Run them at the same time with async and launch
There are two ways to start a coroutine. async starts work that produces a value: it returns a Deferred, and await() suspends until the value is ready. launch starts work that returns nothing, such as logging or a progress message: it returns a Job you can cancel or wait for.
Create Concurrent.kt. loadDashboard starts the three calls with async inside coroutineScope, and main launches a ticker that prints a progress line every half second while the dashboard loads:
cd ~/coroutines-demo
cat > src/main/kotlin/Concurrent.kt <<'KT'
package demo
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlin.time.measureTime
data class Dashboard(val weather: Weather, val rate: Rate, val headlines: List<String>)
suspend fun loadDashboard(services: Services): Dashboard = coroutineScope {
val weather = async { services.weather("Lagos") }
val rate = async { services.rate("USD/NGN") }
val headlines = async { services.headlines() }
Dashboard(weather.await(), rate.await(), headlines.await())
}
fun main() = runBlocking {
val ticker = launch {
while (true) {
delay(500)
println(" ...still loading")
}
}
val took = measureTime {
val dashboard = loadDashboard(Services())
println(dashboard)
}
ticker.cancel()
println("concurrent: ${took.inWholeMilliseconds} ms")
}
KT
gradle -q run -Pdemo=Concurrent | tee concurrent.txtcoroutineScope creates a scope that does not return until every coroutine started inside it has finished. That rule is called structured concurrency: a function that starts coroutines cleans up after them before it returns, so no work leaks out of loadDashboard behind your back. The ticker is the opposite case: it loops forever, so main cancels it once the dashboard is in. Without ticker.cancel(), runBlocking would wait for it and the program would never end.
Everything here runs on one thread, the main thread that runBlocking blocks. The three calls overlap because each one gives the thread back while it waits.
Check it worked
You see two ...still loading lines, the Dashboard(...) line and a time of a little over 1,200 ms, the length of the slowest call rather than the sum of all three.
Step 4 · Watch one failure cancel its siblings
What should a dashboard do when the rate service fails? With coroutineScope, the answer is: fail as a whole, and stop the other calls straight away instead of letting them run on for nothing. Create Failure.kt, which prints a line whenever one of the calls is cancelled:
cd ~/coroutines-demo
cat > src/main/kotlin/Failure.kt <<'KT'
package demo
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.runBlocking
import kotlin.time.measureTime
// Runs block and reports if it was cancelled. Always rethrow CancellationException.
suspend fun <T> logged(name: String, block: suspend () -> T): T =
try {
block()
} catch (e: CancellationException) {
println("$name: cancelled")
throw e
}
fun main() = runBlocking {
val services = Services(failRate = true)
val took = measureTime {
try {
coroutineScope {
val weather = async { logged("weather") { services.weather("Lagos") } }
val rate = async { logged("rate") { services.rate("USD/NGN") } }
val news = async { logged("headlines") { services.headlines() } }
Dashboard(weather.await(), rate.await(), news.await())
}
} catch (e: IllegalStateException) {
println("dashboard failed: ${e.message}")
}
}
println("gave up after ${took.inWholeMilliseconds} ms")
}
KT
gradle -q run -Pdemo=Failure | tee failure.txtAt 800 ms the rate call throws. Its scope sees a child fail, cancels the weather and headlines calls, waits for them to stop, and then rethrows the original exception from coroutineScope, where an ordinary try/catch handles it. Cancellation itself travels as a CancellationException, which is why logged rethrows it: if you catch it and carry on, the coroutine keeps running after it was told to stop.
Sometimes you want partial results instead, for example a dashboard that shows the weather even when the rate is missing. For that, use supervisorScope in place of coroutineScope, where one child failing does not cancel the others, and handle each await() failure yourself.
Check it worked
You see weather: cancelled and headlines: cancelled (in either order), then dashboard failed: rate service returned 503, then a time of a little over 800 ms. The weather and headlines never finished, and you did not wait 1,200 ms for them.
Step 5 · Set deadlines with withTimeout and make loops cancellable
Users on slow or expensive connections should not wait for ever. withTimeout(ms) { ... } cancels the block when time runs out and throws TimeoutCancellationException; withTimeoutOrNull returns null instead, which is often easier to use.
Cancellation is cooperative. It does not stop a thread mid-instruction; it sets a flag, and suspend functions from the library such as delay check it and throw. A loop that only computes and never suspends never checks, so it carries on after it was cancelled. Create Timeouts.kt to see both sides:
cd ~/coroutines-demo
cat > src/main/kotlin/Timeouts.kt <<'KT'
package demo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.delay
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeoutOrNull
import kotlin.time.measureTime
fun main() = runBlocking {
val services = Services()
val news = withTimeoutOrNull(900) { services.headlines() }
println("headlines within 900 ms: $news")
// Spins for one second without ever checking for cancellation.
val stubborn = launch(Dispatchers.Default) {
val end = System.nanoTime() + 1_000_000_000
while (System.nanoTime() < end) { /* busy work */ }
println("stubborn: finished its loop anyway")
}
delay(100)
val stubbornStop = measureTime { stubborn.cancelAndJoin() }
println("stubborn job took ${stubbornStop.inWholeMilliseconds} ms to stop")
// The same loop, but it checks on every pass.
val polite = launch(Dispatchers.Default) {
val end = System.nanoTime() + 1_000_000_000
while (System.nanoTime() < end) { ensureActive() }
println("polite: this line never prints")
}
delay(100)
val politeStop = measureTime { polite.cancelAndJoin() }
println("polite job took ${politeStop.inWholeMilliseconds} ms to stop")
}
KT
gradle -q run -Pdemo=Timeouts | tee timeouts.txtcancelAndJoin() cancels a job and waits until it has really stopped. The loops run on Dispatchers.Default, a pool of background threads, so that main stays free to cancel them; the next step explains dispatchers. ensureActive() throws CancellationException if the coroutine has been cancelled. In real code you get the same effect from any suspending call inside the loop, or by checking isActive and returning.
Check it worked
The first line is headlines within 900 ms: null. Then stubborn: finished its loop anyway appears, and the stubborn job takes around 900 ms to stop, because it ran its whole loop. The polite job stops within a few milliseconds, and its never prints line does not appear.
Step 6 · Put work on the right threads with dispatchers
A dispatcher decides which thread a coroutine runs on. You have already used two: runBlocking keeps its coroutines on the thread that called it, and launch(Dispatchers.Default) moved the loops onto background threads. The two you choose between most often are:
Dispatchers.Defaultfor CPU work such as parsing, sorting or image processing. It has about as many threads as your machine has cores.Dispatchers.IOfor blocking calls you cannot make suspend, such asjava.io.File, JDBC drivers or older SDKs. It allows many more threads (64 by default), because they mostly sit waiting. It shares its threads withDefault.
withContext(dispatcher) { ... } runs one block on another dispatcher, suspends the caller until it is done and returns the block's result. Create Threads.kt:
cd ~/coroutines-demo
cat > src/main/kotlin/Threads.kt <<'KT'
package demo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.io.File
fun isPrime(n: Int): Boolean {
if (n < 2) return false
var d = 2
while (d * d <= n) {
if (n % d == 0) return false
d++
}
return true
}
fun here() = Thread.currentThread().name
fun main() = runBlocking {
println("start on: ${here()}")
val lines = withContext(Dispatchers.IO) {
println("reading on: ${here()}")
File("build.gradle.kts").readLines().size // blocking file read
}
val primes = withContext(Dispatchers.Default) {
println("counting on: ${here()}")
(1..200_000).count(::isPrime) // CPU work
}
println("build.gradle.kts has $lines lines; $primes primes up to 200000")
println("back on: ${here()}")
}
KT
gradle -q run -Pdemo=Threads | tee threads.txtThe function that calls withContext does not need to know which threads are involved. This is the usual pattern: a repository or service function switches to Dispatchers.IO itself, so callers can call it from anywhere, including an Android UI thread, without freezing it.
Check it worked
You see something like:
start on: main
reading on: DefaultDispatcher-worker-1
counting on: DefaultDispatcher-worker-1
build.gradle.kts has 32 lines; 17984 primes up to 200000
back on: mainThe worker numbers can differ, and the same worker can serve both blocks because IO and Default share threads. What matters is that the work left main and came back to it.
Step 7 · Stream changing values with a Flow
A suspend function returns one value. A Flow returns many, one at a time, such as a price that updates every few seconds or rows read from a database. Build one with flow { ... } and send each value with emit. A flow is cold: the code inside does nothing until someone calls collect, and it runs again for every collector. Create Ticks.kt:
cd ~/coroutines-demo
cat > src/main/kotlin/Ticks.kt <<'KT'
package demo
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.runBlocking
// A made-up exchange rate that moves every 200 ms, five times.
fun rateTicks(): Flow<Double> = flow {
var value = 1530.0
for (change in listOf(2.5, -1.0, 4.0, -3.5, 1.0)) {
delay(200)
value += change
emit(value)
}
}
fun main() = runBlocking {
val ticks = rateTicks().map { "USD/NGN $it" }
println("flow built, nothing emitted yet")
ticks.collect { println(it) }
println("flow complete")
}
KT
gradle -q run -Pdemo=Ticks | tee ticks.txtmap returns a new flow that changes each value on its way through; like the original, it does nothing until collected. collect suspends until the flow finishes, and if the collecting coroutine is cancelled the flow stops too, so a screen that goes away stops its updates.
Check it worked
You see flow built, nothing emitted yet first, then five lines arriving about 200 ms apart: USD/NGN 1532.5, USD/NGN 1531.5, USD/NGN 1535.5, USD/NGN 1532.0 and USD/NGN 1533.0, then flow complete.
Step 8 · Test coroutine code in virtual time
Tests that really wait 1,200 ms per call become slow and flaky. runTest from kotlinx-coroutines-test runs the test on a scheduler with a virtual clock: when every coroutine is waiting in delay, the clock jumps straight to the next wake-up. currentTime tells you how many virtual milliseconds have passed, so you can assert that work happened concurrently without waiting for it. Create the test file:
cd ~/coroutines-demo
cat > src/test/kotlin/DashboardTest.kt <<'KT'
package demo
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.test.currentTime
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withTimeout
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
class DashboardTest {
@Test
fun `loads all three in the time of the slowest`() = runTest {
val dashboard = loadDashboard(Services())
assertEquals(29, dashboard.weather.celsius)
assertEquals(2, dashboard.headlines.size)
assertEquals(1_200, currentTime)
}
@Test
fun `one failure fails the whole dashboard early`() = runTest {
val result = runCatching { loadDashboard(Services(failRate = true)) }
assertEquals("rate service returned 503", result.exceptionOrNull()?.message)
assertEquals(800, currentTime)
}
@Test
fun `headlines miss a one second deadline`() = runTest {
val result = runCatching { withTimeout(1_000) { Services().headlines() } }
assertTrue(result.exceptionOrNull() is TimeoutCancellationException)
assertEquals(1_000, currentTime)
}
@Test
fun `rate ticks arrive every 200 ms`() = runTest {
val ticks = rateTicks().toList()
assertEquals(listOf(1532.5, 1531.5, 1535.5, 1532.0, 1533.0), ticks)
assertEquals(1_000, currentTime)
}
}
KT
gradle test | tee test.txtThe first test proves the calls overlap: in sequence they would take 3,000 virtual ms. The second proves the siblings were cancelled at 800 ms rather than left to finish at 1,200. toList() collects a whole flow into a list, which is the simplest way to test a short one.
Check it worked
The output lists four lines such as DashboardTest > loads all three in the time of the slowest() PASSED and ends with BUILD SUCCESSFUL. The four tests cover 4.0 seconds of delays between them, yet the test task spends only milliseconds running them once the build has compiled. To see a failure, change 1_200 to 3_000 in the first test, run gradle test again and read the message that shows the expected and actual time, then change it back.
The same ideas on Android
In an Android app you do not write runBlocking. Each ViewModel has a ready-made scope, viewModelScope, whose coroutines run on the main thread and are cancelled when the user leaves the screen for good. The dashboard loader you wrote fits straight in:
class DashboardViewModel(private val services: Services) : ViewModel() {
private val _state = MutableStateFlow<Dashboard?>(null)
val state: StateFlow<Dashboard?> = _state
fun refresh() {
viewModelScope.launch {
_state.value = withTimeoutOrNull(5_000) { loadDashboard(services) }
}
}
}The structured concurrency from this tutorial is what makes this safe: when the screen closes, viewModelScope is cancelled, which cancels loadDashboard and all three calls inside it. On low-end Android phones and prepaid data, that means no battery or data spent on results nobody will see. Write the screen to show something useful when the state stays null after the timeout.
Step 9 · Clean up
When you share a Gradle project, add the Gradle Wrapper with gradle wrapper --gradle-version 9.9.2 and commit the files it creates, so everyone builds with the same Gradle version. The wrapper downloads its own copy of Gradle the first time it runs, so expect another download of about 135 MB.
Remove the demo project and the files Gradle downloaded for it. The gradle --stop line stops the background Gradle process that kept the build fast:
cd ~
gradle --stop
rm -rf ~/coroutines-demoKeep Gradle in ~/.local/opt and its cache in ~/.gradle if you will build other projects. To remove them too, delete those two folders and the export PATH line you added at the end of ~/.bashrc.
Check it worked
ls ~/coroutines-demo reports No such file or directory.
Next steps
- Learn the Kotlin features you will use around coroutines every day: use Kotlin null safety, data classes and extension functions.
- Get to know the build tool you used here: build a Java project with Gradle and the Kotlin DSL.
- Compare with goroutines, where concurrency is built into the language: run work concurrently in Go with goroutines and channels.
- See the same suspend-and-await model in Python: run many network calls at once with Python asyncio.
Related tutorials
- Write safer PHP with strict types, enums and readonly classesYou will take a loosely typed PHP 8.5 order script that gets totals quietly wrong and turn it into a typed domain model with strict types, a backed enum, readonly value objects and match, then prove it with a clean PHPStan 2.3 run.
- Write reusable TypeScript with genericsYou will replace three copy-pasted lookup functions with one generic function, then build a type-safe pluck, a Result type, a hand-written mapped type and a tested fetchJson helper in TypeScript 7.
- Write regular expressions you can read and testYou will build a small, tested Python module that pulls dates, money amounts and Nigerian and Kenyan phone numbers out of messy SMS text, and know how to port its patterns to JavaScript and when to stop using a regex.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials