Skip to main content

Chapter 1 : UseCase01 - Coroutine Builders and Execution Semantics

Updated 13 min readMarkdown

Mental Model: What Is a Coroutine?

A coroutine is a suspendable computation, represented as a state machine, executed under a Job, scheduled by a dispatcher and resumed via a continuation.

It is not a thread. It is not a task queue item.
It is a logical unit of structured execution.

Think of a coroutine as:

A piece of work that can pause, step aside, and later continue from where it left off - without blocking a thread. That’s it at a high level.

It’s not a thread. It’s not a background worker.
It’s more like a smart function that knows how to suspend and resume.

At runtime, a coroutine consists of:

  • A Job (lifecycle controller)

  • A Continuation (resumption handle)

  • A CoroutineContext

  • A state machine generated by the compiler

When a coroutine hits something like delay():

  • It pauses itself

  • Frees the thread

  • Remembers where it stopped

  • Comes back later and continues

Under the hood, Kotlin turns your suspend function into a kind of step-by-step machine that keeps track of where it paused. But you don’t have to manage that — the compiler does it for you.

You can think of a coroutine as:

  • A task with memory (it remembers its progress)

  • A lifecycle (it can complete or be cancelled)

  • A context (it knows where and how it should run)

That’s the practical mental model.

launch and async are just builders that create this structure.

launch vs async — Conceptual Difference

The difference is result handling and exception storage.

launch

  • Returns a Job

  • Does not hold a result

  • Exceptions are immediately propagated to parent

async

  • Returns a Deferred

  • Holds a result

  • Exceptions are captured and rethrown on await()

That is the architectural difference.

Both launch and async start coroutines. They run the same way.
They suspend the same way. They are scheduled the same way.

The real difference is simple - Do you care about a result?

Remember this for launch — “Just do this work”

Use launch when:

  • You want something to happen

  • You don’t need a returned value

  • You care about its completion, not its output

You get back a Job.

A Job just lets you:

  • Wait for completion (join)

  • Cancel it

It does not give you a result.

If it fails, the failure immediately affects the parent coroutine.

Remember this for async - “Do this and give me something back”

Use async when:

  • You need a computed result

  • You will call await()

You get back a Deferred.

A Deferred is basically a promise that will eventually contain a value.

If it fails:

  • The exception is stored internally.

  • It is thrown when you call await().

So async delays failure until you ask for the result.

Core Difference

launch is for side effects.
async is for values.

Everything else about their execution is the same.

Coroutine Code Example

package org.kotlincoroutineslearner.usecase01

import kotlinx.coroutines.*

/**
 * UC1 Demonstration:
 *
 * This program demonstrates the behavioral difference between
 * launch and async at runtime.
 *
 * Key Observations:
 * 1. launch propagates exceptions immediately.
 * 2. async captures exceptions until await() is called.
 * 3. Both participate in structured concurrency.
 */
fun main() = runBlocking{

    println("Parent started on thread: ${Thread.currentThread().name}")

    val launchJob = launch {
        println("launch started on: ${Thread.currentThread().name}")
        delay(500)
        println("launch completed")
    }

    val deferred = async {
        println("async started on: ${Thread.currentThread().name}")
        delay(500)
        42
    }

    println("Waiting for launch...")
    launchJob.join()

    println("Waiting for async result...")
    val result = deferred.await()
    println("Async result: $result")

    println("Parent completed")

}

OUTPUT LOGS

Parent started on thread: main
Waiting for launch...
launch started on: main
async started on: main
launch completed
Waiting for async result...
Async result: 42
Parent completed

What is happening internally?

Step 1 — runBlocking creates a root coroutine

Think of runBlocking as:

“Start a coroutine world here, and don’t leave until everything inside is finished.”

When your program hits runBlocking:

  1. It creates a root coroutine.

  2. It blocks the current thread (usually main).

  3. It waits until all child coroutines finish.

