• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
3  */
4 
5 @file:JvmMultifileClass
6 @file:JvmName("JobKt")
7 
8 package kotlinx.coroutines
9 
10 import java.util.concurrent.*
11 
12 /**
13  * Cancels a specified [future] when this job is cancelled.
14  * This is a shortcut for the following code with slightly more efficient implementation (one fewer object created).
15  * ```
16  * invokeOnCompletion { if (it != null) future.cancel(false) }
17  * ```
18  *
19  * @suppress **This an internal API and should not be used from general code.**
20  */
21 @InternalCoroutinesApi
cancelFutureOnCompletionnull22 public fun Job.cancelFutureOnCompletion(future: Future<*>): DisposableHandle =
23     invokeOnCompletion(handler = CancelFutureOnCompletion(future))
24 
25 /**
26  * Cancels a specified [future] when this job is cancelled.
27  * This is a shortcut for the following code with slightly more efficient implementation (one fewer object created).
28  * ```
29  * invokeOnCancellation { if (it != null) future.cancel(false) }
30  * ```
31  */
32 public fun CancellableContinuation<*>.cancelFutureOnCancellation(future: Future<*>): Unit =
33     invokeOnCancellation(handler = CancelFutureOnCancel(future))
34 
35 private class CancelFutureOnCompletion(
36     private val future: Future<*>
37 ) : JobNode() {
38     override fun invoke(cause: Throwable?) {
39         // Don't interrupt when cancelling future on completion, because no one is going to reset this
40         // interruption flag and it will cause spurious failures elsewhere
41         if (cause != null) future.cancel(false)
42     }
43 }
44 
45 private class CancelFutureOnCancel(private val future: Future<*>) : CancelHandler()  {
invokenull46     override fun invoke(cause: Throwable?) {
47         // Don't interrupt when cancelling future on completion, because no one is going to reset this
48         // interruption flag and it will cause spurious failures elsewhere
49         if (cause != null)  future.cancel(false)
50     }
toStringnull51     override fun toString() = "CancelFutureOnCancel[$future]"
52 }
53