lm-sistemi-software-distrib.../src/main/kotlin/util/future/Future.kt

67 lines
1.4 KiB
Kotlin

package util.future
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
interface Future<T> {
suspend fun get(): T
suspend fun get(timeout: Long): T?
fun isDone(): Boolean
fun cancel()
fun isCancelled(): Boolean
}
class CoFuture<T>(private val func: suspend () -> T) : Future<T> {
private var value: T? = null
private var job = GlobalScope.launch {
value = func()
}
override suspend fun get(): T {
job.join()
return value!!
}
override suspend fun get(timeout: Long): T? {
delay(timeout)
return value
}
override fun isDone(): Boolean = job.isCompleted
override fun cancel() {
job.cancel()
}
override fun isCancelled(): Boolean = job.isCancelled
}
fun <T> future(func: suspend () -> T): Future<T> = CoFuture(func)
fun <T> delayedEcho(value: T, delay: Long = 1000): Future<T> = future {
delay(delay)
value
}
class MathFuture {
fun add(a: Int, b: Int): Future<Int> = future { a + b }
}
fun main() = runBlocking {
val future = delayedEcho(42, delay = 2000)
println("do other work.")
println(future.get())
val math = MathFuture()
val sums = (0 until 100)
.map { math.add(it, it * 2) }
println("End all sums.")
sums.forEach {
println(it.get())
}
}