Roman Elizarov | 660c2d7 | 2020-02-14 13:18:37 +0300 | [diff] [blame^] | 1 | <!--- TEST_NAME ExceptionsGuideTest --> |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 2 | |
Prendota | b8a559d | 2018-11-30 16:24:23 +0300 | [diff] [blame] | 3 | **Table of contents** |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 4 | |
| 5 | <!--- TOC --> |
| 6 | |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 7 | * [Exception Handling](#exception-handling) |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 8 | * [Exception propagation](#exception-propagation) |
| 9 | * [CoroutineExceptionHandler](#coroutineexceptionhandler) |
| 10 | * [Cancellation and exceptions](#cancellation-and-exceptions) |
| 11 | * [Exceptions aggregation](#exceptions-aggregation) |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 12 | * [Supervision](#supervision) |
| 13 | * [Supervision job](#supervision-job) |
| 14 | * [Supervision scope](#supervision-scope) |
| 15 | * [Exceptions in supervised coroutines](#exceptions-in-supervised-coroutines) |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 16 | |
Roman Elizarov | 660c2d7 | 2020-02-14 13:18:37 +0300 | [diff] [blame^] | 17 | <!--- END --> |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 18 | |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 19 | ## Exception Handling |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 20 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 21 | |
| 22 | This section covers exception handling and cancellation on exceptions. |
| 23 | We already know that cancelled coroutine throws [CancellationException] in suspension points and that it |
| 24 | is ignored by coroutines machinery. But what happens if an exception is thrown during cancellation or multiple children of the same |
| 25 | coroutine throw an exception? |
| 26 | |
| 27 | ### Exception propagation |
| 28 | |
| 29 | Coroutine builders come in two flavors: propagating exceptions automatically ([launch] and [actor]) or |
| 30 | exposing them to users ([async] and [produce]). |
Kenji Otsuka | 4c76c6f | 2018-10-12 07:27:08 +0900 | [diff] [blame] | 31 | The former treat exceptions as unhandled, similar to Java's `Thread.uncaughtExceptionHandler`, |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 32 | while the latter are relying on the user to consume the final |
| 33 | exception, for example via [await][Deferred.await] or [receive][ReceiveChannel.receive] |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 34 | ([produce] and [receive][ReceiveChannel.receive] are covered later in [Channels](https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/channels.md) section). |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 35 | |
Inego | 6da0ccd | 2019-04-21 14:26:40 +0700 | [diff] [blame] | 36 | It can be demonstrated by a simple example that creates coroutines in the [GlobalScope]: |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 37 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 38 | <div class="sample" markdown="1" theme="idea" data-highlight-only> |
| 39 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 40 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 41 | import kotlinx.coroutines.* |
| 42 | |
| 43 | fun main() = runBlocking { |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 44 | val job = GlobalScope.launch { |
| 45 | println("Throwing exception from launch") |
| 46 | throw IndexOutOfBoundsException() // Will be printed to the console by Thread.defaultUncaughtExceptionHandler |
| 47 | } |
| 48 | job.join() |
| 49 | println("Joined failed job") |
| 50 | val deferred = GlobalScope.async { |
| 51 | println("Throwing exception from async") |
| 52 | throw ArithmeticException() // Nothing is printed, relying on user to call await |
| 53 | } |
| 54 | try { |
| 55 | deferred.await() |
| 56 | println("Unreached") |
| 57 | } catch (e: ArithmeticException) { |
| 58 | println("Caught ArithmeticException") |
| 59 | } |
| 60 | } |
| 61 | ``` |
| 62 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 63 | </div> |
| 64 | |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 65 | > You can get full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-exceptions-01.kt). |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 66 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 67 | The output of this code is (with [debug](https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/coroutine-context-and-dispatchers.md#debugging-coroutines-and-threads)): |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 68 | |
| 69 | ```text |
| 70 | Throwing exception from launch |
Roman Elizarov | 303708b | 2018-09-28 12:20:49 +0300 | [diff] [blame] | 71 | Exception in thread "DefaultDispatcher-worker-2 @coroutine#2" java.lang.IndexOutOfBoundsException |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 72 | Joined failed job |
| 73 | Throwing exception from async |
| 74 | Caught ArithmeticException |
| 75 | ``` |
| 76 | |
| 77 | <!--- TEST EXCEPTION--> |
| 78 | |
| 79 | ### CoroutineExceptionHandler |
| 80 | |
| 81 | But what if one does not want to print all exceptions to the console? |
| 82 | [CoroutineExceptionHandler] context element is used as generic `catch` block of coroutine where custom logging or exception handling may take place. |
| 83 | It is similar to using [`Thread.uncaughtExceptionHandler`](https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#setUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler)). |
| 84 | |
| 85 | On JVM it is possible to redefine global exception handler for all coroutines by registering [CoroutineExceptionHandler] via |
| 86 | [`ServiceLoader`](https://docs.oracle.com/javase/8/docs/api/java/util/ServiceLoader.html). |
| 87 | Global exception handler is similar to |
| 88 | [`Thread.defaultUncaughtExceptionHandler`](https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#setDefaultUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler)) |
| 89 | which is used when no more specific handlers are registered. |
| 90 | On Android, `uncaughtExceptionPreHandler` is installed as a global coroutine exception handler. |
| 91 | |
| 92 | [CoroutineExceptionHandler] is invoked only on exceptions which are not expected to be handled by the user, |
| 93 | so registering it in [async] builder and the like of it has no effect. |
| 94 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 95 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 96 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 97 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 98 | import kotlinx.coroutines.* |
| 99 | |
| 100 | fun main() = runBlocking { |
| 101 | //sampleStart |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 102 | val handler = CoroutineExceptionHandler { _, exception -> |
| 103 | println("Caught $exception") |
| 104 | } |
| 105 | val job = GlobalScope.launch(handler) { |
| 106 | throw AssertionError() |
| 107 | } |
| 108 | val deferred = GlobalScope.async(handler) { |
| 109 | throw ArithmeticException() // Nothing will be printed, relying on user to call deferred.await() |
| 110 | } |
| 111 | joinAll(job, deferred) |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 112 | //sampleEnd |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 113 | } |
| 114 | ``` |
| 115 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 116 | </div> |
| 117 | |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 118 | > You can get full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-exceptions-02.kt). |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 119 | |
| 120 | The output of this code is: |
| 121 | |
| 122 | ```text |
| 123 | Caught java.lang.AssertionError |
| 124 | ``` |
| 125 | |
| 126 | <!--- TEST--> |
| 127 | |
| 128 | ### Cancellation and exceptions |
| 129 | |
| 130 | Cancellation is tightly bound with exceptions. Coroutines internally use `CancellationException` for cancellation, these |
| 131 | exceptions are ignored by all handlers, so they should be used only as the source of additional debug information, which can |
| 132 | be obtained by `catch` block. |
Marek Langiewicz | b6dd65c | 2019-10-18 12:10:27 +0200 | [diff] [blame] | 133 | When a coroutine is cancelled using [Job.cancel], it terminates, but it does not cancel its parent. |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 134 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 135 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 136 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 137 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 138 | import kotlinx.coroutines.* |
| 139 | |
| 140 | fun main() = runBlocking { |
| 141 | //sampleStart |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 142 | val job = launch { |
| 143 | val child = launch { |
| 144 | try { |
| 145 | delay(Long.MAX_VALUE) |
| 146 | } finally { |
| 147 | println("Child is cancelled") |
| 148 | } |
| 149 | } |
| 150 | yield() |
| 151 | println("Cancelling child") |
| 152 | child.cancel() |
| 153 | child.join() |
| 154 | yield() |
| 155 | println("Parent is not cancelled") |
| 156 | } |
| 157 | job.join() |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 158 | //sampleEnd |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 159 | } |
| 160 | ``` |
| 161 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 162 | </div> |
| 163 | |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 164 | > You can get full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-exceptions-03.kt). |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 165 | |
| 166 | The output of this code is: |
| 167 | |
| 168 | ```text |
| 169 | Cancelling child |
| 170 | Child is cancelled |
| 171 | Parent is not cancelled |
| 172 | ``` |
| 173 | |
| 174 | <!--- TEST--> |
| 175 | |
andrethiele | f605b26 | 2019-10-03 12:18:37 +0200 | [diff] [blame] | 176 | If a coroutine encounters an exception other than `CancellationException`, it cancels its parent with that exception. |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 177 | This behaviour cannot be overridden and is used to provide stable coroutines hierarchies for |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 178 | [structured concurrency](https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/composing-suspending-functions.md#structured-concurrency-with-async) which do not depend on |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 179 | [CoroutineExceptionHandler] implementation. |
| 180 | The original exception is handled by the parent when all its children terminate. |
| 181 | |
| 182 | > This also a reason why, in these examples, [CoroutineExceptionHandler] is always installed to a coroutine |
| 183 | that is created in [GlobalScope]. It does not make sense to install an exception handler to a coroutine that |
| 184 | is launched in the scope of the main [runBlocking], since the main coroutine is going to be always cancelled |
| 185 | when its child completes with exception despite the installed handler. |
| 186 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 187 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 188 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 189 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 190 | import kotlinx.coroutines.* |
| 191 | |
| 192 | fun main() = runBlocking { |
巳月 | 55a48fb | 2018-10-31 18:27:47 +0800 | [diff] [blame] | 193 | //sampleStart |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 194 | val handler = CoroutineExceptionHandler { _, exception -> |
| 195 | println("Caught $exception") |
| 196 | } |
| 197 | val job = GlobalScope.launch(handler) { |
| 198 | launch { // the first child |
| 199 | try { |
| 200 | delay(Long.MAX_VALUE) |
| 201 | } finally { |
| 202 | withContext(NonCancellable) { |
| 203 | println("Children are cancelled, but exception is not handled until all children terminate") |
| 204 | delay(100) |
| 205 | println("The first child finished its non cancellable block") |
| 206 | } |
| 207 | } |
| 208 | } |
| 209 | launch { // the second child |
| 210 | delay(10) |
| 211 | println("Second child throws an exception") |
| 212 | throw ArithmeticException() |
| 213 | } |
| 214 | } |
| 215 | job.join() |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 216 | //sampleEnd |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 217 | } |
| 218 | ``` |
| 219 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 220 | </div> |
| 221 | |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 222 | > You can get full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-exceptions-04.kt). |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 223 | |
| 224 | The output of this code is: |
| 225 | |
| 226 | ```text |
| 227 | Second child throws an exception |
| 228 | Children are cancelled, but exception is not handled until all children terminate |
| 229 | The first child finished its non cancellable block |
| 230 | Caught java.lang.ArithmeticException |
| 231 | ``` |
| 232 | <!--- TEST--> |
| 233 | |
| 234 | ### Exceptions aggregation |
| 235 | |
| 236 | What happens if multiple children of a coroutine throw an exception? |
| 237 | The general rule is "the first exception wins", so the first thrown exception is exposed to the handler. |
| 238 | But that may cause lost exceptions, for example if coroutine throws an exception in its `finally` block. |
| 239 | So, additional exceptions are suppressed. |
| 240 | |
| 241 | > One of the solutions would have been to report each exception separately, |
| 242 | but then [Deferred.await] should have had the same mechanism to avoid behavioural inconsistency and this |
Andrii Chubko | 5768067 | 2018-10-17 03:56:57 +0300 | [diff] [blame] | 243 | would cause implementation details of a coroutines (whether it had delegated parts of its work to its children or not) |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 244 | to leak to its exception handler. |
| 245 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 246 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 247 | <!--- INCLUDE |
Roman Elizarov | 0950dfa | 2018-07-13 10:33:25 +0300 | [diff] [blame] | 248 | import kotlinx.coroutines.exceptions.* |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 249 | --> |
| 250 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 251 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 252 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 253 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 254 | import kotlinx.coroutines.* |
| 255 | import java.io.* |
| 256 | |
| 257 | fun main() = runBlocking { |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 258 | val handler = CoroutineExceptionHandler { _, exception -> |
Roman Elizarov | 54617b7 | 2018-09-28 17:42:44 +0300 | [diff] [blame] | 259 | println("Caught $exception with suppressed ${exception.suppressed.contentToString()}") |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 260 | } |
| 261 | val job = GlobalScope.launch(handler) { |
| 262 | launch { |
| 263 | try { |
| 264 | delay(Long.MAX_VALUE) |
| 265 | } finally { |
| 266 | throw ArithmeticException() |
| 267 | } |
| 268 | } |
| 269 | launch { |
Roman Elizarov | 938c5e9 | 2018-09-28 16:10:09 +0300 | [diff] [blame] | 270 | delay(100) |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 271 | throw IOException() |
| 272 | } |
| 273 | delay(Long.MAX_VALUE) |
| 274 | } |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 275 | job.join() |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 276 | } |
| 277 | ``` |
| 278 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 279 | </div> |
| 280 | |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 281 | > You can get full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-exceptions-05.kt). |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 282 | |
Roman Elizarov | 54617b7 | 2018-09-28 17:42:44 +0300 | [diff] [blame] | 283 | > Note: This above code will work properly only on JDK7+ that supports `suppressed` exceptions |
| 284 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 285 | The output of this code is: |
| 286 | |
| 287 | ```text |
| 288 | Caught java.io.IOException with suppressed [java.lang.ArithmeticException] |
| 289 | ``` |
| 290 | |
| 291 | <!--- TEST--> |
| 292 | |
| 293 | > Note, this mechanism currently works only on Java version 1.7+. |
| 294 | Limitation on JS and Native is temporary and will be fixed in the future. |
| 295 | |
| 296 | Cancellation exceptions are transparent and unwrapped by default: |
| 297 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 298 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 299 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 300 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 301 | import kotlinx.coroutines.* |
| 302 | import java.io.* |
| 303 | |
| 304 | fun main() = runBlocking { |
| 305 | //sampleStart |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 306 | val handler = CoroutineExceptionHandler { _, exception -> |
| 307 | println("Caught original $exception") |
| 308 | } |
| 309 | val job = GlobalScope.launch(handler) { |
| 310 | val inner = launch { |
| 311 | launch { |
| 312 | launch { |
| 313 | throw IOException() |
| 314 | } |
| 315 | } |
| 316 | } |
| 317 | try { |
| 318 | inner.join() |
Vsevolod Tolstopyatov | a2d8088 | 2018-09-24 19:51:49 +0300 | [diff] [blame] | 319 | } catch (e: CancellationException) { |
| 320 | println("Rethrowing CancellationException with original cause") |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 321 | throw e |
| 322 | } |
| 323 | } |
| 324 | job.join() |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 325 | //sampleEnd |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 326 | } |
| 327 | ``` |
| 328 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 329 | </div> |
| 330 | |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 331 | > You can get full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-exceptions-06.kt). |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 332 | |
| 333 | The output of this code is: |
| 334 | |
| 335 | ```text |
Vsevolod Tolstopyatov | a2d8088 | 2018-09-24 19:51:49 +0300 | [diff] [blame] | 336 | Rethrowing CancellationException with original cause |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 337 | Caught original java.io.IOException |
| 338 | ``` |
| 339 | <!--- TEST--> |
Roman Elizarov | 99c28aa | 2018-09-23 18:42:36 +0300 | [diff] [blame] | 340 | |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 341 | ### Supervision |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 342 | |
| 343 | As we have studied before, cancellation is a bidirectional relationship propagating through the whole |
| 344 | coroutines hierarchy. But what if unidirectional cancellation is required? |
| 345 | |
Aaron Stacy | 2fe443b | 2019-03-24 20:00:36 -0500 | [diff] [blame] | 346 | A good example of such a requirement is a UI component with the job defined in its scope. If any of the UI's child tasks |
| 347 | have failed, it is not always necessary to cancel (effectively kill) the whole UI component, |
| 348 | but if UI component is destroyed (and its job is cancelled), then it is necessary to fail all child jobs as their results are no longer required. |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 349 | |
| 350 | Another example is a server process that spawns several children jobs and needs to _supervise_ |
| 351 | their execution, tracking their failures and restarting just those children jobs that had failed. |
| 352 | |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 353 | #### Supervision job |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 354 | |
| 355 | For these purposes [SupervisorJob][SupervisorJob()] can be used. It is similar to a regular [Job][Job()] with the only exception that cancellation is propagated |
| 356 | only downwards. It is easy to demonstrate with an example: |
| 357 | |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 358 | <div class="sample" markdown="1" theme="idea" data-highlight-only> |
| 359 | |
| 360 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 361 | import kotlinx.coroutines.* |
| 362 | |
| 363 | fun main() = runBlocking { |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 364 | val supervisor = SupervisorJob() |
| 365 | with(CoroutineScope(coroutineContext + supervisor)) { |
Vadym O | d981966 | 2018-10-19 16:16:57 -0500 | [diff] [blame] | 366 | // launch the first child -- its exception is ignored for this example (don't do this in practice!) |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 367 | val firstChild = launch(CoroutineExceptionHandler { _, _ -> }) { |
| 368 | println("First child is failing") |
| 369 | throw AssertionError("First child is cancelled") |
| 370 | } |
| 371 | // launch the second child |
| 372 | val secondChild = launch { |
| 373 | firstChild.join() |
| 374 | // Cancellation of the first child is not propagated to the second child |
| 375 | println("First child is cancelled: ${firstChild.isCancelled}, but second one is still active") |
| 376 | try { |
| 377 | delay(Long.MAX_VALUE) |
| 378 | } finally { |
| 379 | // But cancellation of the supervisor is propagated |
| 380 | println("Second child is cancelled because supervisor is cancelled") |
| 381 | } |
| 382 | } |
| 383 | // wait until the first child fails & completes |
| 384 | firstChild.join() |
| 385 | println("Cancelling supervisor") |
| 386 | supervisor.cancel() |
| 387 | secondChild.join() |
| 388 | } |
| 389 | } |
| 390 | ``` |
| 391 | |
| 392 | </div> |
| 393 | |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 394 | > You can get full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-supervision-01.kt). |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 395 | |
| 396 | The output of this code is: |
| 397 | |
| 398 | ```text |
| 399 | First child is failing |
| 400 | First child is cancelled: true, but second one is still active |
| 401 | Cancelling supervisor |
| 402 | Second child is cancelled because supervisor is cancelled |
| 403 | ``` |
| 404 | <!--- TEST--> |
| 405 | |
| 406 | |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 407 | #### Supervision scope |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 408 | |
| 409 | For *scoped* concurrency [supervisorScope] can be used instead of [coroutineScope] for the same purpose. It propagates cancellation |
| 410 | only in one direction and cancels all children only if it has failed itself. It also waits for all children before completion |
| 411 | just like [coroutineScope] does. |
| 412 | |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 413 | <div class="sample" markdown="1" theme="idea" data-highlight-only> |
| 414 | |
| 415 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 416 | import kotlin.coroutines.* |
| 417 | import kotlinx.coroutines.* |
| 418 | |
| 419 | fun main() = runBlocking { |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 420 | try { |
| 421 | supervisorScope { |
| 422 | val child = launch { |
| 423 | try { |
| 424 | println("Child is sleeping") |
| 425 | delay(Long.MAX_VALUE) |
| 426 | } finally { |
| 427 | println("Child is cancelled") |
| 428 | } |
| 429 | } |
| 430 | // Give our child a chance to execute and print using yield |
| 431 | yield() |
| 432 | println("Throwing exception from scope") |
| 433 | throw AssertionError() |
| 434 | } |
| 435 | } catch(e: AssertionError) { |
| 436 | println("Caught assertion error") |
| 437 | } |
| 438 | } |
| 439 | ``` |
| 440 | |
| 441 | </div> |
| 442 | |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 443 | > You can get full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-supervision-02.kt). |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 444 | |
| 445 | The output of this code is: |
| 446 | |
| 447 | ```text |
| 448 | Child is sleeping |
| 449 | Throwing exception from scope |
| 450 | Child is cancelled |
| 451 | Caught assertion error |
| 452 | ``` |
| 453 | <!--- TEST--> |
| 454 | |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 455 | #### Exceptions in supervised coroutines |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 456 | |
| 457 | Another crucial difference between regular and supervisor jobs is exception handling. |
| 458 | Every child should handle its exceptions by itself via exception handling mechanisms. |
| 459 | This difference comes from the fact that child's failure is not propagated to the parent. |
| 460 | |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 461 | <div class="sample" markdown="1" theme="idea" data-highlight-only> |
| 462 | |
| 463 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 464 | import kotlin.coroutines.* |
| 465 | import kotlinx.coroutines.* |
| 466 | |
| 467 | fun main() = runBlocking { |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 468 | val handler = CoroutineExceptionHandler { _, exception -> |
| 469 | println("Caught $exception") |
| 470 | } |
| 471 | supervisorScope { |
| 472 | val child = launch(handler) { |
| 473 | println("Child throws an exception") |
| 474 | throw AssertionError() |
| 475 | } |
| 476 | println("Scope is completing") |
| 477 | } |
| 478 | println("Scope is completed") |
| 479 | } |
| 480 | ``` |
| 481 | |
| 482 | </div> |
| 483 | |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 484 | > You can get full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-supervision-03.kt). |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 485 | |
| 486 | The output of this code is: |
| 487 | |
| 488 | ```text |
| 489 | Scope is completing |
| 490 | Child throws an exception |
| 491 | Caught java.lang.AssertionError |
| 492 | Scope is completed |
| 493 | ``` |
| 494 | <!--- TEST--> |
| 495 | |
Roman Elizarov | 99c28aa | 2018-09-23 18:42:36 +0300 | [diff] [blame] | 496 | <!--- MODULE kotlinx-coroutines-core --> |
Roman Elizarov | 0950dfa | 2018-07-13 10:33:25 +0300 | [diff] [blame] | 497 | <!--- INDEX kotlinx.coroutines --> |
| 498 | [CancellationException]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-cancellation-exception/index.html |
| 499 | [launch]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/launch.html |
| 500 | [async]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/async.html |
| 501 | [Deferred.await]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-deferred/await.html |
| 502 | [GlobalScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-global-scope/index.html |
| 503 | [CoroutineExceptionHandler]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-exception-handler/index.html |
| 504 | [Job.cancel]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/cancel.html |
| 505 | [runBlocking]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/run-blocking.html |
| 506 | [SupervisorJob()]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-supervisor-job.html |
| 507 | [Job()]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job.html |
| 508 | [supervisorScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/supervisor-scope.html |
| 509 | [coroutineScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/coroutine-scope.html |
| 510 | <!--- INDEX kotlinx.coroutines.channels --> |
| 511 | [actor]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.channels/actor.html |
| 512 | [produce]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.channels/produce.html |
| 513 | [ReceiveChannel.receive]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.channels/-receive-channel/receive.html |
Roman Elizarov | 99c28aa | 2018-09-23 18:42:36 +0300 | [diff] [blame] | 514 | <!--- END --> |