【发布时间】:2019-06-19 14:12:04
【问题描述】:
鉴于我们有一个 CompletableFuture f,在 kotlin 可暂停范围内,我们可以调用 f.await(),我们将暂停直到它完成。
我在实现带有签名 f.await(t) 的类似函数时遇到问题,该函数必须暂停最多 t 毫秒,或者如果未来在该持续时间内完成(以先发生者为准),则更快返回。
这是我尝试过的。
/**
* Suspend current method until future is done or specified duration expires,
* whichever happens first without cancelling the future.
* Returns true if its done, false otherwise.
*/
suspend fun <T> ListenableFuture<T>.await(duration: Long): Boolean {
val future = this
try {
withTimeout(duration) {
withContext(NonCancellable) { // this does not help either
future.await() // i do not expect the future itself to be cancelled
}
}
} catch (t: TimeoutCancellationException) {
// we expected this
} catch (e: Throwable) {
e.printStackTrace()
}
return future.isDone
}
fun main(args: Array<String>) = runBlocking<Unit> {
val future = GlobalScope.future {
try {
repeat(5) {
println("computing")
delay(500)
}
println("complete")
} finally {
withContext(NonCancellable) {
println("cancelling")
delay(500)
println("cancelled")
}
}
}
for (i in 0..10) {
if (future.await(2000)) {
println("checking : done")
} else {
println("checking : not done")
}
}
}
我还需要一个类似的功能来完成工作。但也许这个解决方案也可以帮助我......
输出是
computing
computing
computing
computing
checking : done
checking : done
checking : done
checking : done
cancelling
checking : done
checking : done
checking : done
checking : done
checking : done
checking : done
checking : done
【问题讨论】:
标签: java kotlin kotlin-coroutines coroutine completable-future