@file:DependsOn("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0") import kotlinx.coroutines.* data class Download(val name: String, val chunks: Int, val msPerChunk: Long) val downloads = listOf( Download("notes.txt", 2, 100), Download("photo.jpg", 4, 150), Download("song.mp3", 5, 200), Download("movie.mkv", 10, 250), ) val deadline = args.getOrNull(0)?.toLong() ?: 1200 val broken = args.getOrNull(1) suspend fun fetch(d: Download): Int { var received = 0 try { repeat(d.chunks) { delay(d.msPerChunk) received++ if (d.name == broken && received == d.chunks / 2) { throw IllegalStateException("${d.name} lost its connection") } } println("${d.name}: done") return received } finally { if (received < d.chunks) { println("${d.name}: stopped at $received of ${d.chunks}, partial file deleted") } } } runBlocking { val start = System.currentTimeMillis() try { val total = withTimeoutOrNull(deadline) { downloads.map { d -> async { fetch(d) } }.awaitAll().sum() } if (total == null) { println("deadline of $deadline ms reached") } else { println("all $total chunks received") } } catch (e: IllegalStateException) { println("gave up: ${e.message}") } println("finished in ${System.currentTimeMillis() - start} ms, nothing left running") } /* Try this next… 1. Wrap the downloads in supervisorScope { } inside withTimeoutOrNull, and catch the failure inside each async instead. Run with a broken file. Which downloads survive now? 2. Replace delay(d.msPerChunk) with Thread.sleep(d.msPerChunk). Run it with the default deadline. How long does the run take now, and what happened to movie.mkv? Then add ensureActive() at the top of the repeat and run it again. 3. Add a catch (e: Exception) block inside fetch that prints "retrying" and carries on. Break a file and watch what happens to its siblings. Then catch CancellationException first and rethrow it. 4. Put delay(500) inside the finally block, followed by a println. Does the println ever run? Wrap the delay in withContext(NonCancellable) { } and compare. 5. Start a fifth download with GlobalScope.launch instead of async. Make it the slowest. Is "nothing left running" still true? 6. Print Thread.currentThread().name inside fetch. How many threads did four downloads need? Then pass Dispatchers.Default to async and look again. 7. Make 10,000 downloads with List(10_000) { Download("file$it", 3, 100) }. How long does the batch take? Try the same count with Thread { } instead of async, if you're curious. */