|
| 1 | +/* |
| 2 | + * Copyright 2016-2017 JetBrains s.r.o. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package kotlinx.coroutines.experimental.guava |
| 18 | + |
| 19 | +import com.google.common.util.concurrent.AbstractFuture |
| 20 | +import com.google.common.util.concurrent.FutureCallback |
| 21 | +import com.google.common.util.concurrent.Futures |
| 22 | +import com.google.common.util.concurrent.ListenableFuture |
| 23 | +import kotlinx.coroutines.experimental.* |
| 24 | +import kotlin.coroutines.experimental.Continuation |
| 25 | +import kotlin.coroutines.experimental.CoroutineContext |
| 26 | + |
| 27 | +/** |
| 28 | + * Starts new coroutine and returns its results an an implementation of [ListenableFuture]. |
| 29 | + * This coroutine builder uses [CommonPool] context by default. |
| 30 | + * |
| 31 | + * The running coroutine is cancelled when the resulting future is cancelled or otherwise completed. |
| 32 | + * If the [context] for the new coroutine is omitted or is explicitly specified but does not include a |
| 33 | + * coroutine interceptor, then [CommonPool] is used. |
| 34 | + * See [CoroutineDispatcher] for other standard [context] implementations that are provided by `kotlinx.coroutines`. |
| 35 | + * The [context][CoroutineScope.context] of the parent coroutine from its [scope][CoroutineScope] may be used, |
| 36 | + * in which case the [Job] of the resulting coroutine is a child of the job of the parent coroutine. |
| 37 | + * |
| 38 | + * By default, the coroutine is immediately scheduled for execution. |
| 39 | + * Other options can be specified via `start` parameter. See [CoroutineStart] for details. |
| 40 | + * A value of [CoroutineStart.LAZY] is not supported |
| 41 | + * (since `ListenableFuture` framework does not provide the corresponding capability) and |
| 42 | + * produces [IllegalArgumentException]. |
| 43 | + * |
| 44 | + * See [newCoroutineContext] for a description of debugging facilities that are available for newly created coroutine. |
| 45 | + * |
| 46 | + * @param context context of the coroutine |
| 47 | + * @param start coroutine start option |
| 48 | + * @param block the coroutine code |
| 49 | + */ |
| 50 | +public fun <T> future( |
| 51 | + context: CoroutineContext = CommonPool, |
| 52 | + start: CoroutineStart = CoroutineStart.DEFAULT, |
| 53 | + block: suspend CoroutineScope.() -> T |
| 54 | +): ListenableFuture<T> { |
| 55 | + require(!start.isLazy) { "$start start is not supported" } |
| 56 | + val newContext = newCoroutineContext(CommonPool + context) |
| 57 | + val job = Job(newContext[Job]) |
| 58 | + val future = ListenableFutureCoroutine<T>(newContext + job) |
| 59 | + job.cancelFutureOnCompletion(future) |
| 60 | + start(block, receiver=future, completion=future) // use the specified start strategy |
| 61 | + return future |
| 62 | +} |
| 63 | + |
| 64 | +private class ListenableFutureCoroutine<T>( |
| 65 | + override val context: CoroutineContext |
| 66 | +) : AbstractFuture<T>(), Continuation<T>, CoroutineScope { |
| 67 | + override val isActive: Boolean get() = context[Job]!!.isActive |
| 68 | + override fun resume(value: T) { set(value) } |
| 69 | + override fun resumeWithException(exception: Throwable) { setException(exception) } |
| 70 | + override fun interruptTask() { context[Job]!!.cancel() } |
| 71 | +} |
| 72 | + |
| 73 | +/** |
| 74 | + * Converts this deferred value to the instance of [ListenableFuture]. |
| 75 | + * The deferred value is cancelled when the resulting future is cancelled or otherwise completed. |
| 76 | + */ |
| 77 | +public fun <T> Deferred<T>.asListenableFuture(): ListenableFuture<T> = DeferredListenableFuture<T>(this) |
| 78 | + |
| 79 | +private class DeferredListenableFuture<T>( |
| 80 | + private val deferred: Deferred<T> |
| 81 | +) : AbstractFuture<T>() { |
| 82 | + init { |
| 83 | + deferred.invokeOnCompletion { |
| 84 | + try { |
| 85 | + set(deferred.getCompleted()) |
| 86 | + } catch (exception: Exception) { |
| 87 | + setException(exception) |
| 88 | + } |
| 89 | + } |
| 90 | + } |
| 91 | + override fun interruptTask() { deferred.cancel() } |
| 92 | +} |
| 93 | + |
| 94 | +/** |
| 95 | + * Awaits for completion of the future without blocking a thread. |
| 96 | + * |
| 97 | + * This suspending function is cancellable. |
| 98 | + * If the [Job] of the current coroutine is completed while this suspending function is waiting, this function |
| 99 | + * stops waiting for the future and immediately resumes with [CancellationException]. |
| 100 | + * |
| 101 | + * Note, that `ListenableFuture` does not support removal of installed listeners, so on cancellation of this wait |
| 102 | + * a few small objects will remain in the `ListenableFuture` list of listeners until the future completes. However, the |
| 103 | + * care is taken to clear the reference to the waiting coroutine itself, so that its memory can be released even if |
| 104 | + * the future never completes. |
| 105 | + */ |
| 106 | +public suspend fun <T> ListenableFuture<T>.await(): T = suspendCancellableCoroutine { cont: CancellableContinuation<T> -> |
| 107 | + val callback = ContinuationCallback(cont) |
| 108 | + Futures.addCallback(this, callback) |
| 109 | + cont.invokeOnCompletion { |
| 110 | + callback.cont = null // clear the reference to continuation from the future's callback |
| 111 | + } |
| 112 | +} |
| 113 | + |
| 114 | +private class ContinuationCallback<T>( |
| 115 | + @Volatile @JvmField var cont: Continuation<T>? |
| 116 | +) : FutureCallback<T> { |
| 117 | + override fun onSuccess(result: T?) { cont?.resume(result as T) } |
| 118 | + override fun onFailure(t: Throwable) { cont?.resumeWithException(t) } |
| 119 | +} |
0 commit comments