So runBlocking is basically a bridge between normal blocking code and coroutine code. It says: “I’ll stay here until my children are done.”

Step 2 — launch creates a child Job

launch:

  1. Combines parent context with its own.

  2. Creates a Standalone Coroutine.

  3. Registers itself as a child of parent Job.

  4. Schedules execution via dispatcher.

The parent now tracks it structurally.

When the code calls launch {...} inside runBlocking{...}

  1. Kotlin creates something called a Job.

  2. Job is a controller object that tracks the life of the coroutine.

A Job knows whether the coroutine is active or not. It also knows whether the coroutine is cancelled / completed. This Job becomes a child of the runBlocking Job.

So now we have a small tree:

runBlocking (parent Job)

└── launch (child Job)

That’s structured concurrency.

  1. The Coroutine is Scheduled. The coroutine body : {delay(500)
    println("Hello")}
    does not run immediately on a new thread. Instead, it is handed to a dispatcher. The dispatcher decides when and where to run it. If you didn’t specify a dispatcher, it inherits the parent one.

  2. The coroutine starts running. When it executes we have {delay(500)}. delay is a suspending function. It means - The coroutine pauses. It does not block the thread. It saves its current position. It tells the scheduler: “Resume me after 500ms.” Then the thread becomes free. The coroutine is paused. The thread is not blocked.The Job is still active.

  3. After 500ms - The scheduler wakes it up.

    The coroutine resumes exactly where it left off : println("Hello")

    Then it completes. The Job state becomes “Completed”.

  4. Now the parent (runBlocking) sees:

    “Okay, my child is done.” If there are no more children, runBlocking returns and your program continues.

Step 3 - async()

When we use :

val deferred = async {
    delay(500)
    42
}
val result = deferred.await()

The internal steps are almost identical in the above code snippet.

The only extra thing is: Instead of just completing, it stores the result (42) inside the Deferred object.

So internally:

  • It runs

  • It suspends

  • It resumes

  • It stores the result

  • It marks itself complete

Then when you call: deferred.await()

You are basically saying: “Give me the result. If you failed, throw the error.”

Important Execution Detail — Eager Start

What happens by default?

Both launch and async start immediately.

val job = launch { println("Hello") }

println("World")

You cannot guarantee whether "Hello" or "World" prints first. Why?

Because:

  • launch schedules the coroutine instantly.

  • The dispatcher decides when it runs.

  • There is no implicit ordering.

launch and async use CoroutineStart.DEFAULT, which schedules execution immediately.

If ordering matters, you must:

  • use join()

  • or control execution explicitly

Structured Concurrency Rule

This is one of the most important principles in coroutines.

What is the rule?

A parent coroutine:

  • Waits for all children to finish.

  • Cancels children if it is cancelled.

  • Fails if a child fails (unless supervised).

Example:

runBlocking {
    launch {
        delay(1000)
    }
}

runBlocking will not complete until the launch finishes.

Why does this exist?

To prevent:

  • Background coroutines leaking

  • Silent failures

  • Orphan tasks

Structured concurrency guarantees that child coroutines are bound to the lifecycle of their parent. This gives predictable cancellation and cleanup.

Internal Execution Timeline (Simplified)

Let’s compress the lifecycle into 5 stages:

1. Creation - A Job object is created.

2. Scheduling - The coroutine is handed to a dispatcher.

3. Execution - The coroutine runs until it hits a suspension point.

4. Suspension - State is saved. Thread is released.

5. Resumption :

Dispatcher resumes it later from saved state. No thread is blocked during suspension. A coroutine runs until suspension, saves its state, releases the thread, and resumes later via a continuation That’s the entire model.

TESTING THE USECASE

package uc01

import kotlinx.coroutines.*
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runTest
import kotlin.test.*

