https://kotlinlang.org logo
Title
j

janvladimirmostert

11/10/2019, 5:25 PM
CompletableFuture.await()
, how much overhead does
await()
add in the scenario where the
CompletableFuture
is not yet done?
public suspend fun <T> CompletionStage<T>.await(): T {
    // fast path when CompletableFuture is already done (does not suspend)
    if (this is Future<*> && isDone()) {
        ...
    }

    // slow path -- suspend
    return suspendCancellableCoroutine { cont: CancellableContinuation<T> ->
        val consumer = ContinuationConsumer(cont)
        whenComplete(consumer)
        cont.invokeOnCancellation {
            // mayInterruptIfRunning is not used
            (this as? CompletableFuture<T>)?.cancel(false)
            consumer.cont = null // shall clear reference to continuation to aid GC
        }
    }
}
Is the overhead just extra class instances being created or is there more happening?
o

octylFractal

11/10/2019, 5:30 PM
there is a small amount of overhead for context switching when the coroutine is resumed, since the future likely isn't on the appropriate thread pool, and some function call overhead
🖖 1
j

janvladimirmostert

11/10/2019, 5:46 PM
ok, that sounds fairly reasonable - using this with an async database driver that returns CompletableFuture<Result>, the convenience of await definitely outweighs the little bit of extra overhead here