Serge
06/14/2019, 7:11 PMfun main() {
val list = listOf("1", "2", "3", "4", "5") //listOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15" )
val threadPool = Executors.newFixedThreadPool(3)!!
//val threadPoolAsCouritineDispatcher = threadPool.asCoroutineDispatcher()
fun <A> Iterable<A>.parallelIterWithExecutorAttempt(
exec: ExecutorService,
block: (A) -> Unit) {
this.asIterable().map { exec.submit { block(it) } }.forEach { it.get() }
}
suspend fun work(item: String) =
withContext(Dispatchers.Default) {
//<https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-core/jvm/test/guide/example-cancel-07.kt>
//<https://medium.com/@elizarov/blocking-threads-suspending-coroutines-d33e11bf4761>
val result = withTimeoutOrNull(timeMillis = 130L) {
repeat(10) { i ->
println("ListItem=$item -> I'm sleeping on iteration -> $i ...")
delay(50L)
//Thread.sleep(50L) //to mimic non-couroutine external I/O operaion
}
println("process=$item ->Done") // will get cancelled before it produces this result
}
}
println("parallelIterWithExecutor")
runBlocking {
list.parallelIterWithExecutorAttempt(threadPool) { item ->
launch {
work(item)
} //timeout...
}
}
println("end of life for process")
}
louiscad
06/14/2019, 7:34 PMSerge
06/14/2019, 8:57 PMlouiscad
06/14/2019, 9:01 PMGlobalScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) { … }
) before attempting to resume the continuation.