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