1. Why Asynchronous Programming?

[THEORY]

[PREDICT]

Read the code carefully before you run it.

prediction.kt
import kotlin.system.measureTimeMillis

fun loadProfile(): String {
    Thread.sleep(500)
    return "Profile loaded"
}

fun loadSettings(): String {
    Thread.sleep(500)
    return "Settings loaded"
}

fun main() {
    val duration = measureTimeMillis {
        println(loadProfile())
        println(loadSettings())
    }
    println("Total time: $duration ms")
}

loadProfile() and loadSettings() each block for 500ms. How long does the whole block take, roughly, and why?

[TASK]

An order system checks three things at checkout: the user profile, the cart and the stock level. Each check takes time (simulated with Thread.sleep). Add the missing function checkStockLevel (like the other two, with Thread.sleep(800) and return value true) and call all three checks one after another in the main block. Measure the total duration with measureTimeMillis and print it.

task.kt
import kotlin.system.measureTimeMillis fun checkProfile(): Boolean { Thread.sleep(300) return true } fun checkCart(): Boolean { Thread.sleep(500) return true } // TODO: fun checkStockLevel(): Boolean { ... } fun main() { val duration = measureTimeMillis { // TODO: call all three checks } println("Checkout check finished in $duration ms") }

Before you get a hint: what have you tried, and where exactly are you stuck?

[COMPREHENSION CHECK]

1. Why is an extra thread per slow operation not an infinitely scalable solution?

2. What is a central problem of callback-based asynchronous code?

3. Roughly how long does the measured block in the sample code take, and why?