Skip to content

Commit 20dbd9f

Browse files
committed
Fast-path for isDone in ListenableFuture#await, stop using deprecated API
1 parent 87f2faa commit 20dbd9f

File tree

1 file changed

+14
-5
lines changed
  • integration/kotlinx-coroutines-guava/src/main/kotlin/kotlinx/coroutines/experimental/guava

1 file changed

+14
-5
lines changed

integration/kotlinx-coroutines-guava/src/main/kotlin/kotlinx/coroutines/experimental/guava/ListenableFuture.kt

+14-5
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ package kotlinx.coroutines.experimental.guava
1818

1919
import com.google.common.util.concurrent.*
2020
import kotlinx.coroutines.experimental.*
21+
import java.util.concurrent.*
2122
import kotlin.coroutines.experimental.*
2223

2324
/**
@@ -126,11 +127,19 @@ private class DeferredListenableFuture<T>(
126127
* care is taken to clear the reference to the waiting coroutine itself, so that its memory can be released even if
127128
* the future never completes.
128129
*/
129-
public suspend fun <T> ListenableFuture<T>.await(): T = suspendCancellableCoroutine { cont: CancellableContinuation<T> ->
130-
val callback = ContinuationCallback(cont)
131-
Futures.addCallback(this, callback)
132-
cont.invokeOnCancellation {
133-
callback.cont = null // clear the reference to continuation from the future's callback
130+
public suspend fun <T> ListenableFuture<T>.await(): T {
131+
try {
132+
if (isDone) return get() as T
133+
} catch (e: ExecutionException) {
134+
throw e.cause ?: e // unwrap original cause from ExecutionException
135+
}
136+
137+
return suspendCancellableCoroutine { cont: CancellableContinuation<T> ->
138+
val callback = ContinuationCallback(cont)
139+
Futures.addCallback(this, callback, MoreExecutors.directExecutor())
140+
cont.invokeOnCancellation {
141+
callback.cont = null // clear the reference to continuation from the future's callback
142+
}
134143
}
135144
}
136145

0 commit comments

Comments
 (0)