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. |
| 148 | When a coroutine is cancelled using [Job.cancel] without a cause, it terminates, but it does not cancel its parent. |
| 149 | Cancelling without cause is a mechanism for parent to cancel its children without cancelling itself. |
| 150 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 151 | <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] | 152 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 153 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 154 | import kotlinx.coroutines.* |
| 155 | |
| 156 | fun main() = runBlocking { |
| 157 | //sampleStart |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 158 | val job = launch { |
| 159 | val child = launch { |
| 160 | try { |
| 161 | delay(Long.MAX_VALUE) |
| 162 | } finally { |
| 163 | println("Child is cancelled") |
| 164 | } |
| 165 | } |
| 166 | yield() |
| 167 | println("Cancelling child") |
| 168 | child.cancel() |
| 169 | child.join() |
| 170 | yield() |
| 171 | println("Parent is not cancelled") |
| 172 | } |
| 173 | job.join() |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 174 | //sampleEnd |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 175 | } |
| 176 | ``` |
| 177 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 178 | </div> |
| 179 | |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 180 | > 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] | 181 | |
| 182 | The output of this code is: |
| 183 | |
| 184 | ```text |
| 185 | Cancelling child |
| 186 | Child is cancelled |
| 187 | Parent is not cancelled |
| 188 | ``` |
| 189 | |
| 190 | <!--- TEST--> |
| 191 | |
| 192 | If a coroutine encounters exception other than `CancellationException`, it cancels its parent with that exception. |
| 193 | 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] | 194 | [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] | 195 | [CoroutineExceptionHandler] implementation. |
| 196 | The original exception is handled by the parent when all its children terminate. |
| 197 | |
| 198 | > This also a reason why, in these examples, [CoroutineExceptionHandler] is always installed to a coroutine |
| 199 | that is created in [GlobalScope]. It does not make sense to install an exception handler to a coroutine that |
| 200 | is launched in the scope of the main [runBlocking], since the main coroutine is going to be always cancelled |
| 201 | when its child completes with exception despite the installed handler. |
| 202 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 203 | <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] | 204 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 205 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 206 | import kotlinx.coroutines.* |
| 207 | |
| 208 | fun main() = runBlocking { |
巳月 | 55a48fb | 2018-10-31 18:27:47 +0800 | [diff] [blame] | 209 | //sampleStart |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 210 | val handler = CoroutineExceptionHandler { _, exception -> |
| 211 | println("Caught $exception") |
| 212 | } |
| 213 | val job = GlobalScope.launch(handler) { |
| 214 | launch { // the first child |
| 215 | try { |
| 216 | delay(Long.MAX_VALUE) |
| 217 | } finally { |
| 218 | withContext(NonCancellable) { |
| 219 | println("Children are cancelled, but exception is not handled until all children terminate") |
| 220 | delay(100) |
| 221 | println("The first child finished its non cancellable block") |
| 222 | } |
| 223 | } |
| 224 | } |
| 225 | launch { // the second child |
| 226 | delay(10) |
| 227 | println("Second child throws an exception") |
| 228 | throw ArithmeticException() |
| 229 | } |
| 230 | } |
| 231 | job.join() |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 232 | //sampleEnd |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 233 | } |
| 234 | ``` |
| 235 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 236 | </div> |
| 237 | |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 238 | > 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] | 239 | |
| 240 | The output of this code is: |
| 241 | |
| 242 | ```text |
| 243 | Second child throws an exception |
| 244 | Children are cancelled, but exception is not handled until all children terminate |
| 245 | The first child finished its non cancellable block |
| 246 | Caught java.lang.ArithmeticException |
| 247 | ``` |
| 248 | <!--- TEST--> |
| 249 | |
| 250 | ### Exceptions aggregation |
| 251 | |
| 252 | What happens if multiple children of a coroutine throw an exception? |
| 253 | The general rule is "the first exception wins", so the first thrown exception is exposed to the handler. |
| 254 | But that may cause lost exceptions, for example if coroutine throws an exception in its `finally` block. |
| 255 | So, additional exceptions are suppressed. |
| 256 | |
| 257 | > One of the solutions would have been to report each exception separately, |
| 258 | 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] | 259 | 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] | 260 | to leak to its exception handler. |
| 261 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 262 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 263 | <!--- INCLUDE |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 264 | |
Roman Elizarov | 0950dfa | 2018-07-13 10:33:25 +0300 | [diff] [blame] | 265 | import kotlinx.coroutines.exceptions.* |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 266 | --> |
| 267 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 268 | <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] | 269 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 270 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 271 | import kotlinx.coroutines.* |
| 272 | import java.io.* |
| 273 | |
| 274 | fun main() = runBlocking { |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 275 | val handler = CoroutineExceptionHandler { _, exception -> |
Roman Elizarov | 54617b7 | 2018-09-28 17:42:44 +0300 | [diff] [blame] | 276 | println("Caught $exception with suppressed ${exception.suppressed.contentToString()}") |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 277 | } |
| 278 | val job = GlobalScope.launch(handler) { |
| 279 | launch { |
| 280 | try { |
| 281 | delay(Long.MAX_VALUE) |
| 282 | } finally { |
| 283 | throw ArithmeticException() |
| 284 | } |
| 285 | } |
| 286 | launch { |
Roman Elizarov | 938c5e9 | 2018-09-28 16:10:09 +0300 | [diff] [blame] | 287 | delay(100) |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 288 | throw IOException() |
| 289 | } |
| 290 | delay(Long.MAX_VALUE) |
| 291 | } |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 292 | job.join() |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 293 | } |
| 294 | ``` |
| 295 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 296 | </div> |
| 297 | |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 298 | > 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] | 299 | |
Roman Elizarov | 54617b7 | 2018-09-28 17:42:44 +0300 | [diff] [blame] | 300 | > Note: This above code will work properly only on JDK7+ that supports `suppressed` exceptions |
| 301 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 302 | The output of this code is: |
| 303 | |
| 304 | ```text |
| 305 | Caught java.io.IOException with suppressed [java.lang.ArithmeticException] |
| 306 | ``` |
| 307 | |
| 308 | <!--- TEST--> |
| 309 | |
| 310 | > Note, this mechanism currently works only on Java version 1.7+. |
| 311 | Limitation on JS and Native is temporary and will be fixed in the future. |
| 312 | |
| 313 | Cancellation exceptions are transparent and unwrapped by default: |
| 314 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 315 | <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] | 316 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 317 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 318 | import kotlinx.coroutines.* |
| 319 | import java.io.* |
| 320 | |
| 321 | fun main() = runBlocking { |
| 322 | //sampleStart |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 323 | val handler = CoroutineExceptionHandler { _, exception -> |
| 324 | println("Caught original $exception") |
| 325 | } |
| 326 | val job = GlobalScope.launch(handler) { |
| 327 | val inner = launch { |
| 328 | launch { |
| 329 | launch { |
| 330 | throw IOException() |
| 331 | } |
| 332 | } |
| 333 | } |
| 334 | try { |
| 335 | inner.join() |
Vsevolod Tolstopyatov | a2d8088 | 2018-09-24 19:51:49 +0300 | [diff] [blame] | 336 | } catch (e: CancellationException) { |
| 337 | println("Rethrowing CancellationException with original cause") |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 338 | throw e |
| 339 | } |
| 340 | } |
| 341 | job.join() |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 342 | //sampleEnd |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 343 | } |
| 344 | ``` |
| 345 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 346 | </div> |
| 347 | |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 348 | > 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] | 349 | |
| 350 | The output of this code is: |
| 351 | |
| 352 | ```text |
Vsevolod Tolstopyatov | a2d8088 | 2018-09-24 19:51:49 +0300 | [diff] [blame] | 353 | Rethrowing CancellationException with original cause |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 354 | Caught original java.io.IOException |
| 355 | ``` |
| 356 | <!--- TEST--> |
Roman Elizarov | 99c28aa | 2018-09-23 18:42:36 +0300 | [diff] [blame] | 357 | |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame^] | 358 | ### Supervision |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 359 | |
| 360 | As we have studied before, cancellation is a bidirectional relationship propagating through the whole |
| 361 | coroutines hierarchy. But what if unidirectional cancellation is required? |
| 362 | |
Aaron Stacy | 2fe443b | 2019-03-24 20:00:36 -0500 | [diff] [blame] | 363 | 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 |
| 364 | have failed, it is not always necessary to cancel (effectively kill) the whole UI component, |
| 365 | 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] | 366 | |
| 367 | Another example is a server process that spawns several children jobs and needs to _supervise_ |
| 368 | their execution, tracking their failures and restarting just those children jobs that had failed. |
| 369 | |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame^] | 370 | #### Supervision job |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 371 | |
| 372 | For these purposes [SupervisorJob][SupervisorJob()] can be used. It is similar to a regular [Job][Job()] with the only exception that cancellation is propagated |
| 373 | only downwards. It is easy to demonstrate with an example: |
| 374 | |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 375 | <div class="sample" markdown="1" theme="idea" data-highlight-only> |
| 376 | |
| 377 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 378 | import kotlinx.coroutines.* |
| 379 | |
| 380 | fun main() = runBlocking { |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 381 | val supervisor = SupervisorJob() |
| 382 | with(CoroutineScope(coroutineContext + supervisor)) { |
Vadym O | d981966 | 2018-10-19 16:16:57 -0500 | [diff] [blame] | 383 | // 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] | 384 | val firstChild = launch(CoroutineExceptionHandler { _, _ -> }) { |
| 385 | println("First child is failing") |
| 386 | throw AssertionError("First child is cancelled") |
| 387 | } |
| 388 | // launch the second child |
| 389 | val secondChild = launch { |
| 390 | firstChild.join() |
| 391 | // Cancellation of the first child is not propagated to the second child |
| 392 | println("First child is cancelled: ${firstChild.isCancelled}, but second one is still active") |
| 393 | try { |
| 394 | delay(Long.MAX_VALUE) |
| 395 | } finally { |
| 396 | // But cancellation of the supervisor is propagated |
| 397 | println("Second child is cancelled because supervisor is cancelled") |
| 398 | } |
| 399 | } |
| 400 | // wait until the first child fails & completes |
| 401 | firstChild.join() |
| 402 | println("Cancelling supervisor") |
| 403 | supervisor.cancel() |
| 404 | secondChild.join() |
| 405 | } |
| 406 | } |
| 407 | ``` |
| 408 | |
| 409 | </div> |
| 410 | |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 411 | > 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] | 412 | |
| 413 | The output of this code is: |
| 414 | |
| 415 | ```text |
| 416 | First child is failing |
| 417 | First child is cancelled: true, but second one is still active |
| 418 | Cancelling supervisor |
| 419 | Second child is cancelled because supervisor is cancelled |
| 420 | ``` |
| 421 | <!--- TEST--> |
| 422 | |
| 423 | |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame^] | 424 | #### Supervision scope |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 425 | |
| 426 | For *scoped* concurrency [supervisorScope] can be used instead of [coroutineScope] for the same purpose. It propagates cancellation |
| 427 | only in one direction and cancels all children only if it has failed itself. It also waits for all children before completion |
| 428 | just like [coroutineScope] does. |
| 429 | |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 430 | <div class="sample" markdown="1" theme="idea" data-highlight-only> |
| 431 | |
| 432 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 433 | import kotlin.coroutines.* |
| 434 | import kotlinx.coroutines.* |
| 435 | |
| 436 | fun main() = runBlocking { |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 437 | try { |
| 438 | supervisorScope { |
| 439 | val child = launch { |
| 440 | try { |
| 441 | println("Child is sleeping") |
| 442 | delay(Long.MAX_VALUE) |
| 443 | } finally { |
| 444 | println("Child is cancelled") |
| 445 | } |
| 446 | } |
| 447 | // Give our child a chance to execute and print using yield |
| 448 | yield() |
| 449 | println("Throwing exception from scope") |
| 450 | throw AssertionError() |
| 451 | } |
| 452 | } catch(e: AssertionError) { |
| 453 | println("Caught assertion error") |
| 454 | } |
| 455 | } |
| 456 | ``` |
| 457 | |
| 458 | </div> |
| 459 | |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 460 | > 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] | 461 | |
| 462 | The output of this code is: |
| 463 | |
| 464 | ```text |
| 465 | Child is sleeping |
| 466 | Throwing exception from scope |
| 467 | Child is cancelled |
| 468 | Caught assertion error |
| 469 | ``` |
| 470 | <!--- TEST--> |
| 471 | |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame^] | 472 | #### Exceptions in supervised coroutines |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 473 | |
| 474 | Another crucial difference between regular and supervisor jobs is exception handling. |
| 475 | Every child should handle its exceptions by itself via exception handling mechanisms. |
| 476 | This difference comes from the fact that child's failure is not propagated to the parent. |
| 477 | |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 478 | <div class="sample" markdown="1" theme="idea" data-highlight-only> |
| 479 | |
| 480 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 481 | import kotlin.coroutines.* |
| 482 | import kotlinx.coroutines.* |
| 483 | |
| 484 | fun main() = runBlocking { |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 485 | val handler = CoroutineExceptionHandler { _, exception -> |
| 486 | println("Caught $exception") |
| 487 | } |
| 488 | supervisorScope { |
| 489 | val child = launch(handler) { |
| 490 | println("Child throws an exception") |
| 491 | throw AssertionError() |
| 492 | } |
| 493 | println("Scope is completing") |
| 494 | } |
| 495 | println("Scope is completed") |
| 496 | } |
| 497 | ``` |
| 498 | |
| 499 | </div> |
| 500 | |
Inego | 69c26df | 2019-04-21 14:51:25 +0700 | [diff] [blame] | 501 | > 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] | 502 | |
| 503 | The output of this code is: |
| 504 | |
| 505 | ```text |
| 506 | Scope is completing |
| 507 | Child throws an exception |
| 508 | Caught java.lang.AssertionError |
| 509 | Scope is completed |
| 510 | ``` |
| 511 | <!--- TEST--> |
| 512 | |
Roman Elizarov | 99c28aa | 2018-09-23 18:42:36 +0300 | [diff] [blame] | 513 | <!--- MODULE kotlinx-coroutines-core --> |
Roman Elizarov | 0950dfa | 2018-07-13 10:33:25 +0300 | [diff] [blame] | 514 | <!--- INDEX kotlinx.coroutines --> |
| 515 | [CancellationException]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-cancellation-exception/index.html |
| 516 | [launch]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/launch.html |
| 517 | [async]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/async.html |
| 518 | [Deferred.await]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-deferred/await.html |
| 519 | [GlobalScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-global-scope/index.html |
| 520 | [CoroutineExceptionHandler]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-exception-handler/index.html |
| 521 | [Job.cancel]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/cancel.html |
| 522 | [runBlocking]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/run-blocking.html |
| 523 | [SupervisorJob()]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-supervisor-job.html |
| 524 | [Job()]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job.html |
| 525 | [supervisorScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/supervisor-scope.html |
| 526 | [coroutineScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/coroutine-scope.html |
| 527 | <!--- INDEX kotlinx.coroutines.channels --> |
| 528 | [actor]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.channels/actor.html |
| 529 | [produce]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.channels/produce.html |
| 530 | [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] | 531 | <!--- END --> |