Skip to content

Instantly share code, notes, and snippets.

@ylegall
Created February 2, 2019 20:15
Show Gist options
  • Save ylegall/14eb8ac41d16250508151801bf54f56f to your computer and use it in GitHub Desktop.
Save ylegall/14eb8ac41d16250508151801bf54f56f to your computer and use it in GitHub Desktop.
run n tasks in parallel and get results that finish within a timeout
package aoc2015
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
import kotlinx.coroutines.withTimeoutOrNull
import kotlin.random.Random
import kotlin.system.measureTimeMillis
data class Task(val id: Int, val duration: Long)
private suspend fun Task.run(): Int {
println("starting $this")
val elapsed = measureTimeMillis { delay(duration) }
println("finished $this in $elapsed ms")
return id
}
private suspend fun processTasksAsyncWithTimeout(tasks: List<Task>): List<Int> = coroutineScope {
val results = arrayListOf<Int>()
try {
withTimeout(1000) {
tasks.forEach {
launch {
val result = it.run()
results.add(result)
}
}
}
} catch (e: TimeoutCancellationException) {
println(e)
}
results
}
private suspend fun processTasksAsyncWithTimeout2(tasks: List<Task>): List<Int> = coroutineScope {
tasks.map {
async { withTimeoutOrNull(1000) { it.run() } }
}.mapNotNull {
it.await()
}
}
// https://medium.com/@elizarov/kotlin-coroutines-a-deeper-look-180536305c3f
fun main() = runBlocking {
val tasks = (1 .. 10).map { Task(it, Random.nextLong(2000)) }
val startTime = System.currentTimeMillis()
// val results = processTasksAsyncWithTimeout(tasks)
val results = processTasksAsyncWithTimeout2(tasks)
val elapsed = System.currentTimeMillis() - startTime
println("---------")
results.forEach { println(it) }
println("finished ${results.size} tasks in $elapsed ms")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment