`CompletableFuture.await()`, how much overhead doe...
# coroutines
j
CompletableFuture.await()
, how much overhead does
await()
add in the scenario where the
CompletableFuture
is not yet done?
Copy code
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
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
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