Read the code carefully before you run it.
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?
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.
Before you get a hint: what have you tried, and where exactly are you stuck?
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?