1 /* 2 * Copyright 2016-2020 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 { future.cancel(false) } 17 * ``` 18 * 19 * @suppress **This an internal API and should not be used from general code.** 20 */ 21 @InternalCoroutinesApi cancelFutureOnCompletionnull22public fun Job.cancelFutureOnCompletion(future: Future<*>): DisposableHandle = 23 invokeOnCompletion(handler = CancelFutureOnCompletion(this, future)) // TODO make it work only on cancellation as well? 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 { future.cancel(false) } 30 * ``` 31 */ 32 public fun CancellableContinuation<*>.cancelFutureOnCancellation(future: Future<*>): Unit = 33 invokeOnCancellation(handler = CancelFutureOnCancel(future)) 34 35 private class CancelFutureOnCompletion( 36 job: Job, 37 private val future: Future<*> 38 ) : JobNode<Job>(job) { 39 override fun invoke(cause: Throwable?) { 40 // Don't interrupt when cancelling future on completion, because no one is going to reset this 41 // interruption flag and it will cause spurious failures elsewhere 42 future.cancel(false) 43 } 44 override fun toString() = "CancelFutureOnCompletion[$future]" 45 } 46 47 private class CancelFutureOnCancel(private val future: Future<*>) : CancelHandler() { invokenull48 override fun invoke(cause: Throwable?) { 49 // Don't interrupt when cancelling future on completion, because no one is going to reset this 50 // interruption flag and it will cause spurious failures elsewhere 51 future.cancel(false) 52 } toStringnull53 override fun toString() = "CancelFutureOnCancel[$future]" 54 } 55