I have a few hundred Java class instances that all need to complete their .calculate() method or die in 10 minutes. They will grab up the CPU and memory, so I'd like to only allow 5 (threads?) at once. I believe I'm close, but coming from a Java background I'm not yet familiar enough with kotlin coroutines (vs java ExecutorServices) to make this compile.
// ...my logic to create a stream of identical class type instances
// that all have a vanilla blocking .calculate():Double method...
// which I now want to (maybe?) map to Jobs
listOf(MyClass(1), MyClass(2), MyClass(1000))
.map {
launch(CommonPool) {
val errorRate: Double? = it?.calculate()
println("${it?.javaClass?.simpleName} $errorRate") // desired output
errorRate
}
}
.collect(Collectors.toList<Job>())
jobs.forEach {
println(it.join())
}
And then I think I need to wrap the calculate with a non-blocking calculate? Or a blocking, but timeout limited? Should that "runBlocking" be there? Better as a lambda in the above code?
fun MyClass.calculateTimeLimited(): Double = runBlocking {
withTimeout(TIMEOUT) {
this.calculate() // <-- doesn't compile! "this" is "CoroutineScope"