/**
 * UC1 Test Suite
 *
 * Purpose:
 * Validate the execution semantics of coroutine builders:
 * - launch
 * - async
 *
 * These tests focus on:
 * 1. Structural completion
 * 2. Result semantics
 * 3. Exception propagation
 *
 * We use runTest to control scheduling deterministically.
 */
class CoroutineBuildersTest {

    /**
     * Demonstrates that launch does not produce a result
     * and must be joined for structural completion.
     *
     * Why this matters:
     * launch is designed for side-effects.
     * Its lifecycle must be explicitly awaited via join.
     *
     * What is this test proving?
     * It proves that:
     * A coroutine started with launch does not block the parent automatically, but it
     * must complete before the parent scope finishes.
     */
    @Test
    fun `launch completes structurally`() = runTest {

        var completed = false

        val job = launch {
            delay(100)
            completed = true
        }

        assertFalse(completed)

        job.join()

        assertTrue(completed)
    }

    /**
     * Demonstrates that async produces a Deferred result
     * which must be awaited.
     *
     * Why this matters:
     * async stores its result internally and exposes it via await().
     */
    @Test
    fun `async returns computed value`() = runTest {

        val  deferred = async {
            delay(100)
            99
        }
        val result = deferred.await()
        assertEquals(99,result)
    }

    /**
     * launch propagates exception immediately to parent.
     *
     * Why:
     * launch does not capture exceptions.
     * It treats failure as fatal within structured scope.
     */
    @Test
    fun `launch propagates exception immediately`() {

        assertFailsWith<IllegalStateException> {
            runTest {
                launch {
                    throw IllegalStateException("Failure")
                }
            }
        }
    }

    /**
     * async captures exception and rethrows on await().
     *
     * Why:
     * Deferred stores failure internally.
     * Parent is not failed until await() is called.
     */

    @Test
    fun `async captures exception until await`() = runTest {
        supervisorScope {
            val deferred = async {
                throw IllegalArgumentException("Async Failure")
            }

            assertFailsWith<IllegalArgumentException> {
                deferred.await()
            }
        }
    }

    /**
     * Demonstrates eager start behavior.
     *
     * Why:
     * launch and async are eager by default.
     * They are scheduled immediately.
     */
    @OptIn(ExperimentalCoroutinesApi::class)
    @Test
    fun `coroutines start eagerly by default`() = runTest {
        var started = false

        launch {
            started = true
        }

        advanceUntilIdle()

        assertTrue(started)
    }
}

Let us discuss all the tests one-by-one.

/**
     * Demonstrates that launch does not produce a result
     * and must be joined for structural completion.
     *
     * Why this matters:
     * launch is designed for side-effects.
     * Its lifecycle must be explicitly awaited via join.
     *
     * What is this test proving?
     * It proves that:
     * A coroutine started with launch does not block the parent automatically, but it
     * must complete before the parent scope finishes.
     */
    @Test
    fun `launch completes structurally`() = runTest {

        var completed = false

        val job = launch {
            delay(100)
            completed = true
        }

        assertFalse(completed)

        job.join()

        assertTrue(completed)
    }

Step-by-step explanation

  • launch starts immediately.

  • Inside it, we delay(100).

  • Delay suspends the coroutine.

  • So completed is still false.

That’s why:

assertFalse(completed) is correct

job.join() tells us “Wait until this coroutine finishes.

After it resumes from delay and sets completed = true, the assertion passes.

Why is this important?

Because:

  • launch does NOT give you a result.

  • You must explicitly wait if you care about completion.

  • Structured concurrency ensures it will complete before scope ends.

Second test

/**
     * Demonstrates that async produces a Deferred result
     * which must be awaited.
     *
     * Why this matters:
     * async stores its result internally and exposes it via await().
     */
    @Test
    fun `async returns computed value`() = runTest {

        val  deferred = async {
            delay(100)
            99
        }
        val result = deferred.await()
        assertEquals(99,result)
    }

What is this test proving?

It proves that:

