diff options
Diffstat (limited to 'integration/kotlinx-coroutines-jdk8/src/future/Future.kt')
-rw-r--r-- | integration/kotlinx-coroutines-jdk8/src/future/Future.kt | 21 |
1 files changed, 13 insertions, 8 deletions
diff --git a/integration/kotlinx-coroutines-jdk8/src/future/Future.kt b/integration/kotlinx-coroutines-jdk8/src/future/Future.kt index b3b45e9d..caf2a3c3 100644 --- a/integration/kotlinx-coroutines-jdk8/src/future/Future.kt +++ b/integration/kotlinx-coroutines-jdk8/src/future/Future.kt @@ -48,7 +48,7 @@ public fun <T> CoroutineScope.future( private class CompletableFutureCoroutine<T>( context: CoroutineContext, private val future: CompletableFuture<T> -) : AbstractCoroutine<T>(context), BiConsumer<T?, Throwable?> { +) : AbstractCoroutine<T>(context, initParentJob = true, active = true), BiConsumer<T?, Throwable?> { override fun accept(value: T?, exception: Throwable?) { cancel() } @@ -126,13 +126,18 @@ public fun <T> CompletionStage<T>.asDeferred(): Deferred<T> { } val result = CompletableDeferred<T>() whenComplete { value, exception -> - if (exception == null) { - // the future has completed normally - result.complete(value) - } else { - // the future has completed with an exception, unwrap it consistently with fast path - // Note: In the fast-path the implementation of CompletableFuture.get() does unwrapping - result.completeExceptionally((exception as? CompletionException)?.cause ?: exception) + try { + if (exception == null) { + // the future has completed normally + result.complete(value) + } else { + // the future has completed with an exception, unwrap it consistently with fast path + // Note: In the fast-path the implementation of CompletableFuture.get() does unwrapping + result.completeExceptionally((exception as? CompletionException)?.cause ?: exception) + } + } catch (e: Throwable) { + // We come here iff the internals of Deferred threw an exception during its completion + handleCoroutineException(EmptyCoroutineContext, e) } } result.cancelFutureOnCompletion(future) |