Roman Elizarov | f106ff3 | 2017-05-17 12:22:14 +0300 | [diff] [blame] | 1 | /* |
Roman Elizarov | 1f74a2d | 2018-06-29 19:19:45 +0300 | [diff] [blame^] | 2 | * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. |
Roman Elizarov | f106ff3 | 2017-05-17 12:22:14 +0300 | [diff] [blame] | 3 | */ |
| 4 | |
| 5 | package kotlinx.coroutines.experimental.guava |
| 6 | |
Roman Elizarov | a4b5693 | 2018-03-13 17:59:48 +0300 | [diff] [blame] | 7 | import com.google.common.util.concurrent.* |
Roman Elizarov | f106ff3 | 2017-05-17 12:22:14 +0300 | [diff] [blame] | 8 | import kotlinx.coroutines.experimental.* |
Vsevolod Tolstopyatov | 20dbd9f | 2018-05-07 20:08:20 +0300 | [diff] [blame] | 9 | import java.util.concurrent.* |
Roman Elizarov | a4b5693 | 2018-03-13 17:59:48 +0300 | [diff] [blame] | 10 | import kotlin.coroutines.experimental.* |
Roman Elizarov | f106ff3 | 2017-05-17 12:22:14 +0300 | [diff] [blame] | 11 | |
| 12 | /** |
| 13 | * Starts new coroutine and returns its results an an implementation of [ListenableFuture]. |
| 14 | * This coroutine builder uses [CommonPool] context by default. |
| 15 | * |
| 16 | * The running coroutine is cancelled when the resulting future is cancelled or otherwise completed. |
Roman Elizarov | c0d559b | 2017-09-28 14:27:05 +0300 | [diff] [blame] | 17 | * |
| 18 | * The [context] for the new coroutine can be explicitly specified. |
| 19 | * See [CoroutineDispatcher] for the standard context implementations that are provided by `kotlinx.coroutines`. |
Roman Elizarov | c7d10a4 | 2018-03-13 18:28:42 +0300 | [diff] [blame] | 20 | * The [coroutineContext] of the parent coroutine may be used, |
Roman Elizarov | f106ff3 | 2017-05-17 12:22:14 +0300 | [diff] [blame] | 21 | * in which case the [Job] of the resulting coroutine is a child of the job of the parent coroutine. |
Roman Elizarov | e8f694e | 2017-11-28 10:12:00 +0300 | [diff] [blame] | 22 | * The parent job may be also explicitly specified using [parent] parameter. |
| 23 | * |
Roman Elizarov | c0d559b | 2017-09-28 14:27:05 +0300 | [diff] [blame] | 24 | * If the context does not have any dispatcher nor any other [ContinuationInterceptor], then [DefaultDispatcher] is used. |
Roman Elizarov | f106ff3 | 2017-05-17 12:22:14 +0300 | [diff] [blame] | 25 | * |
| 26 | * By default, the coroutine is immediately scheduled for execution. |
| 27 | * Other options can be specified via `start` parameter. See [CoroutineStart] for details. |
| 28 | * A value of [CoroutineStart.LAZY] is not supported |
| 29 | * (since `ListenableFuture` framework does not provide the corresponding capability) and |
| 30 | * produces [IllegalArgumentException]. |
| 31 | * |
| 32 | * See [newCoroutineContext] for a description of debugging facilities that are available for newly created coroutine. |
| 33 | * |
Roman Elizarov | c0d559b | 2017-09-28 14:27:05 +0300 | [diff] [blame] | 34 | * @param context context of the coroutine. The default value is [DefaultDispatcher]. |
| 35 | * @param start coroutine start option. The default value is [CoroutineStart.DEFAULT]. |
Roman Elizarov | e8f694e | 2017-11-28 10:12:00 +0300 | [diff] [blame] | 36 | * @param parent explicitly specifies the parent job, overrides job from the [context] (if any). |
Roman Elizarov | a4b5693 | 2018-03-13 17:59:48 +0300 | [diff] [blame] | 37 | * @param onCompletion optional completion handler for the coroutine (see [Job.invokeOnCompletion]). |
Roman Elizarov | c0d559b | 2017-09-28 14:27:05 +0300 | [diff] [blame] | 38 | * @param block the coroutine code. |
Roman Elizarov | f106ff3 | 2017-05-17 12:22:14 +0300 | [diff] [blame] | 39 | */ |
| 40 | public fun <T> future( |
Roman Elizarov | c0d559b | 2017-09-28 14:27:05 +0300 | [diff] [blame] | 41 | context: CoroutineContext = DefaultDispatcher, |
Roman Elizarov | f106ff3 | 2017-05-17 12:22:14 +0300 | [diff] [blame] | 42 | start: CoroutineStart = CoroutineStart.DEFAULT, |
Roman Elizarov | e8f694e | 2017-11-28 10:12:00 +0300 | [diff] [blame] | 43 | parent: Job? = null, |
Roman Elizarov | a4b5693 | 2018-03-13 17:59:48 +0300 | [diff] [blame] | 44 | onCompletion: CompletionHandler? = null, |
Roman Elizarov | f106ff3 | 2017-05-17 12:22:14 +0300 | [diff] [blame] | 45 | block: suspend CoroutineScope.() -> T |
| 46 | ): ListenableFuture<T> { |
| 47 | require(!start.isLazy) { "$start start is not supported" } |
Roman Elizarov | e8f694e | 2017-11-28 10:12:00 +0300 | [diff] [blame] | 48 | val newContext = newCoroutineContext(context, parent) |
Roman Elizarov | f106ff3 | 2017-05-17 12:22:14 +0300 | [diff] [blame] | 49 | val job = Job(newContext[Job]) |
| 50 | val future = ListenableFutureCoroutine<T>(newContext + job) |
| 51 | job.cancelFutureOnCompletion(future) |
Roman Elizarov | a4b5693 | 2018-03-13 17:59:48 +0300 | [diff] [blame] | 52 | if (onCompletion != null) job.invokeOnCompletion(handler = onCompletion) |
Roman Elizarov | f106ff3 | 2017-05-17 12:22:14 +0300 | [diff] [blame] | 53 | start(block, receiver=future, completion=future) // use the specified start strategy |
| 54 | return future |
| 55 | } |
| 56 | |
Roman Elizarov | e8f694e | 2017-11-28 10:12:00 +0300 | [diff] [blame] | 57 | /** @suppress **Deprecated**: Binary compatibility */ |
| 58 | @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) |
| 59 | public fun <T> future( |
| 60 | context: CoroutineContext = DefaultDispatcher, |
| 61 | start: CoroutineStart = CoroutineStart.DEFAULT, |
Roman Elizarov | a4b5693 | 2018-03-13 17:59:48 +0300 | [diff] [blame] | 62 | parent: Job? = null, |
| 63 | block: suspend CoroutineScope.() -> T |
| 64 | ): ListenableFuture<T> = future(context, start, parent, block = block) |
| 65 | |
| 66 | /** @suppress **Deprecated**: Binary compatibility */ |
| 67 | @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) |
| 68 | public fun <T> future( |
| 69 | context: CoroutineContext = DefaultDispatcher, |
| 70 | start: CoroutineStart = CoroutineStart.DEFAULT, |
Roman Elizarov | e8f694e | 2017-11-28 10:12:00 +0300 | [diff] [blame] | 71 | block: suspend CoroutineScope.() -> T |
| 72 | ): ListenableFuture<T> = |
| 73 | future(context, start, block = block) |
| 74 | |
Roman Elizarov | f106ff3 | 2017-05-17 12:22:14 +0300 | [diff] [blame] | 75 | private class ListenableFutureCoroutine<T>( |
| 76 | override val context: CoroutineContext |
| 77 | ) : AbstractFuture<T>(), Continuation<T>, CoroutineScope { |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 78 | override val coroutineContext: CoroutineContext get() = context |
Roman Elizarov | f106ff3 | 2017-05-17 12:22:14 +0300 | [diff] [blame] | 79 | override val isActive: Boolean get() = context[Job]!!.isActive |
| 80 | override fun resume(value: T) { set(value) } |
| 81 | override fun resumeWithException(exception: Throwable) { setException(exception) } |
| 82 | override fun interruptTask() { context[Job]!!.cancel() } |
| 83 | } |
| 84 | |
| 85 | /** |
| 86 | * Converts this deferred value to the instance of [ListenableFuture]. |
| 87 | * The deferred value is cancelled when the resulting future is cancelled or otherwise completed. |
| 88 | */ |
| 89 | public fun <T> Deferred<T>.asListenableFuture(): ListenableFuture<T> = DeferredListenableFuture<T>(this) |
| 90 | |
| 91 | private class DeferredListenableFuture<T>( |
| 92 | private val deferred: Deferred<T> |
| 93 | ) : AbstractFuture<T>() { |
| 94 | init { |
| 95 | deferred.invokeOnCompletion { |
| 96 | try { |
| 97 | set(deferred.getCompleted()) |
| 98 | } catch (exception: Exception) { |
| 99 | setException(exception) |
| 100 | } |
| 101 | } |
| 102 | } |
| 103 | override fun interruptTask() { deferred.cancel() } |
| 104 | } |
| 105 | |
| 106 | /** |
| 107 | * Awaits for completion of the future without blocking a thread. |
| 108 | * |
| 109 | * This suspending function is cancellable. |
Roman Elizarov | d82b3a9 | 2017-06-23 21:52:08 +0300 | [diff] [blame] | 110 | * If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting, this function |
Roman Elizarov | f106ff3 | 2017-05-17 12:22:14 +0300 | [diff] [blame] | 111 | * stops waiting for the future and immediately resumes with [CancellationException]. |
| 112 | * |
| 113 | * Note, that `ListenableFuture` does not support removal of installed listeners, so on cancellation of this wait |
| 114 | * a few small objects will remain in the `ListenableFuture` list of listeners until the future completes. However, the |
| 115 | * care is taken to clear the reference to the waiting coroutine itself, so that its memory can be released even if |
| 116 | * the future never completes. |
| 117 | */ |
Vsevolod Tolstopyatov | 20dbd9f | 2018-05-07 20:08:20 +0300 | [diff] [blame] | 118 | public suspend fun <T> ListenableFuture<T>.await(): T { |
| 119 | try { |
| 120 | if (isDone) return get() as T |
| 121 | } catch (e: ExecutionException) { |
| 122 | throw e.cause ?: e // unwrap original cause from ExecutionException |
| 123 | } |
| 124 | |
| 125 | return suspendCancellableCoroutine { cont: CancellableContinuation<T> -> |
| 126 | val callback = ContinuationCallback(cont) |
| 127 | Futures.addCallback(this, callback, MoreExecutors.directExecutor()) |
| 128 | cont.invokeOnCancellation { |
| 129 | callback.cont = null // clear the reference to continuation from the future's callback |
| 130 | } |
Roman Elizarov | f106ff3 | 2017-05-17 12:22:14 +0300 | [diff] [blame] | 131 | } |
| 132 | } |
| 133 | |
| 134 | private class ContinuationCallback<T>( |
| 135 | @Volatile @JvmField var cont: Continuation<T>? |
| 136 | ) : FutureCallback<T> { |
Roman Elizarov | 19bf4d5 | 2017-07-11 14:43:28 +0300 | [diff] [blame] | 137 | @Suppress("UNCHECKED_CAST") |
Roman Elizarov | f106ff3 | 2017-05-17 12:22:14 +0300 | [diff] [blame] | 138 | override fun onSuccess(result: T?) { cont?.resume(result as T) } |
| 139 | override fun onFailure(t: Throwable) { cont?.resumeWithException(t) } |
| 140 | } |