Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 14 / Topic 7 of 7

Putting it together: a concurrent task runner

Every tool from this part, aimed at something a real backend genuinely needs: run a batch of independent tasks concurrently, isolate each one's failure or timeout from the rest, and never block an OS thread doing it.

data class TaskResult<T>(val taskId: String, val value: T? = null, val error: String? = null) {
    val succeeded: Boolean get() = error == null
}

class TaskRunner(private val timeoutMs: Long = 500) {

    suspend fun <T> runAll(taskIds: List<String>, task: suspend (String) -> T): List<TaskResult<T>> =
        supervisorScope {
            taskIds.map { id ->
                async(Dispatchers.Default) {
                    try {
                        val value = withTimeout(timeoutMs) { task(id) }
                        TaskResult(id, value = value)
                    } catch (e: TimeoutCancellationException) {
                        TaskResult<T>(id, error = "timed out after ${timeoutMs}ms")
                    } catch (e: Exception) {
                        TaskResult<T>(id, error = e.message ?: "unknown error")
                    }
                }
            }.awaitAll()
        }
}

suspend fun printPackingSlip(orderId: String): String {
    val workMs = if (orderId == "O-1004") 800L else 80L + orderId.last().code.toLong()
    delay(workMs)                               // simulated work, never Thread.sleep
    if (orderId == "O-1002") throw IllegalStateException("printer jammed")
    return "$orderId: packing slip printed"
}
val orderIds = listOf("O-1001", "O-1002", "O-1003", "O-1004", "O-1005")
val runner = TaskRunner(timeoutMs = 300)

val startedAt = System.currentTimeMillis()
val results = runner.runAll(orderIds, ::printPackingSlip)
val elapsed = System.currentTimeMillis() - startedAt

results.forEach { result ->
    if (result.succeeded) println("OK   ${result.value}")
    else println("FAIL ${result.taskId}: ${result.error}")
}

val okCount = results.count { it.succeeded }
println("Finished ${orderIds.size} tasks on a shared thread pool in ${elapsed}ms (varies)")
println("$okCount/${orderIds.size} succeeded")
$ kotlinc 07_concurrent_task_runner.kt -cp ../libs/kotlinx-coroutines-core-jvm-1.11.0.jar -include-runtime -d 07_concurrent_task_runner.jar
$ java -cp "07_concurrent_task_runner.jar:../libs/kotlinx-coroutines-core-jvm-1.11.0.jar" _07_concurrent_task_runnerKt
OK   O-1001: packing slip printed
FAIL O-1002: printer jammed
OK   O-1003: packing slip printed
FAIL O-1004: timed out after 300ms
OK   O-1005: packing slip printed
Finished 5 tasks on a shared thread pool in 310ms (varies)
3/5 succeeded

A few design choices worth noticing:

  • runAll is generic over T (Part 13) -- it would work identically for a List<Int> result or a List<Receipt> result, not just String.
  • supervisorScope + a per-task try/catch means O-1002's real failure and O-1004's timeout never touch O-1001, O-1003 or O-1005 -- each task reports its own outcome in a TaskResult instead of one bad apple failing the whole batch.
  • Every "wait" in printPackingSlip is delay, not Thread.sleep -- five tasks here means five coroutines sharing Dispatchers.Default's small thread pool, not five dedicated threads, the same property Section 5 measured directly with 1,000 coroutines.

Full program: examples/07_concurrent_task_runner.kt.

Done here? The practice set for Part 14 — including the solutions — is on the part page.

Search the guide