async stores and returns a value using Deferred.

What happens internally?

  • async starts immediately.

  • It suspends at delay(100).

  • When resumed, it produces 99.

  • That value is stored inside Deferred.

Then, deferred.await() means: “If you’re done, give me the result. If not, wait.” 

await() suspends until completion.

Why is this different from launch?

Because launch cannot return a value.

This test shows that:

  • async is value-oriented.

  • await() is mandatory to retrieve the result.

async returns a Deferred, which holds the result of the coroutine. await() suspends until the result is available and then returns it.

Third test

@Test
fun `launch propagates exception immediately`() {
    assertFailsWith<IllegalStateException> {
        runTest {
            launch {
                throw IllegalStateException("Failure")
            }
        }
    }
}

What is this test proving?

It proves:

A coroutine started with launch does not store exceptions — it immediately fails its parent.

What happens step-by-step?

  1. launch starts.

  2. It throws IllegalStateException.

  3. Since it’s a child of runTest, the failure propagates upward.

  4. The parent scope fails.

  5. The test catches that failure.

There is no join().
No await().
Failure happens automatically.

Why does it behave this way?

Because:

  • launch is for side effects.

  • Side effects must not silently fail.

  • So failures are treated as fatal.

This is structured concurrency doing its job.

Fourth test

/**
     * async captures exception and rethrows on await().
     *
     * Why:
     * Deferred stores failure internally.
     * Parent is not failed until await() is called.
     */

    @Test
    fun `async captures exception until await`() = runTest {
        supervisorScope {
            val deferred = async {
                throw IllegalArgumentException("Async Failure")
            }

            assertFailsWith<IllegalArgumentException> {
                deferred.await()
            }
        }
    }

What is this test proving?

It proves:

async does NOT immediately crash the parent when it fails.
It stores the exception and rethrows it when await() is called.

What happens step by step?

  1. async starts.

  2. It throws IllegalArgumentException.

  3. Instead of propagating upward, it stores the failure internally.

  4. The parent (runTest) does NOT fail immediately.

  5. Only when we call:

deferred.await()

the stored exception is rethrown.

Why does async behave differently from launch?

Because async is designed for value production.

If it failed immediately:

  • You could never coordinate multiple async calls.

  • You couldn’t combine results safely.

  • Structured concurrency would become too aggressive.

So async says:

“I’ll remember the failure. Ask me for the result, and I’ll tell you what happened.”

async captures exceptions inside its Deferred. The exception is rethrown only when await() is called. Unlike launch, it does not immediately cancel the parent.

Fifth Test

 /**
     * Demonstrates eager start behavior.
     *
     * Why:
     * launch and async are eager by default.
     * They are scheduled immediately.
     */
    @OptIn(ExperimentalCoroutinesApi::class)
    @Test
    fun `coroutines start eagerly by default`() = runTest {
        var started = false

        launch {
            started = true
        }

        advanceUntilIdle()

        assertTrue(started)
    }

What is this test proving?

It proves:

launch (and async) begin execution immediately unless told otherwise.

What does “eager” mean?

It means:

  • As soon as you call launch {}, it is scheduled.

  • You don’t need to call start().

  • It doesn’t wait for join() or await().

Start mode = CoroutineStart.DEFAULT.

Why do we call advanceUntilIdle()?

Because we’re using runTest, which uses a test scheduler.

advanceUntilIdle() tells the test engine:

“Run all scheduled coroutines until nothing is left.”

Then we assert:

assertTrue(started)

If coroutines were lazy, this would be false.

Why does eager start matter?

Because it affects ordering.

Example:

val job = launch { println("A") }

println("B")

The order of A and B is NOT guaranteed.

That’s because the coroutine starts immediately and may run before the next line.

By default, coroutines use CoroutineStart.DEFAULT, meaning they are scheduled immediately when created. They do not wait for join() or await() to begin execution.

No comments yet. Be the first to comment.