blob: 9fb0bc85d549fc6753a9fced560a9b038b67af9e [file] [log] [blame]
Roman Elizarovf106ff32017-05-17 12:22:14 +03001/*
Roman Elizarov1f74a2d2018-06-29 19:19:45 +03002 * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
Roman Elizarovf106ff32017-05-17 12:22:14 +03003 */
4
5package kotlinx.coroutines.experimental.guava
6
Roman Elizarova4b56932018-03-13 17:59:48 +03007import com.google.common.util.concurrent.*
Roman Elizarovf106ff32017-05-17 12:22:14 +03008import kotlinx.coroutines.experimental.*
Vsevolod Tolstopyatov20dbd9f2018-05-07 20:08:20 +03009import java.util.concurrent.*
Roman Elizarova4b56932018-03-13 17:59:48 +030010import kotlin.coroutines.experimental.*
Roman Elizarovf106ff32017-05-17 12:22:14 +030011
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 Elizarovc0d559b2017-09-28 14:27:05 +030017 *
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 Elizarovc7d10a42018-03-13 18:28:42 +030020 * The [coroutineContext] of the parent coroutine may be used,
Roman Elizarovf106ff32017-05-17 12:22:14 +030021 * in which case the [Job] of the resulting coroutine is a child of the job of the parent coroutine.
Roman Elizarove8f694e2017-11-28 10:12:00 +030022 * The parent job may be also explicitly specified using [parent] parameter.
23 *
Roman Elizarovc0d559b2017-09-28 14:27:05 +030024 * If the context does not have any dispatcher nor any other [ContinuationInterceptor], then [DefaultDispatcher] is used.
Roman Elizarovf106ff32017-05-17 12:22:14 +030025 *
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 Elizarovc0d559b2017-09-28 14:27:05 +030034 * @param context context of the coroutine. The default value is [DefaultDispatcher].
35 * @param start coroutine start option. The default value is [CoroutineStart.DEFAULT].
Roman Elizarove8f694e2017-11-28 10:12:00 +030036 * @param parent explicitly specifies the parent job, overrides job from the [context] (if any).
Roman Elizarova4b56932018-03-13 17:59:48 +030037 * @param onCompletion optional completion handler for the coroutine (see [Job.invokeOnCompletion]).
Roman Elizarovc0d559b2017-09-28 14:27:05 +030038 * @param block the coroutine code.
Roman Elizarovf106ff32017-05-17 12:22:14 +030039 */
40public fun <T> future(
Roman Elizarovc0d559b2017-09-28 14:27:05 +030041 context: CoroutineContext = DefaultDispatcher,
Roman Elizarovf106ff32017-05-17 12:22:14 +030042 start: CoroutineStart = CoroutineStart.DEFAULT,
Roman Elizarove8f694e2017-11-28 10:12:00 +030043 parent: Job? = null,
Roman Elizarova4b56932018-03-13 17:59:48 +030044 onCompletion: CompletionHandler? = null,
Roman Elizarovf106ff32017-05-17 12:22:14 +030045 block: suspend CoroutineScope.() -> T
46): ListenableFuture<T> {
47 require(!start.isLazy) { "$start start is not supported" }
Roman Elizarove8f694e2017-11-28 10:12:00 +030048 val newContext = newCoroutineContext(context, parent)
Roman Elizarovf106ff32017-05-17 12:22:14 +030049 val job = Job(newContext[Job])
50 val future = ListenableFutureCoroutine<T>(newContext + job)
51 job.cancelFutureOnCompletion(future)
Roman Elizarova4b56932018-03-13 17:59:48 +030052 if (onCompletion != null) job.invokeOnCompletion(handler = onCompletion)
Roman Elizarovf106ff32017-05-17 12:22:14 +030053 start(block, receiver=future, completion=future) // use the specified start strategy
54 return future
55}
56
Roman Elizarove8f694e2017-11-28 10:12:00 +030057/** @suppress **Deprecated**: Binary compatibility */
58@Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN)
59public fun <T> future(
60 context: CoroutineContext = DefaultDispatcher,
61 start: CoroutineStart = CoroutineStart.DEFAULT,
Roman Elizarova4b56932018-03-13 17:59:48 +030062 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)
68public fun <T> future(
69 context: CoroutineContext = DefaultDispatcher,
70 start: CoroutineStart = CoroutineStart.DEFAULT,
Roman Elizarove8f694e2017-11-28 10:12:00 +030071 block: suspend CoroutineScope.() -> T
72): ListenableFuture<T> =
73 future(context, start, block = block)
74
Roman Elizarovf106ff32017-05-17 12:22:14 +030075private class ListenableFutureCoroutine<T>(
76 override val context: CoroutineContext
77) : AbstractFuture<T>(), Continuation<T>, CoroutineScope {
Roman Elizarov43e3af72017-07-21 16:01:31 +030078 override val coroutineContext: CoroutineContext get() = context
Roman Elizarovf106ff32017-05-17 12:22:14 +030079 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 */
89public fun <T> Deferred<T>.asListenableFuture(): ListenableFuture<T> = DeferredListenableFuture<T>(this)
90
91private 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 Elizarovd82b3a92017-06-23 21:52:08 +0300110 * If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting, this function
Roman Elizarovf106ff32017-05-17 12:22:14 +0300111 * 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 Tolstopyatov20dbd9f2018-05-07 20:08:20 +0300118public 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 Elizarovf106ff32017-05-17 12:22:14 +0300131 }
132}
133
134private class ContinuationCallback<T>(
135 @Volatile @JvmField var cont: Continuation<T>?
136) : FutureCallback<T> {
Roman Elizarov19bf4d52017-07-11 14:43:28 +0300137 @Suppress("UNCHECKED_CAST")
Roman Elizarovf106ff32017-05-17 12:22:14 +0300138 override fun onSuccess(result: T?) { cont?.resume(result as T) }
139 override fun onFailure(t: Throwable) { cont?.resumeWithException(t) }
140}