Roman Elizarov | 43e9011 | 2017-05-10 11:25:20 +0300 | [diff] [blame] | 1 | <!--- INCLUDE .*/example-([a-z]+)-([0-9a-z]+)\.kt |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 2 | /* |
Roman Elizarov | 1f74a2d | 2018-06-29 19:19:45 +0300 | [diff] [blame] | 3 | * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 4 | */ |
Roman Elizarov | f16fd27 | 2017-02-07 11:26:00 +0300 | [diff] [blame] | 5 | |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 6 | // This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit. |
Roman Elizarov | a9687a3 | 2018-06-29 17:28:38 +0300 | [diff] [blame] | 7 | package kotlinx.coroutines.experimental.guide.$$1$$2 |
Roman Elizarov | f16fd27 | 2017-02-07 11:26:00 +0300 | [diff] [blame] | 8 | |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 9 | import kotlinx.coroutines.experimental.* |
Roman Elizarov | f16fd27 | 2017-02-07 11:26:00 +0300 | [diff] [blame] | 10 | --> |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 11 | <!--- KNIT core/kotlinx-coroutines-core/test/guide/.*\.kt --> |
| 12 | <!--- TEST_OUT core/kotlinx-coroutines-core/test/guide/test/GuideTest.kt |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 13 | // This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit. |
Roman Elizarov | a9687a3 | 2018-06-29 17:28:38 +0300 | [diff] [blame] | 14 | package kotlinx.coroutines.experimental.guide.test |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 15 | |
| 16 | import org.junit.Test |
| 17 | |
| 18 | class GuideTest { |
| 19 | --> |
Roman Elizarov | f16fd27 | 2017-02-07 11:26:00 +0300 | [diff] [blame] | 20 | |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 21 | # Guide to kotlinx.coroutines by example |
| 22 | |
Roman Elizarov | a4d45d2 | 2017-11-20 16:47:09 +0300 | [diff] [blame] | 23 | This is a guide on core features of `kotlinx.coroutines` with a series of examples. |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 24 | |
Roman Elizarov | 2a63892 | 2017-03-04 10:22:43 +0300 | [diff] [blame] | 25 | ## Introduction and setup |
| 26 | |
| 27 | Kotlin, as a language, provides only minimal low-level APIs in its standard library to enable various other |
| 28 | libraries to utilize coroutines. Unlike many other languages with similar capabilities, `async` and `await` |
| 29 | are not keywords in Kotlin and are not even part of its standard library. |
| 30 | |
Robert Hencke | 497d343 | 2017-04-11 00:14:29 -0400 | [diff] [blame] | 31 | `kotlinx.coroutines` is one such rich library. It contains a number of high-level |
Roman Elizarov | a4d45d2 | 2017-11-20 16:47:09 +0300 | [diff] [blame] | 32 | coroutine-enabled primitives that this guide covers, including `launch`, `async` and others. |
Roman Elizarov | 2a63892 | 2017-03-04 10:22:43 +0300 | [diff] [blame] | 33 | You need to add a dependency on `kotlinx-coroutines-core` module as explained |
| 34 | [here](README.md#using-in-your-projects) to use primitives from this guide in your projects. |
| 35 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 36 | ## Table of contents |
| 37 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 38 | <!--- TOC --> |
| 39 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 40 | * [Coroutine basics](#coroutine-basics) |
| 41 | * [Your first coroutine](#your-first-coroutine) |
| 42 | * [Bridging blocking and non-blocking worlds](#bridging-blocking-and-non-blocking-worlds) |
| 43 | * [Waiting for a job](#waiting-for-a-job) |
| 44 | * [Extract function refactoring](#extract-function-refactoring) |
| 45 | * [Coroutines ARE light-weight](#coroutines-are-light-weight) |
| 46 | * [Coroutines are like daemon threads](#coroutines-are-like-daemon-threads) |
| 47 | * [Cancellation and timeouts](#cancellation-and-timeouts) |
| 48 | * [Cancelling coroutine execution](#cancelling-coroutine-execution) |
| 49 | * [Cancellation is cooperative](#cancellation-is-cooperative) |
| 50 | * [Making computation code cancellable](#making-computation-code-cancellable) |
| 51 | * [Closing resources with finally](#closing-resources-with-finally) |
| 52 | * [Run non-cancellable block](#run-non-cancellable-block) |
| 53 | * [Timeout](#timeout) |
| 54 | * [Composing suspending functions](#composing-suspending-functions) |
| 55 | * [Sequential by default](#sequential-by-default) |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 56 | * [Concurrent using async](#concurrent-using-async) |
| 57 | * [Lazily started async](#lazily-started-async) |
| 58 | * [Async-style functions](#async-style-functions) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 59 | * [Coroutine context and dispatchers](#coroutine-context-and-dispatchers) |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 60 | * [Dispatchers and threads](#dispatchers-and-threads) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 61 | * [Unconfined vs confined dispatcher](#unconfined-vs-confined-dispatcher) |
| 62 | * [Debugging coroutines and threads](#debugging-coroutines-and-threads) |
| 63 | * [Jumping between threads](#jumping-between-threads) |
| 64 | * [Job in the context](#job-in-the-context) |
| 65 | * [Children of a coroutine](#children-of-a-coroutine) |
| 66 | * [Combining contexts](#combining-contexts) |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 67 | * [Parental responsibilities](#parental-responsibilities) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 68 | * [Naming coroutines for debugging](#naming-coroutines-for-debugging) |
Roman Elizarov | 2fd7cb3 | 2017-02-11 23:18:59 +0300 | [diff] [blame] | 69 | * [Cancellation via explicit job](#cancellation-via-explicit-job) |
Vsevolod Tolstopyatov | e342597 | 2018-08-22 19:41:57 +0300 | [diff] [blame^] | 70 | * [Thread-local data](#thread-local-data) |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 71 | * [Exception handling](#exception-handling) |
| 72 | * [Exception propagation](#exception-propagation) |
| 73 | * [CoroutineExceptionHandler](#coroutineexceptionhandler) |
| 74 | * [Cancellation and exceptions](#cancellation-and-exceptions) |
| 75 | * [Exceptions aggregation](#exceptions-aggregation) |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 76 | * [Channels](#channels) |
| 77 | * [Channel basics](#channel-basics) |
| 78 | * [Closing and iteration over channels](#closing-and-iteration-over-channels) |
| 79 | * [Building channel producers](#building-channel-producers) |
| 80 | * [Pipelines](#pipelines) |
| 81 | * [Prime numbers with pipeline](#prime-numbers-with-pipeline) |
| 82 | * [Fan-out](#fan-out) |
| 83 | * [Fan-in](#fan-in) |
| 84 | * [Buffered channels](#buffered-channels) |
Vsevolod Tolstopyatov | 03d2ff7 | 2018-05-29 17:28:20 +0300 | [diff] [blame] | 85 | * [Ticker channels](#ticker-channels) |
Roman Elizarov | b0517ba | 2017-02-27 14:03:14 +0300 | [diff] [blame] | 86 | * [Channels are fair](#channels-are-fair) |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 87 | * [Shared mutable state and concurrency](#shared-mutable-state-and-concurrency) |
| 88 | * [The problem](#the-problem) |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 89 | * [Volatiles are of no help](#volatiles-are-of-no-help) |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 90 | * [Thread-safe data structures](#thread-safe-data-structures) |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 91 | * [Thread confinement fine-grained](#thread-confinement-fine-grained) |
| 92 | * [Thread confinement coarse-grained](#thread-confinement-coarse-grained) |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 93 | * [Mutual exclusion](#mutual-exclusion) |
| 94 | * [Actors](#actors) |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 95 | * [Select expression](#select-expression) |
| 96 | * [Selecting from channels](#selecting-from-channels) |
| 97 | * [Selecting on close](#selecting-on-close) |
| 98 | * [Selecting to send](#selecting-to-send) |
| 99 | * [Selecting deferred values](#selecting-deferred-values) |
| 100 | * [Switch over a channel of deferred values](#switch-over-a-channel-of-deferred-values) |
Roman Elizarov | 8db1733 | 2017-03-09 12:40:45 +0300 | [diff] [blame] | 101 | * [Further reading](#further-reading) |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 102 | |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 103 | <!--- END_TOC --> |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 104 | |
| 105 | ## Coroutine basics |
| 106 | |
| 107 | This section covers basic coroutine concepts. |
| 108 | |
| 109 | ### Your first coroutine |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 110 | |
| 111 | Run the following code: |
| 112 | |
| 113 | ```kotlin |
| 114 | fun main(args: Array<String>) { |
Roman Elizarov | a4d45d2 | 2017-11-20 16:47:09 +0300 | [diff] [blame] | 115 | launch { // launch new coroutine in background and continue |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 116 | delay(1000L) // non-blocking delay for 1 second (default time unit is ms) |
| 117 | println("World!") // print after delay |
| 118 | } |
Roman Elizarov | a4d45d2 | 2017-11-20 16:47:09 +0300 | [diff] [blame] | 119 | println("Hello,") // main thread continues while coroutine is delayed |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 120 | Thread.sleep(2000L) // block main thread for 2 seconds to keep JVM alive |
| 121 | } |
| 122 | ``` |
| 123 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 124 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-basic-01.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 125 | |
| 126 | Run this code: |
| 127 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 128 | ```text |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 129 | Hello, |
| 130 | World! |
| 131 | ``` |
| 132 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 133 | <!--- TEST --> |
| 134 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 135 | Essentially, coroutines are light-weight threads. |
| 136 | They are launched with [launch] _coroutine builder_. |
| 137 | You can achieve the same result replacing |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 138 | `launch { ... }` with `thread { ... }` and `delay(...)` with `Thread.sleep(...)`. Try it. |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 139 | |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 140 | If you start by replacing `launch` by `thread`, the compiler produces the following error: |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 141 | |
| 142 | ``` |
| 143 | Error: Kotlin: Suspend functions are only allowed to be called from a coroutine or another suspend function |
| 144 | ``` |
| 145 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 146 | That is because [delay] is a special _suspending function_ that does not block a thread, but _suspends_ |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 147 | coroutine and it can be only used from a coroutine. |
| 148 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 149 | ### Bridging blocking and non-blocking worlds |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 150 | |
Roman Elizarov | a4d45d2 | 2017-11-20 16:47:09 +0300 | [diff] [blame] | 151 | The first example mixes _non-blocking_ `delay(...)` and _blocking_ `Thread.sleep(...)` in the same code. |
| 152 | It is easy to get lost which one is blocking and which one is not. |
| 153 | Let's be explicit about blocking using [runBlocking] coroutine builder: |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 154 | |
| 155 | ```kotlin |
Roman Elizarov | a4d45d2 | 2017-11-20 16:47:09 +0300 | [diff] [blame] | 156 | fun main(args: Array<String>) { |
| 157 | launch { // launch new coroutine in background and continue |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 158 | delay(1000L) |
| 159 | println("World!") |
| 160 | } |
Roman Elizarov | a4d45d2 | 2017-11-20 16:47:09 +0300 | [diff] [blame] | 161 | println("Hello,") // main thread continues here immediately |
| 162 | runBlocking { // but this expression blocks the main thread |
| 163 | delay(2000L) // ... while we delay for 2 seconds to keep JVM alive |
| 164 | } |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 165 | } |
| 166 | ``` |
| 167 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 168 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-basic-02.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 169 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 170 | <!--- TEST |
| 171 | Hello, |
| 172 | World! |
| 173 | --> |
| 174 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 175 | The result is the same, but this code uses only non-blocking [delay]. |
Tylos | 81451de | 2017-12-17 21:33:17 +0100 | [diff] [blame] | 176 | The main thread, that invokes `runBlocking`, _blocks_ until the coroutine inside `runBlocking` completes. |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 177 | |
Roman Elizarov | a4d45d2 | 2017-11-20 16:47:09 +0300 | [diff] [blame] | 178 | This example can be also rewritten in a more idiomatic way, using `runBlocking` to wrap |
| 179 | the execution of the main function: |
| 180 | |
| 181 | ```kotlin |
| 182 | fun main(args: Array<String>) = runBlocking<Unit> { // start main coroutine |
| 183 | launch { // launch new coroutine in background and continue |
| 184 | delay(1000L) |
| 185 | println("World!") |
| 186 | } |
| 187 | println("Hello,") // main coroutine continues here immediately |
| 188 | delay(2000L) // delaying for 2 seconds to keep JVM alive |
| 189 | } |
| 190 | ``` |
| 191 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 192 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-basic-02b.kt) |
Roman Elizarov | a4d45d2 | 2017-11-20 16:47:09 +0300 | [diff] [blame] | 193 | |
| 194 | <!--- TEST |
| 195 | Hello, |
| 196 | World! |
| 197 | --> |
| 198 | |
| 199 | Here `runBlocking<Unit> { ... }` works as an adaptor that is used to start the top-level main coroutine. |
| 200 | We explicitly specify its `Unit` return type, because a well-formed `main` function in Kotlin has to return `Unit`. |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 201 | |
| 202 | This is also a way to write unit-tests for suspending functions: |
| 203 | |
| 204 | ```kotlin |
| 205 | class MyTest { |
| 206 | @Test |
| 207 | fun testMySuspendingFunction() = runBlocking<Unit> { |
| 208 | // here we can use suspending functions using any assertion style that we like |
| 209 | } |
| 210 | } |
| 211 | ``` |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame] | 212 | |
| 213 | <!--- CLEAR --> |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 214 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 215 | ### Waiting for a job |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 216 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 217 | Delaying for a time while another coroutine is working is not a good approach. Let's explicitly |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 218 | wait (in a non-blocking way) until the background [Job] that we have launched is complete: |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 219 | |
| 220 | ```kotlin |
| 221 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 222 | val job = launch { // launch new coroutine and keep a reference to its Job |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 223 | delay(1000L) |
| 224 | println("World!") |
| 225 | } |
| 226 | println("Hello,") |
| 227 | job.join() // wait until child coroutine completes |
| 228 | } |
| 229 | ``` |
| 230 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 231 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-basic-03.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 232 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 233 | <!--- TEST |
| 234 | Hello, |
| 235 | World! |
| 236 | --> |
| 237 | |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 238 | Now the result is still the same, but the code of the main coroutine is not tied to the duration of |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 239 | the background job in any way. Much better. |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 240 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 241 | ### Extract function refactoring |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 242 | |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 243 | Let's extract the block of code inside `launch { ... }` into a separate function. When you |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 244 | perform "Extract function" refactoring on this code you get a new function with `suspend` modifier. |
| 245 | That is your first _suspending function_. Suspending functions can be used inside coroutines |
| 246 | just like regular functions, but their additional feature is that they can, in turn, |
| 247 | use other suspending functions, like `delay` in this example, to _suspend_ execution of a coroutine. |
| 248 | |
| 249 | ```kotlin |
| 250 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 251 | val job = launch { doWorld() } |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 252 | println("Hello,") |
| 253 | job.join() |
| 254 | } |
| 255 | |
| 256 | // this is your first suspending function |
| 257 | suspend fun doWorld() { |
| 258 | delay(1000L) |
| 259 | println("World!") |
| 260 | } |
| 261 | ``` |
| 262 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 263 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-basic-04.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 264 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 265 | <!--- TEST |
| 266 | Hello, |
| 267 | World! |
| 268 | --> |
| 269 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 270 | ### Coroutines ARE light-weight |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 271 | |
| 272 | Run the following code: |
| 273 | |
| 274 | ```kotlin |
| 275 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 276 | val jobs = List(100_000) { // launch a lot of coroutines and list their jobs |
| 277 | launch { |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 278 | delay(1000L) |
| 279 | print(".") |
| 280 | } |
| 281 | } |
| 282 | jobs.forEach { it.join() } // wait for all jobs to complete |
| 283 | } |
| 284 | ``` |
| 285 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 286 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-basic-05.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 287 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 288 | <!--- TEST lines.size == 1 && lines[0] == ".".repeat(100_000) --> |
| 289 | |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 290 | It launches 100K coroutines and, after a second, each coroutine prints a dot. |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 291 | Now, try that with threads. What would happen? (Most likely your code will produce some sort of out-of-memory error) |
| 292 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 293 | ### Coroutines are like daemon threads |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 294 | |
| 295 | The following code launches a long-running coroutine that prints "I'm sleeping" twice a second and then |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 296 | returns from the main function after some delay: |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 297 | |
| 298 | ```kotlin |
| 299 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 300 | launch { |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 301 | repeat(1000) { i -> |
| 302 | println("I'm sleeping $i ...") |
| 303 | delay(500L) |
| 304 | } |
| 305 | } |
| 306 | delay(1300L) // just quit after delay |
| 307 | } |
| 308 | ``` |
| 309 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 310 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-basic-06.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 311 | |
| 312 | You can run and see that it prints three lines and terminates: |
| 313 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 314 | ```text |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 315 | I'm sleeping 0 ... |
| 316 | I'm sleeping 1 ... |
| 317 | I'm sleeping 2 ... |
| 318 | ``` |
| 319 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 320 | <!--- TEST --> |
| 321 | |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 322 | Active coroutines do not keep the process alive. They are like daemon threads. |
| 323 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 324 | ## Cancellation and timeouts |
| 325 | |
| 326 | This section covers coroutine cancellation and timeouts. |
| 327 | |
| 328 | ### Cancelling coroutine execution |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 329 | |
Brad | 977ada1 | 2018-07-19 16:01:40 -0400 | [diff] [blame] | 330 | In a small application the return from "main" method might sound like a good idea to get all coroutines |
| 331 | implicitly terminated but in a larger, long-running application, you need finer-grained control. |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 332 | The [launch] function returns a [Job] that can be used to cancel running coroutine: |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 333 | |
| 334 | ```kotlin |
| 335 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 336 | val job = launch { |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 337 | repeat(1000) { i -> |
| 338 | println("I'm sleeping $i ...") |
| 339 | delay(500L) |
| 340 | } |
| 341 | } |
| 342 | delay(1300L) // delay a bit |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 343 | println("main: I'm tired of waiting!") |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 344 | job.cancel() // cancels the job |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 345 | job.join() // waits for job's completion |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 346 | println("main: Now I can quit.") |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 347 | } |
| 348 | ``` |
| 349 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 350 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-cancel-01.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 351 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 352 | It produces the following output: |
| 353 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 354 | ```text |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 355 | I'm sleeping 0 ... |
| 356 | I'm sleeping 1 ... |
| 357 | I'm sleeping 2 ... |
| 358 | main: I'm tired of waiting! |
| 359 | main: Now I can quit. |
| 360 | ``` |
| 361 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 362 | <!--- TEST --> |
| 363 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 364 | As soon as main invokes `job.cancel`, we don't see any output from the other coroutine because it was cancelled. |
Roman Elizarov | 8839673 | 2017-09-27 21:30:47 +0300 | [diff] [blame] | 365 | There is also a [Job] extension function [cancelAndJoin] |
| 366 | that combines [cancel][Job.cancel] and [join][Job.join] invocations. |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 367 | |
| 368 | ### Cancellation is cooperative |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 369 | |
Tair Rzayev | af73462 | 2017-02-01 22:30:16 +0200 | [diff] [blame] | 370 | Coroutine cancellation is _cooperative_. A coroutine code has to cooperate to be cancellable. |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 371 | All the suspending functions in `kotlinx.coroutines` are _cancellable_. They check for cancellation of |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 372 | coroutine and throw [CancellationException] when cancelled. However, if a coroutine is working in |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 373 | a computation and does not check for cancellation, then it cannot be cancelled, like the following |
| 374 | example shows: |
| 375 | |
| 376 | ```kotlin |
| 377 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 24cd654 | 2017-08-03 21:20:04 -0700 | [diff] [blame] | 378 | val startTime = System.currentTimeMillis() |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 379 | val job = launch { |
Roman Elizarov | 24cd654 | 2017-08-03 21:20:04 -0700 | [diff] [blame] | 380 | var nextPrintTime = startTime |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 381 | var i = 0 |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 382 | while (i < 5) { // computation loop, just wastes CPU |
Roman Elizarov | 24cd654 | 2017-08-03 21:20:04 -0700 | [diff] [blame] | 383 | // print a message twice a second |
| 384 | if (System.currentTimeMillis() >= nextPrintTime) { |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 385 | println("I'm sleeping ${i++} ...") |
Roman Elizarov | 35d2c34 | 2017-07-20 14:54:39 +0300 | [diff] [blame] | 386 | nextPrintTime += 500L |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 387 | } |
| 388 | } |
| 389 | } |
| 390 | delay(1300L) // delay a bit |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 391 | println("main: I'm tired of waiting!") |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 392 | job.cancelAndJoin() // cancels the job and waits for its completion |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 393 | println("main: Now I can quit.") |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 394 | } |
| 395 | ``` |
| 396 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 397 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-cancel-02.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 398 | |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 399 | Run it to see that it continues to print "I'm sleeping" even after cancellation |
| 400 | until the job completes by itself after five iterations. |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 401 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 402 | <!--- TEST |
| 403 | I'm sleeping 0 ... |
| 404 | I'm sleeping 1 ... |
| 405 | I'm sleeping 2 ... |
| 406 | main: I'm tired of waiting! |
| 407 | I'm sleeping 3 ... |
| 408 | I'm sleeping 4 ... |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 409 | main: Now I can quit. |
| 410 | --> |
| 411 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 412 | ### Making computation code cancellable |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 413 | |
| 414 | There are two approaches to making computation code cancellable. The first one is to periodically |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 415 | invoke a suspending function that checks for cancellation. There is a [yield] function that is a good choice for that purpose. |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 416 | The other one is to explicitly check the cancellation status. Let us try the later approach. |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 417 | |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 418 | Replace `while (i < 5)` in the previous example with `while (isActive)` and rerun it. |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 419 | |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame] | 420 | ```kotlin |
| 421 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 24cd654 | 2017-08-03 21:20:04 -0700 | [diff] [blame] | 422 | val startTime = System.currentTimeMillis() |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 423 | val job = launch { |
Roman Elizarov | 24cd654 | 2017-08-03 21:20:04 -0700 | [diff] [blame] | 424 | var nextPrintTime = startTime |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame] | 425 | var i = 0 |
| 426 | while (isActive) { // cancellable computation loop |
Roman Elizarov | 24cd654 | 2017-08-03 21:20:04 -0700 | [diff] [blame] | 427 | // print a message twice a second |
| 428 | if (System.currentTimeMillis() >= nextPrintTime) { |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame] | 429 | println("I'm sleeping ${i++} ...") |
Roman Elizarov | 24cd654 | 2017-08-03 21:20:04 -0700 | [diff] [blame] | 430 | nextPrintTime += 500L |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame] | 431 | } |
| 432 | } |
| 433 | } |
| 434 | delay(1300L) // delay a bit |
| 435 | println("main: I'm tired of waiting!") |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 436 | job.cancelAndJoin() // cancels the job and waits for its completion |
Roman Elizarov | b3d55a5 | 2017-02-03 12:47:21 +0300 | [diff] [blame] | 437 | println("main: Now I can quit.") |
| 438 | } |
| 439 | ``` |
| 440 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 441 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-cancel-03.kt) |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 442 | |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 443 | As you can see, now this loop is cancelled. [isActive][CoroutineScope.isActive] is a property that is available inside |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 444 | the code of coroutines via [CoroutineScope] object. |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 445 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 446 | <!--- TEST |
| 447 | I'm sleeping 0 ... |
| 448 | I'm sleeping 1 ... |
| 449 | I'm sleeping 2 ... |
| 450 | main: I'm tired of waiting! |
| 451 | main: Now I can quit. |
| 452 | --> |
| 453 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 454 | ### Closing resources with finally |
| 455 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 456 | Cancellable suspending functions throw [CancellationException] on cancellation which can be handled in |
Brad | 977ada1 | 2018-07-19 16:01:40 -0400 | [diff] [blame] | 457 | the usual way. For example, `try {...} finally {...}` expression and Kotlin `use` function execute their |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 458 | finalization actions normally when coroutine is cancelled: |
| 459 | |
| 460 | ```kotlin |
| 461 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 462 | val job = launch { |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 463 | try { |
| 464 | repeat(1000) { i -> |
| 465 | println("I'm sleeping $i ...") |
| 466 | delay(500L) |
| 467 | } |
| 468 | } finally { |
| 469 | println("I'm running finally") |
| 470 | } |
| 471 | } |
| 472 | delay(1300L) // delay a bit |
| 473 | println("main: I'm tired of waiting!") |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 474 | job.cancelAndJoin() // cancels the job and waits for its completion |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 475 | println("main: Now I can quit.") |
| 476 | } |
| 477 | ``` |
| 478 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 479 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-cancel-04.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 480 | |
Roman Elizarov | 8839673 | 2017-09-27 21:30:47 +0300 | [diff] [blame] | 481 | Both [join][Job.join] and [cancelAndJoin] wait for all the finalization actions to complete, |
| 482 | so the example above produces the following output: |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 483 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 484 | ```text |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 485 | I'm sleeping 0 ... |
| 486 | I'm sleeping 1 ... |
| 487 | I'm sleeping 2 ... |
| 488 | main: I'm tired of waiting! |
| 489 | I'm running finally |
| 490 | main: Now I can quit. |
| 491 | ``` |
| 492 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 493 | <!--- TEST --> |
| 494 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 495 | ### Run non-cancellable block |
| 496 | |
| 497 | Any attempt to use a suspending function in the `finally` block of the previous example will cause |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 498 | [CancellationException], because the coroutine running this code is cancelled. Usually, this is not a |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 499 | problem, since all well-behaving closing operations (closing a file, cancelling a job, or closing any kind of a |
| 500 | communication channel) are usually non-blocking and do not involve any suspending functions. However, in the |
| 501 | rare case when you need to suspend in the cancelled coroutine you can wrap the corresponding code in |
Roman Elizarov | f9e13f5 | 2017-12-21 12:23:15 +0300 | [diff] [blame] | 502 | `withContext(NonCancellable) {...}` using [withContext] function and [NonCancellable] context as the following example shows: |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 503 | |
| 504 | ```kotlin |
| 505 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 506 | val job = launch { |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 507 | try { |
| 508 | repeat(1000) { i -> |
| 509 | println("I'm sleeping $i ...") |
| 510 | delay(500L) |
| 511 | } |
| 512 | } finally { |
Roman Elizarov | f9e13f5 | 2017-12-21 12:23:15 +0300 | [diff] [blame] | 513 | withContext(NonCancellable) { |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 514 | println("I'm running finally") |
| 515 | delay(1000L) |
| 516 | println("And I've just delayed for 1 sec because I'm non-cancellable") |
| 517 | } |
| 518 | } |
| 519 | } |
| 520 | delay(1300L) // delay a bit |
| 521 | println("main: I'm tired of waiting!") |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 522 | job.cancelAndJoin() // cancels the job and waits for its completion |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 523 | println("main: Now I can quit.") |
| 524 | } |
| 525 | ``` |
| 526 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 527 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-cancel-05.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 528 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 529 | <!--- TEST |
| 530 | I'm sleeping 0 ... |
| 531 | I'm sleeping 1 ... |
| 532 | I'm sleeping 2 ... |
| 533 | main: I'm tired of waiting! |
| 534 | I'm running finally |
| 535 | And I've just delayed for 1 sec because I'm non-cancellable |
| 536 | main: Now I can quit. |
| 537 | --> |
| 538 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 539 | ### Timeout |
| 540 | |
Brad | 977ada1 | 2018-07-19 16:01:40 -0400 | [diff] [blame] | 541 | The most obvious reason to cancel coroutine execution in practice |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 542 | is because its execution time has exceeded some timeout. |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 543 | While you can manually track the reference to the corresponding [Job] and launch a separate coroutine to cancel |
| 544 | the tracked one after delay, there is a ready to use [withTimeout] function that does it. |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 545 | Look at the following example: |
| 546 | |
| 547 | ```kotlin |
| 548 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 549 | withTimeout(1300L) { |
| 550 | repeat(1000) { i -> |
| 551 | println("I'm sleeping $i ...") |
| 552 | delay(500L) |
| 553 | } |
| 554 | } |
| 555 | } |
| 556 | ``` |
| 557 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 558 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-cancel-06.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 559 | |
| 560 | It produces the following output: |
| 561 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 562 | ```text |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 563 | I'm sleeping 0 ... |
| 564 | I'm sleeping 1 ... |
| 565 | I'm sleeping 2 ... |
Roman Elizarov | 63f6ea2 | 2017-09-06 18:42:34 +0300 | [diff] [blame] | 566 | Exception in thread "main" kotlinx.coroutines.experimental.TimeoutCancellationException: Timed out waiting for 1300 MILLISECONDS |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 567 | ``` |
| 568 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 569 | <!--- TEST STARTS_WITH --> |
| 570 | |
Roman Elizarov | 63f6ea2 | 2017-09-06 18:42:34 +0300 | [diff] [blame] | 571 | The `TimeoutCancellationException` that is thrown by [withTimeout] is a subclass of [CancellationException]. |
Roman Elizarov | ca9d5be | 2017-04-20 19:23:18 +0300 | [diff] [blame] | 572 | We have not seen its stack trace printed on the console before. That is because |
Roman Elizarov | 7c864d8 | 2017-02-27 10:17:50 +0300 | [diff] [blame] | 573 | inside a cancelled coroutine `CancellationException` is considered to be a normal reason for coroutine completion. |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 574 | However, in this example we have used `withTimeout` right inside the `main` function. |
| 575 | |
| 576 | Because cancellation is just an exception, all the resources will be closed in a usual way. |
Roman Elizarov | 63f6ea2 | 2017-09-06 18:42:34 +0300 | [diff] [blame] | 577 | You can wrap the code with timeout in `try {...} catch (e: TimeoutCancellationException) {...}` block if |
| 578 | you need to do some additional action specifically on any kind of timeout or use [withTimeoutOrNull] function |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 579 | that is similar to [withTimeout], but returns `null` on timeout instead of throwing an exception: |
| 580 | |
| 581 | ```kotlin |
| 582 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 583 | val result = withTimeoutOrNull(1300L) { |
| 584 | repeat(1000) { i -> |
| 585 | println("I'm sleeping $i ...") |
| 586 | delay(500L) |
| 587 | } |
| 588 | "Done" // will get cancelled before it produces this result |
| 589 | } |
| 590 | println("Result is $result") |
| 591 | } |
| 592 | ``` |
| 593 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 594 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-cancel-07.kt) |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 595 | |
| 596 | There is no longer an exception when running this code: |
| 597 | |
| 598 | ```text |
| 599 | I'm sleeping 0 ... |
| 600 | I'm sleeping 1 ... |
| 601 | I'm sleeping 2 ... |
| 602 | Result is null |
| 603 | ``` |
| 604 | |
| 605 | <!--- TEST --> |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 606 | |
| 607 | ## Composing suspending functions |
| 608 | |
| 609 | This section covers various approaches to composition of suspending functions. |
| 610 | |
| 611 | ### Sequential by default |
| 612 | |
| 613 | Assume that we have two suspending functions defined elsewhere that do something useful like some kind of |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 614 | remote service call or computation. We just pretend they are useful, but actually each one just |
| 615 | delays for a second for the purpose of this example: |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 616 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 617 | <!--- INCLUDE .*/example-compose-([0-9]+).kt |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 618 | import kotlin.system.* |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 619 | --> |
| 620 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 621 | ```kotlin |
| 622 | suspend fun doSomethingUsefulOne(): Int { |
| 623 | delay(1000L) // pretend we are doing something useful here |
| 624 | return 13 |
| 625 | } |
| 626 | |
| 627 | suspend fun doSomethingUsefulTwo(): Int { |
| 628 | delay(1000L) // pretend we are doing something useful here, too |
| 629 | return 29 |
| 630 | } |
| 631 | ``` |
| 632 | |
Roman Elizarov | fa7723e | 2017-02-06 11:17:51 +0300 | [diff] [blame] | 633 | <!--- INCLUDE .*/example-compose-([0-9]+).kt --> |
| 634 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 635 | What do we do if need to invoke them _sequentially_ -- first `doSomethingUsefulOne` _and then_ |
| 636 | `doSomethingUsefulTwo` and compute the sum of their results? |
Ronen Sabag | d2d42ea | 2017-12-24 21:55:06 +0200 | [diff] [blame] | 637 | In practice we do this if we use the results of the first function to make a decision on whether we need |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 638 | to invoke the second one or to decide on how to invoke it. |
| 639 | |
| 640 | We just use a normal sequential invocation, because the code in the coroutine, just like in the regular |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 641 | code, is _sequential_ by default. The following example demonstrates it by measuring the total |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 642 | time it takes to execute both suspending functions: |
| 643 | |
| 644 | ```kotlin |
| 645 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 646 | val time = measureTimeMillis { |
| 647 | val one = doSomethingUsefulOne() |
| 648 | val two = doSomethingUsefulTwo() |
| 649 | println("The answer is ${one + two}") |
| 650 | } |
| 651 | println("Completed in $time ms") |
| 652 | } |
| 653 | ``` |
| 654 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 655 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-compose-01.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 656 | |
| 657 | It produces something like this: |
| 658 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 659 | ```text |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 660 | The answer is 42 |
| 661 | Completed in 2017 ms |
| 662 | ``` |
| 663 | |
Roman Elizarov | 35d2c34 | 2017-07-20 14:54:39 +0300 | [diff] [blame] | 664 | <!--- TEST ARBITRARY_TIME --> |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 665 | |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 666 | ### Concurrent using async |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 667 | |
| 668 | What if there are no dependencies between invocation of `doSomethingUsefulOne` and `doSomethingUsefulTwo` and |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 669 | we want to get the answer faster, by doing both _concurrently_? This is where [async] comes to help. |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 670 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 671 | Conceptually, [async] is just like [launch]. It starts a separate coroutine which is a light-weight thread |
| 672 | that works concurrently with all the other coroutines. The difference is that `launch` returns a [Job] and |
| 673 | does not carry any resulting value, while `async` returns a [Deferred] -- a light-weight non-blocking future |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 674 | that represents a promise to provide a result later. You can use `.await()` on a deferred value to get its eventual result, |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 675 | but `Deferred` is also a `Job`, so you can cancel it if needed. |
| 676 | |
| 677 | ```kotlin |
| 678 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 679 | val time = measureTimeMillis { |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 680 | val one = async { doSomethingUsefulOne() } |
| 681 | val two = async { doSomethingUsefulTwo() } |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 682 | println("The answer is ${one.await() + two.await()}") |
| 683 | } |
| 684 | println("Completed in $time ms") |
| 685 | } |
| 686 | ``` |
| 687 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 688 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-compose-02.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 689 | |
| 690 | It produces something like this: |
| 691 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 692 | ```text |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 693 | The answer is 42 |
| 694 | Completed in 1017 ms |
| 695 | ``` |
| 696 | |
Roman Elizarov | 35d2c34 | 2017-07-20 14:54:39 +0300 | [diff] [blame] | 697 | <!--- TEST ARBITRARY_TIME --> |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 698 | |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 699 | This is twice as fast, because we have concurrent execution of two coroutines. |
| 700 | Note, that concurrency with coroutines is always explicit. |
| 701 | |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 702 | ### Lazily started async |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 703 | |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 704 | There is a laziness option to [async] using an optional `start` parameter with a value of [CoroutineStart.LAZY]. |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 705 | It starts coroutine only when its result is needed by some |
| 706 | [await][Deferred.await] or if a [start][Job.start] function |
Sahil Lone | 52a0ec0 | 2018-07-19 18:55:35 +0200 | [diff] [blame] | 707 | is invoked. Run the following example: |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 708 | |
| 709 | ```kotlin |
| 710 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 711 | val time = measureTimeMillis { |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 712 | val one = async(start = CoroutineStart.LAZY) { doSomethingUsefulOne() } |
| 713 | val two = async(start = CoroutineStart.LAZY) { doSomethingUsefulTwo() } |
Sahil Lone | 52a0ec0 | 2018-07-19 18:55:35 +0200 | [diff] [blame] | 714 | // some computation |
| 715 | one.start() // start the first one |
| 716 | two.start() // start the second one |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 717 | println("The answer is ${one.await() + two.await()}") |
| 718 | } |
| 719 | println("Completed in $time ms") |
| 720 | } |
| 721 | ``` |
| 722 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 723 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-compose-03.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 724 | |
| 725 | It produces something like this: |
| 726 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 727 | ```text |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 728 | The answer is 42 |
Sahil Lone | 52a0ec0 | 2018-07-19 18:55:35 +0200 | [diff] [blame] | 729 | Completed in 1017 ms |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 730 | ``` |
| 731 | |
Roman Elizarov | 35d2c34 | 2017-07-20 14:54:39 +0300 | [diff] [blame] | 732 | <!--- TEST ARBITRARY_TIME --> |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 733 | |
Sahil Lone | 52a0ec0 | 2018-07-19 18:55:35 +0200 | [diff] [blame] | 734 | So, here the two coroutines are defined but not executed as in the previous example, but the control is given to |
| 735 | the programmer about when exactly to start the execution by calling [start][Job.start] on it. We first |
| 736 | start `one`, then start `two`, and then await for the individual coroutines to finish. |
| 737 | |
| 738 | Note, that if we have called [await][Deferred.await] in `println` and omitted [start][Job.start] on individual |
| 739 | coroutines, then we would have got the sequential behaviour as [await][Deferred.await] starts the coroutine |
| 740 | execution and waits for the execution to finish, which is not the intended use-case for laziness. |
| 741 | The use-case for `async(start = CoroutineStart.LAZY)` is a replacement for the |
| 742 | standard `lazy` function in cases when computation of the value involves suspending functions. |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 743 | |
| 744 | ### Async-style functions |
| 745 | |
| 746 | We can define async-style functions that invoke `doSomethingUsefulOne` and `doSomethingUsefulTwo` |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 747 | _asynchronously_ using [async] coroutine builder. It is a good style to name such functions with |
Marcin Moskała | 7e94e70 | 2018-01-29 18:39:02 +0100 | [diff] [blame] | 748 | "Async" suffix to highlight the fact that they only start asynchronous computation and one needs |
| 749 | to use the resulting deferred value to get the result. |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 750 | |
| 751 | ```kotlin |
Marcin Moskała | 7e94e70 | 2018-01-29 18:39:02 +0100 | [diff] [blame] | 752 | // The result type of somethingUsefulOneAsync is Deferred<Int> |
| 753 | fun somethingUsefulOneAsync() = async { |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 754 | doSomethingUsefulOne() |
| 755 | } |
| 756 | |
Marcin Moskała | 7e94e70 | 2018-01-29 18:39:02 +0100 | [diff] [blame] | 757 | // The result type of somethingUsefulTwoAsync is Deferred<Int> |
| 758 | fun somethingUsefulTwoAsync() = async { |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 759 | doSomethingUsefulTwo() |
| 760 | } |
| 761 | ``` |
| 762 | |
Marcin Moskała | 7e94e70 | 2018-01-29 18:39:02 +0100 | [diff] [blame] | 763 | Note, that these `xxxAsync` functions are **not** _suspending_ functions. They can be used from anywhere. |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 764 | However, their use always implies asynchronous (here meaning _concurrent_) execution of their action |
| 765 | with the invoking code. |
| 766 | |
| 767 | The following example shows their use outside of coroutine: |
| 768 | |
| 769 | ```kotlin |
| 770 | // note, that we don't have `runBlocking` to the right of `main` in this example |
| 771 | fun main(args: Array<String>) { |
| 772 | val time = measureTimeMillis { |
| 773 | // we can initiate async actions outside of a coroutine |
Marcin Moskała | 7e94e70 | 2018-01-29 18:39:02 +0100 | [diff] [blame] | 774 | val one = somethingUsefulOneAsync() |
| 775 | val two = somethingUsefulTwoAsync() |
Roman Elizarov | 32d9532 | 2017-02-09 15:57:31 +0300 | [diff] [blame] | 776 | // but waiting for a result must involve either suspending or blocking. |
| 777 | // here we use `runBlocking { ... }` to block the main thread while waiting for the result |
| 778 | runBlocking { |
| 779 | println("The answer is ${one.await() + two.await()}") |
| 780 | } |
| 781 | } |
| 782 | println("Completed in $time ms") |
| 783 | } |
| 784 | ``` |
| 785 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 786 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-compose-04.kt) |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 787 | |
Roman Elizarov | 35d2c34 | 2017-07-20 14:54:39 +0300 | [diff] [blame] | 788 | <!--- TEST ARBITRARY_TIME |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 789 | The answer is 42 |
| 790 | Completed in 1085 ms |
| 791 | --> |
| 792 | |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 793 | ## Coroutine context and dispatchers |
| 794 | |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 795 | Coroutines always execute in some context which is represented by the value of |
| 796 | [CoroutineContext](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.experimental/-coroutine-context/) |
| 797 | type, defined in the Kotlin standard library. |
| 798 | |
| 799 | The coroutine context is a set of various elements. The main elements are the [Job] of the coroutine, |
| 800 | which we've seen before, and its dispatcher, which is covered in this section. |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 801 | |
| 802 | ### Dispatchers and threads |
| 803 | |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 804 | Coroutine context includes a _coroutine dispatcher_ (see [CoroutineDispatcher]) that determines what thread or threads |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 805 | the corresponding coroutine uses for its execution. Coroutine dispatcher can confine coroutine execution |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 806 | to a specific thread, dispatch it to a thread pool, or let it run unconfined. |
| 807 | |
| 808 | All coroutines builders like [launch] and [async] accept an optional |
| 809 | [CoroutineContext](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.experimental/-coroutine-context/) |
| 810 | parameter that can be used to explicitly specify the dispatcher for new coroutine and other context elements. |
| 811 | |
| 812 | Try the following example: |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 813 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 814 | <!--- INCLUDE |
| 815 | import kotlin.coroutines.experimental.* |
| 816 | --> |
| 817 | |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 818 | ```kotlin |
| 819 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 820 | val jobs = arrayListOf<Job>() |
| 821 | jobs += launch(Unconfined) { // not confined -- will work with main thread |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 822 | println(" 'Unconfined': I'm working in thread ${Thread.currentThread().name}") |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 823 | } |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 824 | jobs += launch(coroutineContext) { // context of the parent, runBlocking coroutine |
| 825 | println("'coroutineContext': I'm working in thread ${Thread.currentThread().name}") |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 826 | } |
| 827 | jobs += launch(CommonPool) { // will get dispatched to ForkJoinPool.commonPool (or equivalent) |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 828 | println(" 'CommonPool': I'm working in thread ${Thread.currentThread().name}") |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 829 | } |
| 830 | jobs += launch(newSingleThreadContext("MyOwnThread")) { // will get its own new thread |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 831 | println(" 'newSTC': I'm working in thread ${Thread.currentThread().name}") |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 832 | } |
| 833 | jobs.forEach { it.join() } |
| 834 | } |
| 835 | ``` |
| 836 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 837 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-context-01.kt) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 838 | |
| 839 | It produces the following output (maybe in different order): |
| 840 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 841 | ```text |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 842 | 'Unconfined': I'm working in thread main |
| 843 | 'CommonPool': I'm working in thread ForkJoinPool.commonPool-worker-1 |
| 844 | 'newSTC': I'm working in thread MyOwnThread |
| 845 | 'coroutineContext': I'm working in thread main |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 846 | ``` |
| 847 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 848 | <!--- TEST LINES_START_UNORDERED --> |
| 849 | |
Roman Elizarov | d9ae2bc | 2017-10-20 17:36:56 +0800 | [diff] [blame] | 850 | The default dispatcher that we've used in previous sections is representend by [DefaultDispatcher], which |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 851 | is equal to [CommonPool] in the current implementation. So, `launch { ... }` is the same |
Charles Muchene | fa13beb | 2018-01-08 16:56:54 +0300 | [diff] [blame] | 852 | as `launch(DefaultDispatcher) { ... }`, which is the same as `launch(CommonPool) { ... }`. |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 853 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 854 | The difference between parent |
| 855 | [coroutineContext](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.experimental/coroutine-context.html) and |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 856 | [Unconfined] context will be shown later. |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 857 | |
Roman Elizarov | d9ae2bc | 2017-10-20 17:36:56 +0800 | [diff] [blame] | 858 | Note, that [newSingleThreadContext] creates a new thread, which is a very expensive resource. |
| 859 | In a real application it must be either released, when no longer needed, using [close][ThreadPoolDispatcher.close] |
| 860 | function, or stored in a top-level variable and reused throughout the application. |
| 861 | |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 862 | ### Unconfined vs confined dispatcher |
| 863 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 864 | The [Unconfined] coroutine dispatcher starts coroutine in the caller thread, but only until the |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 865 | first suspension point. After suspension it resumes in the thread that is fully determined by the |
| 866 | suspending function that was invoked. Unconfined dispatcher is appropriate when coroutine does not |
| 867 | consume CPU time nor updates any shared data (like UI) that is confined to a specific thread. |
| 868 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 869 | On the other side, |
| 870 | [coroutineContext](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.experimental/coroutine-context.html) |
| 871 | property, that is available inside any coroutine, is a reference to a context of this particular coroutine. |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 872 | This way, a parent context can be inherited. The default dispatcher for [runBlocking] coroutine, in particular, |
| 873 | is confined to the invoker thread, so inheriting it has the effect of confining execution to |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 874 | this thread with a predictable FIFO scheduling. |
| 875 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 876 | <!--- INCLUDE |
| 877 | import kotlin.coroutines.experimental.* |
| 878 | --> |
| 879 | |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 880 | ```kotlin |
| 881 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 882 | val jobs = arrayListOf<Job>() |
| 883 | jobs += launch(Unconfined) { // not confined -- will work with main thread |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 884 | println(" 'Unconfined': I'm working in thread ${Thread.currentThread().name}") |
Roman Elizarov | d002162 | 2017-03-10 15:43:38 +0300 | [diff] [blame] | 885 | delay(500) |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 886 | println(" 'Unconfined': After delay in thread ${Thread.currentThread().name}") |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 887 | } |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 888 | jobs += launch(coroutineContext) { // context of the parent, runBlocking coroutine |
| 889 | println("'coroutineContext': I'm working in thread ${Thread.currentThread().name}") |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 890 | delay(1000) |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 891 | println("'coroutineContext': After delay in thread ${Thread.currentThread().name}") |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 892 | } |
| 893 | jobs.forEach { it.join() } |
| 894 | } |
| 895 | ``` |
| 896 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 897 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-context-02.kt) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 898 | |
| 899 | Produces the output: |
| 900 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 901 | ```text |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 902 | 'Unconfined': I'm working in thread main |
| 903 | 'coroutineContext': I'm working in thread main |
| 904 | 'Unconfined': After delay in thread kotlinx.coroutines.DefaultExecutor |
| 905 | 'coroutineContext': After delay in thread main |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 906 | ``` |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 907 | |
| 908 | <!--- TEST LINES_START --> |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 909 | |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 910 | So, the coroutine that had inherited `coroutineContext` of `runBlocking {...}` continues to execute |
| 911 | in the `main` thread, while the unconfined one had resumed in the default executor thread that [delay] |
| 912 | function is using. |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 913 | |
| 914 | ### Debugging coroutines and threads |
| 915 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 916 | Coroutines can suspend on one thread and resume on another thread with [Unconfined] dispatcher or |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 917 | with a default multi-threaded dispatcher. Even with a single-threaded dispatcher it might be hard to |
paolop | b019b10 | 2018-06-09 16:42:24 +0000 | [diff] [blame] | 918 | figure out what coroutine was doing, where, and when. The common approach to debugging applications with |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 919 | threads is to print the thread name in the log file on each log statement. This feature is universally supported |
| 920 | by logging frameworks. When using coroutines, the thread name alone does not give much of a context, so |
| 921 | `kotlinx.coroutines` includes debugging facilities to make it easier. |
| 922 | |
| 923 | Run the following code with `-Dkotlinx.coroutines.debug` JVM option: |
| 924 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 925 | <!--- INCLUDE |
| 926 | import kotlin.coroutines.experimental.* |
| 927 | --> |
| 928 | |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 929 | ```kotlin |
| 930 | fun log(msg: String) = println("[${Thread.currentThread().name}] $msg") |
| 931 | |
| 932 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 933 | val a = async(coroutineContext) { |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 934 | log("I'm computing a piece of the answer") |
| 935 | 6 |
| 936 | } |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 937 | val b = async(coroutineContext) { |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 938 | log("I'm computing another piece of the answer") |
| 939 | 7 |
| 940 | } |
| 941 | log("The answer is ${a.await() * b.await()}") |
| 942 | } |
| 943 | ``` |
| 944 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 945 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-context-03.kt) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 946 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 947 | There are three coroutines. The main coroutine (#1) -- `runBlocking` one, |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 948 | and two coroutines computing deferred values `a` (#2) and `b` (#3). |
| 949 | They are all executing in the context of `runBlocking` and are confined to the main thread. |
| 950 | The output of this code is: |
| 951 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 952 | ```text |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 953 | [main @coroutine#2] I'm computing a piece of the answer |
| 954 | [main @coroutine#3] I'm computing another piece of the answer |
| 955 | [main @coroutine#1] The answer is 42 |
| 956 | ``` |
| 957 | |
Kirill Timofeev | a518696 | 2017-10-25 14:25:47 +0300 | [diff] [blame] | 958 | <!--- TEST FLEXIBLE_THREAD --> |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 959 | |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 960 | The `log` function prints the name of the thread in square brackets and you can see, that it is the `main` |
| 961 | thread, but the identifier of the currently executing coroutine is appended to it. This identifier |
| 962 | is consecutively assigned to all created coroutines when debugging mode is turned on. |
| 963 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 964 | You can read more about debugging facilities in the documentation for [newCoroutineContext] function. |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 965 | |
| 966 | ### Jumping between threads |
| 967 | |
| 968 | Run the following code with `-Dkotlinx.coroutines.debug` JVM option: |
| 969 | |
| 970 | ```kotlin |
| 971 | fun log(msg: String) = println("[${Thread.currentThread().name}] $msg") |
| 972 | |
| 973 | fun main(args: Array<String>) { |
Roman Elizarov | d9ae2bc | 2017-10-20 17:36:56 +0800 | [diff] [blame] | 974 | newSingleThreadContext("Ctx1").use { ctx1 -> |
| 975 | newSingleThreadContext("Ctx2").use { ctx2 -> |
| 976 | runBlocking(ctx1) { |
| 977 | log("Started in ctx1") |
Roman Elizarov | f9e13f5 | 2017-12-21 12:23:15 +0300 | [diff] [blame] | 978 | withContext(ctx2) { |
Roman Elizarov | d9ae2bc | 2017-10-20 17:36:56 +0800 | [diff] [blame] | 979 | log("Working in ctx2") |
| 980 | } |
| 981 | log("Back to ctx1") |
| 982 | } |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 983 | } |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 984 | } |
| 985 | } |
| 986 | ``` |
| 987 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 988 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-context-04.kt) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 989 | |
Roman Elizarov | d9ae2bc | 2017-10-20 17:36:56 +0800 | [diff] [blame] | 990 | It demonstrates several new techniques. One is using [runBlocking] with an explicitly specified context, and |
Roman Elizarov | f9e13f5 | 2017-12-21 12:23:15 +0300 | [diff] [blame] | 991 | the other one is using [withContext] function to change a context of a coroutine while still staying in the |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 992 | same coroutine as you can see in the output below: |
| 993 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 994 | ```text |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 995 | [Ctx1 @coroutine#1] Started in ctx1 |
| 996 | [Ctx2 @coroutine#1] Working in ctx2 |
| 997 | [Ctx1 @coroutine#1] Back to ctx1 |
| 998 | ``` |
| 999 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1000 | <!--- TEST --> |
| 1001 | |
Roman Elizarov | d9ae2bc | 2017-10-20 17:36:56 +0800 | [diff] [blame] | 1002 | |
Artsiom Chapialiou | e185ed6 | 2018-06-03 19:34:22 -0400 | [diff] [blame] | 1003 | Note, that this example also uses `use` function from the Kotlin standard library to release threads that |
Roman Elizarov | d9ae2bc | 2017-10-20 17:36:56 +0800 | [diff] [blame] | 1004 | are created with [newSingleThreadContext] when they are no longer needed. |
| 1005 | |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1006 | ### Job in the context |
| 1007 | |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1008 | The coroutine's [Job] is part of its context. The coroutine can retrieve it from its own context |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 1009 | using `coroutineContext[Job]` expression: |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1010 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 1011 | <!--- INCLUDE |
| 1012 | import kotlin.coroutines.experimental.* |
| 1013 | --> |
| 1014 | |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1015 | ```kotlin |
| 1016 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 1017 | println("My job is ${coroutineContext[Job]}") |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1018 | } |
| 1019 | ``` |
| 1020 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 1021 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-context-05.kt) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1022 | |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1023 | It produces something like that when running in [debug mode](#debugging-coroutines-and-threads): |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1024 | |
| 1025 | ``` |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 1026 | My job is "coroutine#1":BlockingCoroutine{Active}@6d311334 |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1027 | ``` |
| 1028 | |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 1029 | <!--- TEST lines.size == 1 && lines[0].startsWith("My job is \"coroutine#1\":BlockingCoroutine{Active}@") --> |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1030 | |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 1031 | So, [isActive][CoroutineScope.isActive] in [CoroutineScope] is just a convenient shortcut for |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 1032 | `coroutineContext[Job]?.isActive == true`. |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1033 | |
| 1034 | ### Children of a coroutine |
| 1035 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 1036 | When |
| 1037 | [coroutineContext](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.experimental/coroutine-context.html) |
| 1038 | of a coroutine is used to launch another coroutine, |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 1039 | the [Job] of the new coroutine becomes |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1040 | a _child_ of the parent coroutine's job. When the parent coroutine is cancelled, all its children |
| 1041 | are recursively cancelled, too. |
| 1042 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 1043 | <!--- INCLUDE |
| 1044 | import kotlin.coroutines.experimental.* |
| 1045 | --> |
| 1046 | |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1047 | ```kotlin |
| 1048 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1049 | // launch a coroutine to process some kind of incoming request |
| 1050 | val request = launch { |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1051 | // it spawns two other jobs, one with its separate context |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1052 | val job1 = launch { |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1053 | println("job1: I have my own context and execute independently!") |
| 1054 | delay(1000) |
| 1055 | println("job1: I am not affected by cancellation of the request") |
| 1056 | } |
| 1057 | // and the other inherits the parent context |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 1058 | val job2 = launch(coroutineContext) { |
Roman Elizarov | 74619c1 | 2017-11-09 10:32:15 +0300 | [diff] [blame] | 1059 | delay(100) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1060 | println("job2: I am a child of the request coroutine") |
| 1061 | delay(1000) |
| 1062 | println("job2: I will not execute this line if my parent request is cancelled") |
| 1063 | } |
| 1064 | // request completes when both its sub-jobs complete: |
| 1065 | job1.join() |
| 1066 | job2.join() |
| 1067 | } |
| 1068 | delay(500) |
| 1069 | request.cancel() // cancel processing of the request |
| 1070 | delay(1000) // delay a second to see what happens |
| 1071 | println("main: Who has survived request cancellation?") |
| 1072 | } |
| 1073 | ``` |
| 1074 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 1075 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-context-06.kt) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1076 | |
| 1077 | The output of this code is: |
| 1078 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1079 | ```text |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1080 | job1: I have my own context and execute independently! |
| 1081 | job2: I am a child of the request coroutine |
| 1082 | job1: I am not affected by cancellation of the request |
| 1083 | main: Who has survived request cancellation? |
| 1084 | ``` |
| 1085 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1086 | <!--- TEST --> |
| 1087 | |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1088 | ### Combining contexts |
| 1089 | |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1090 | Coroutine contexts can be combined using `+` operator. The context on the right-hand side replaces relevant entries |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 1091 | of the context on the left-hand side. For example, a [Job] of the parent coroutine can be inherited, while |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1092 | its dispatcher replaced: |
| 1093 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 1094 | <!--- INCLUDE |
| 1095 | import kotlin.coroutines.experimental.* |
| 1096 | --> |
| 1097 | |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1098 | ```kotlin |
| 1099 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1100 | // start a coroutine to process some kind of incoming request |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 1101 | val request = launch(coroutineContext) { // use the context of `runBlocking` |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1102 | // spawns CPU-intensive child job in CommonPool !!! |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 1103 | val job = launch(coroutineContext + CommonPool) { |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1104 | println("job: I am a child of the request coroutine, but with a different dispatcher") |
| 1105 | delay(1000) |
| 1106 | println("job: I will not execute this line if my parent request is cancelled") |
| 1107 | } |
| 1108 | job.join() // request completes when its sub-job completes |
| 1109 | } |
| 1110 | delay(500) |
| 1111 | request.cancel() // cancel processing of the request |
| 1112 | delay(1000) // delay a second to see what happens |
| 1113 | println("main: Who has survived request cancellation?") |
| 1114 | } |
| 1115 | ``` |
| 1116 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 1117 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-context-07.kt) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1118 | |
| 1119 | The expected outcome of this code is: |
| 1120 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1121 | ```text |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1122 | job: I am a child of the request coroutine, but with a different dispatcher |
| 1123 | main: Who has survived request cancellation? |
| 1124 | ``` |
| 1125 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1126 | <!--- TEST --> |
| 1127 | |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 1128 | ### Parental responsibilities |
| 1129 | |
| 1130 | A parent coroutine always waits for completion of all its children. Parent does not have to explicitly track |
Roman Elizarov | 8839673 | 2017-09-27 21:30:47 +0300 | [diff] [blame] | 1131 | all the children it launches and it does not have to use [Job.join] to wait for them at the end: |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 1132 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 1133 | <!--- INCLUDE |
| 1134 | import kotlin.coroutines.experimental.* |
| 1135 | --> |
| 1136 | |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 1137 | ```kotlin |
| 1138 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1139 | // launch a coroutine to process some kind of incoming request |
| 1140 | val request = launch { |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 1141 | repeat(3) { i -> // launch a few children jobs |
| 1142 | launch(coroutineContext) { |
| 1143 | delay((i + 1) * 200L) // variable delay 200ms, 400ms, 600ms |
| 1144 | println("Coroutine $i is done") |
| 1145 | } |
| 1146 | } |
| 1147 | println("request: I'm done and I don't explicitly join my children that are still active") |
| 1148 | } |
| 1149 | request.join() // wait for completion of the request, including all its children |
| 1150 | println("Now processing of the request is complete") |
| 1151 | } |
| 1152 | ``` |
| 1153 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 1154 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-context-08.kt) |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 1155 | |
| 1156 | The result is going to be: |
| 1157 | |
| 1158 | ```text |
| 1159 | request: I'm done and I don't explicitly join my children that are still active |
| 1160 | Coroutine 0 is done |
| 1161 | Coroutine 1 is done |
| 1162 | Coroutine 2 is done |
| 1163 | Now processing of the request is complete |
| 1164 | ``` |
| 1165 | |
| 1166 | <!--- TEST --> |
| 1167 | |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1168 | ### Naming coroutines for debugging |
| 1169 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1170 | Automatically assigned ids are good when coroutines log often and you just need to correlate log records |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1171 | coming from the same coroutine. However, when coroutine is tied to the processing of a specific request |
| 1172 | or doing some specific background task, it is better to name it explicitly for debugging purposes. |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1173 | [CoroutineName] context element serves the same function as a thread name. It'll get displayed in the thread name that |
| 1174 | is executing this coroutine when [debugging mode](#debugging-coroutines-and-threads) is turned on. |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1175 | |
| 1176 | The following example demonstrates this concept: |
| 1177 | |
| 1178 | ```kotlin |
| 1179 | fun log(msg: String) = println("[${Thread.currentThread().name}] $msg") |
| 1180 | |
| 1181 | fun main(args: Array<String>) = runBlocking(CoroutineName("main")) { |
| 1182 | log("Started main coroutine") |
| 1183 | // run two background value computations |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1184 | val v1 = async(CoroutineName("v1coroutine")) { |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1185 | delay(500) |
Roman Elizarov | 674efea | 2017-10-21 17:16:30 +0300 | [diff] [blame] | 1186 | log("Computing v1") |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1187 | 252 |
| 1188 | } |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1189 | val v2 = async(CoroutineName("v2coroutine")) { |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1190 | delay(1000) |
Roman Elizarov | 674efea | 2017-10-21 17:16:30 +0300 | [diff] [blame] | 1191 | log("Computing v2") |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1192 | 6 |
| 1193 | } |
| 1194 | log("The answer for v1 / v2 = ${v1.await() / v2.await()}") |
| 1195 | } |
| 1196 | ``` |
| 1197 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 1198 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-context-09.kt) |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1199 | |
| 1200 | The output it produces with `-Dkotlinx.coroutines.debug` JVM option is similar to: |
| 1201 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1202 | ```text |
Roman Elizarov | 2f6d7c9 | 2017-02-03 15:16:07 +0300 | [diff] [blame] | 1203 | [main @main#1] Started main coroutine |
| 1204 | [ForkJoinPool.commonPool-worker-1 @v1coroutine#2] Computing v1 |
| 1205 | [ForkJoinPool.commonPool-worker-2 @v2coroutine#3] Computing v2 |
| 1206 | [main @main#1] The answer for v1 / v2 = 42 |
| 1207 | ``` |
Roman Elizarov | 1293ccd | 2017-02-01 18:49:54 +0300 | [diff] [blame] | 1208 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1209 | <!--- TEST FLEXIBLE_THREAD --> |
| 1210 | |
Roman Elizarov | 2fd7cb3 | 2017-02-11 23:18:59 +0300 | [diff] [blame] | 1211 | ### Cancellation via explicit job |
| 1212 | |
| 1213 | Let us put our knowledge about contexts, children and jobs together. Assume that our application has |
| 1214 | an object with a lifecycle, but that object is not a coroutine. For example, we are writing an Android application |
| 1215 | and launch various coroutines in the context of an Android activity to perform asynchronous operations to fetch |
| 1216 | and update data, do animations, etc. All of these coroutines must be cancelled when activity is destroyed |
| 1217 | to avoid memory leaks. |
| 1218 | |
| 1219 | We can manage a lifecycle of our coroutines by creating an instance of [Job] that is tied to |
Roman Elizarov | 8839673 | 2017-09-27 21:30:47 +0300 | [diff] [blame] | 1220 | the lifecycle of our activity. A job instance is created using [Job()] factory function |
Roman Elizarov | e8f694e | 2017-11-28 10:12:00 +0300 | [diff] [blame] | 1221 | as the following example shows. For convenience, rather than using `launch(coroutineContext + job)` expression, |
| 1222 | we can write `launch(coroutineContext, parent = job)` to make explicit the fact that the parent job is being used. |
| 1223 | |
| 1224 | Now, a single invocation of [Job.cancel] cancels all the children we've launched. |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 1225 | Moreover, [Job.join] waits for all of them to complete, so we can also use [cancelAndJoin] here in |
| 1226 | this example: |
Roman Elizarov | 2fd7cb3 | 2017-02-11 23:18:59 +0300 | [diff] [blame] | 1227 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 1228 | <!--- INCLUDE |
| 1229 | import kotlin.coroutines.experimental.* |
| 1230 | --> |
| 1231 | |
Roman Elizarov | 2fd7cb3 | 2017-02-11 23:18:59 +0300 | [diff] [blame] | 1232 | ```kotlin |
| 1233 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1234 | val job = Job() // create a job object to manage our lifecycle |
| 1235 | // now launch ten coroutines for a demo, each working for a different time |
| 1236 | val coroutines = List(10) { i -> |
| 1237 | // they are all children of our job object |
Roman Elizarov | e8f694e | 2017-11-28 10:12:00 +0300 | [diff] [blame] | 1238 | launch(coroutineContext, parent = job) { // we use the context of main runBlocking thread, but with our parent job |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 1239 | delay((i + 1) * 200L) // variable delay 200ms, 400ms, ... etc |
Roman Elizarov | 2fd7cb3 | 2017-02-11 23:18:59 +0300 | [diff] [blame] | 1240 | println("Coroutine $i is done") |
| 1241 | } |
| 1242 | } |
| 1243 | println("Launched ${coroutines.size} coroutines") |
| 1244 | delay(500L) // delay for half a second |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 1245 | println("Cancelling the job!") |
| 1246 | job.cancelAndJoin() // cancel all our coroutines and wait for all of them to complete |
Roman Elizarov | 2fd7cb3 | 2017-02-11 23:18:59 +0300 | [diff] [blame] | 1247 | } |
| 1248 | ``` |
| 1249 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 1250 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-context-10.kt) |
Roman Elizarov | 2fd7cb3 | 2017-02-11 23:18:59 +0300 | [diff] [blame] | 1251 | |
| 1252 | The output of this example is: |
| 1253 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1254 | ```text |
Roman Elizarov | 2fd7cb3 | 2017-02-11 23:18:59 +0300 | [diff] [blame] | 1255 | Launched 10 coroutines |
| 1256 | Coroutine 0 is done |
| 1257 | Coroutine 1 is done |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 1258 | Cancelling the job! |
Roman Elizarov | 2fd7cb3 | 2017-02-11 23:18:59 +0300 | [diff] [blame] | 1259 | ``` |
| 1260 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1261 | <!--- TEST --> |
| 1262 | |
Roman Elizarov | 2fd7cb3 | 2017-02-11 23:18:59 +0300 | [diff] [blame] | 1263 | As you can see, only the first three coroutines had printed a message and the others were cancelled |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 1264 | by a single invocation of `job.cancelAndJoin()`. So all we need to do in our hypothetical Android |
Roman Elizarov | 2fd7cb3 | 2017-02-11 23:18:59 +0300 | [diff] [blame] | 1265 | application is to create a parent job object when activity is created, use it for child coroutines, |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 1266 | and cancel it when activity is destroyed. We cannot `join` them in the case of Android lifecycle, |
| 1267 | since it is synchronous, but this joining ability is useful when building backend services to ensure bounded |
| 1268 | resource usage. |
Roman Elizarov | 2fd7cb3 | 2017-02-11 23:18:59 +0300 | [diff] [blame] | 1269 | |
Vsevolod Tolstopyatov | e342597 | 2018-08-22 19:41:57 +0300 | [diff] [blame^] | 1270 | ### Thread-local data |
| 1271 | |
| 1272 | Sometimes it is very convenient to have an ability to pass some thread-local data, but, for coroutines, which |
| 1273 | are not bound to any particular thread, it is hard to achieve it manually without writing a lot of boilerplate. |
| 1274 | |
| 1275 | For [`ThreadLocal`](https://docs.oracle.com/javase/8/docs/api/java/lang/ThreadLocal.html), |
| 1276 | [asContextElement] is here for the rescue. It creates an additional context element, |
| 1277 | which keep the value of the given `ThreadLocal` and restores it every time the coroutine switches its context. |
| 1278 | |
| 1279 | It is easy to demonstrate it in action: |
| 1280 | |
| 1281 | <!--- INCLUDE |
| 1282 | import kotlin.coroutines.experimental.* |
| 1283 | --> |
| 1284 | |
| 1285 | ```kotlin |
| 1286 | val threadLocal = ThreadLocal<String?>() // declare thread-local variable |
| 1287 | |
| 1288 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1289 | threadLocal.set("main") |
| 1290 | println("Pre-main, current thread: ${Thread.currentThread()}, thread local value: '${threadLocal.get()}'") |
| 1291 | val job = launch(CommonPool + threadLocal.asContextElement(value = "launch"), start = CoroutineStart.UNDISPATCHED) { |
| 1292 | println("Launch start, current thread: ${Thread.currentThread()}, thread local value: '${threadLocal.get()}'") |
| 1293 | yield() |
| 1294 | println("After yield, current thread: ${Thread.currentThread()}, thread local value: '${threadLocal.get()}'") |
| 1295 | } |
| 1296 | job.join() |
| 1297 | println("Post-main, current thread: ${Thread.currentThread()}, thread local value: '${threadLocal.get()}'") |
| 1298 | } |
| 1299 | ``` |
| 1300 | |
| 1301 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-context-11.kt) |
| 1302 | |
| 1303 | The output of this example is: |
| 1304 | |
| 1305 | ```text |
| 1306 | Pre-main, current thread: Thread[main @coroutine#1,5,main], thread local value: 'main' |
| 1307 | Launch start, current thread: Thread[main @coroutine#2,5,main], thread local value: 'launch' |
| 1308 | After yield, current thread: Thread[ForkJoinPool.commonPool-worker-1 @coroutine#2,5,main], thread local value: 'launch' |
| 1309 | Post-main, current thread: Thread[main @coroutine#1,5,main], thread local value: 'main' |
| 1310 | ``` |
| 1311 | |
| 1312 | <!--- TEST FLEXIBLE_THREAD --> |
| 1313 | |
| 1314 | Note how thread-local value is restored properly, no matter on what thread the coroutine is executed. |
| 1315 | `ThreadLocal` has first-class support and can be used with any primitive `kotlinx.corotuines` provides. |
| 1316 | It has one key limitation: when thread-local is mutated, a new value is not propagated to the coroutine caller |
| 1317 | (as context element cannot track all `ThreadLocal` object accesses) and updated value is lost on the next suspension. |
| 1318 | Use [withContext] to update the value of the thread-local in a coroutine, see [asContextElement] for more details. |
| 1319 | |
| 1320 | Alternatively, a value can be stored in a mutable box like `class Counter(var i: Int)`, which is, in turn, |
| 1321 | is stored in a thread-local variable. However, in this case you are fully responsible to synchronize |
| 1322 | potentially concurrent modifications to the variable in this box. |
| 1323 | |
| 1324 | For advanced usage, for example for integration with logging MDC, transactional contexts or any other libraries |
| 1325 | which internally use thread-locals for passing data, see documentation for [ThreadContextElement] interface |
| 1326 | that should be implemented. |
| 1327 | |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1328 | ## Exception handling |
| 1329 | |
| 1330 | <!--- INCLUDE .*/example-exceptions-([0-9]+).kt |
| 1331 | --> |
| 1332 | |
| 1333 | This section covers exception handling and cancellation on exceptions. |
| 1334 | We already know that cancelled coroutine throws [CancellationException] in suspension points and that it |
| 1335 | is ignored by coroutines machinery. But what happens if an exception is thrown during cancellation or multiple children of the same |
| 1336 | coroutine throw an exception? |
| 1337 | |
| 1338 | ### Exception propagation |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1339 | |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1340 | Coroutine builders come in two flavors: propagating exceptions automatically ([launch] and [actor]) or exposing them to users ([async] and [produce]). |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1341 | The former treat exceptions as unhandled, similar to Java's `Thread.uncaughExceptionHandler`, while the latter are relying on the user to consume the final |
| 1342 | exception, for example via [await][Deferred.await] or [receive][ReceiveChannel.receive] |
| 1343 | ([produce] and [receive][ReceiveChannel.receive] are covered later in [Channels](#channels) section). |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1344 | |
| 1345 | It can be demonstrated by a simple example: |
| 1346 | |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1347 | ```kotlin |
| 1348 | fun main(args: Array<String>) = runBlocking { |
| 1349 | val job = launch { |
| 1350 | println("Throwing exception from launch") |
| 1351 | throw IndexOutOfBoundsException() // Will be printed to the console by Thread.defaultUncaughtExceptionHandler |
| 1352 | } |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1353 | job.join() |
| 1354 | println("Joined failed job") |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1355 | val deferred = async { |
| 1356 | println("Throwing exception from async") |
| 1357 | throw ArithmeticException() // Nothing is printed, relying on user to call await |
| 1358 | } |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1359 | try { |
| 1360 | deferred.await() |
| 1361 | println("Unreached") |
| 1362 | } catch (e: ArithmeticException) { |
| 1363 | println("Caught ArithmeticException") |
| 1364 | } |
| 1365 | } |
| 1366 | ``` |
| 1367 | |
| 1368 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-exceptions-01.kt) |
| 1369 | |
| 1370 | The output of this code is: |
| 1371 | |
| 1372 | ```text |
| 1373 | Throwing exception from launch |
| 1374 | Exception in thread "ForkJoinPool.commonPool-worker-2 @coroutine#2" java.lang.IndexOutOfBoundsException |
| 1375 | Joined failed job |
| 1376 | Throwing exception from async |
| 1377 | Caught ArithmeticException |
| 1378 | ``` |
| 1379 | |
| 1380 | <!--- TEST EXCEPTION--> |
| 1381 | |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1382 | ### CoroutineExceptionHandler |
| 1383 | |
| 1384 | But what if one does not want to print all exceptions to the console? |
| 1385 | [CoroutineExceptionHandler] context element is used as generic `catch` block of coroutine where custom logging or exception handling may take place. |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1386 | It is similar to using [`Thread.uncaughtExceptionHandler`](https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#setUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler)). |
| 1387 | |
| 1388 | On JVM it's possible to redefine global exception handler for all coroutines by registering [CoroutineExceptionHandler] via |
| 1389 | [`ServiceLoader`](https://docs.oracle.com/javase/8/docs/api/java/util/ServiceLoader.html). |
| 1390 | Global exception handler is similar to |
| 1391 | [`Thread.defaultUncaughtExceptionHandler`](https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#setDefaultUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler)) |
| 1392 | which is used when no more specific handlers are registered. |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1393 | On Android, `uncaughtExceptionPreHandler` is installed as a global coroutine exception handler. |
| 1394 | |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1395 | [CoroutineExceptionHandler] is invoked only on exceptions which are not expected to be handled by the user, |
| 1396 | so registering it in [async] builder and the like of it has no effect. |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1397 | |
| 1398 | ```kotlin |
| 1399 | fun main(args: Array<String>) = runBlocking { |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1400 | val handler = CoroutineExceptionHandler { _, exception -> |
| 1401 | println("Caught $exception") |
| 1402 | } |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1403 | val job = launch(handler) { |
| 1404 | throw AssertionError() |
| 1405 | } |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1406 | val deferred = async(handler) { |
| 1407 | throw ArithmeticException() // Nothing will be printed, relying on user to call deferred.await() |
| 1408 | } |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1409 | joinAll(job, deferred) |
| 1410 | } |
| 1411 | ``` |
| 1412 | |
| 1413 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-exceptions-02.kt) |
| 1414 | |
| 1415 | The output of this code is: |
| 1416 | |
| 1417 | ```text |
| 1418 | Caught java.lang.AssertionError |
| 1419 | ``` |
| 1420 | |
| 1421 | <!--- TEST--> |
| 1422 | |
| 1423 | ### Cancellation and exceptions |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1424 | |
| 1425 | Cancellation is tightly bound with exceptions. Coroutines internally use `CancellationException` for cancellation, these |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1426 | exceptions are ignored by all handlers, so they should be used only as the source of additional debug information, which can |
| 1427 | be obtained by `catch` block. |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1428 | When a coroutine is cancelled using [Job.cancel] without a cause, it terminates, but it does not cancel its parent. |
| 1429 | Cancelling without cause is a mechanism for parent to cancel its children without cancelling itself. |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1430 | |
| 1431 | <!--- INCLUDE |
| 1432 | import kotlin.coroutines.experimental.* |
| 1433 | --> |
| 1434 | |
| 1435 | ```kotlin |
| 1436 | fun main(args: Array<String>) = runBlocking { |
| 1437 | val job = launch(coroutineContext, parent = Job()) { |
| 1438 | val child = launch(coroutineContext) { |
| 1439 | try { |
| 1440 | delay(Long.MAX_VALUE) |
| 1441 | } finally { |
| 1442 | println("Child is cancelled") |
| 1443 | } |
| 1444 | } |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1445 | yield() |
| 1446 | println("Cancelling child") |
| 1447 | child.cancel() |
| 1448 | child.join() |
| 1449 | yield() |
| 1450 | println("Parent is not cancelled") |
| 1451 | } |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1452 | job.join() |
| 1453 | } |
| 1454 | ``` |
| 1455 | |
| 1456 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-exceptions-03.kt) |
| 1457 | |
| 1458 | The output of this code is: |
| 1459 | |
| 1460 | ```text |
| 1461 | Cancelling child |
| 1462 | Child is cancelled |
| 1463 | Parent is not cancelled |
| 1464 | ``` |
| 1465 | |
| 1466 | <!--- TEST--> |
| 1467 | |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1468 | If a coroutine encounters exception other than `CancellationException`, it cancels its parent with that exception. |
| 1469 | This behaviour cannot be overridden and is used to provide stable coroutines hierarchies which do not depend on [CoroutineExceptionHandler] implementation. |
| 1470 | The original exception is handled by the parent when all its children terminate. |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1471 | |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1472 | <!--- INCLUDE |
| 1473 | import kotlin.coroutines.experimental.* |
| 1474 | --> |
| 1475 | |
| 1476 | ```kotlin |
| 1477 | fun main(args: Array<String>) = runBlocking { |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1478 | val handler = CoroutineExceptionHandler { _, exception -> |
| 1479 | println("Caught $exception") |
| 1480 | } |
| 1481 | val job = launch(handler) { |
| 1482 | val child1 = launch(coroutineContext, start = CoroutineStart.ATOMIC) { |
| 1483 | try { |
| 1484 | delay(Long.MAX_VALUE) |
| 1485 | } finally { |
| 1486 | withContext(NonCancellable) { |
| 1487 | println("Children are cancelled, but exception is not handled until all children terminate") |
| 1488 | delay(100) |
| 1489 | println("Last child finished its non cancellable block") |
| 1490 | } |
| 1491 | } |
| 1492 | } |
| 1493 | val child2 = launch(coroutineContext, start = CoroutineStart.ATOMIC) { |
| 1494 | delay(10) |
| 1495 | println("Second child throws an exception") |
| 1496 | throw ArithmeticException() |
| 1497 | } |
| 1498 | } |
| 1499 | job.join() |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1500 | } |
| 1501 | ``` |
| 1502 | |
| 1503 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-exceptions-04.kt) |
| 1504 | |
| 1505 | The output of this code is: |
| 1506 | |
| 1507 | ```text |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1508 | Second child throws an exception |
| 1509 | Children are cancelled, but exception is not handled until all children terminate |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1510 | Last child finished its non cancellable block |
| 1511 | Caught java.lang.ArithmeticException |
| 1512 | ``` |
| 1513 | <!--- TEST--> |
| 1514 | |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1515 | ### Exceptions aggregation |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1516 | |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1517 | What happens if multiple children of a coroutine throw an exception? |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1518 | The general rule is "the first exception wins", so the first thrown exception is exposed to the handler. |
| 1519 | But that may cause lost exceptions, for example if coroutine throws an exception in its `finally` block. |
| 1520 | |
| 1521 | One of the solutions would have been to report each exception separately, |
| 1522 | but then [Deferred.await] should have had the same mechanism to avoid behavioural inconsistency and this |
| 1523 | would cause implementation details of a coroutines (whether it had delegate parts of its work to its children or not) |
| 1524 | to leak to its exception handler. |
| 1525 | |
| 1526 | To avoid that, additional exceptions are suppressed. |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1527 | |
| 1528 | <!--- INCLUDE |
| 1529 | import kotlinx.coroutines.experimental.exceptions.* |
| 1530 | import kotlin.coroutines.experimental.* |
| 1531 | import java.io.* |
| 1532 | --> |
| 1533 | |
| 1534 | ```kotlin |
| 1535 | fun main(args: Array<String>) = runBlocking { |
| 1536 | val handler = CoroutineExceptionHandler { _, exception -> |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1537 | println("Caught $exception with suppressed ${exception.suppressed().contentToString()}") |
| 1538 | } |
| 1539 | val job = launch(handler + coroutineContext, parent = Job()) { |
| 1540 | launch(coroutineContext, start = CoroutineStart.ATOMIC) { |
| 1541 | try { |
| 1542 | delay(Long.MAX_VALUE) |
| 1543 | } finally { |
| 1544 | throw ArithmeticException() |
| 1545 | } |
| 1546 | } |
| 1547 | launch(coroutineContext) { |
| 1548 | throw IOException() |
| 1549 | } |
| 1550 | delay(Long.MAX_VALUE) |
| 1551 | } |
| 1552 | job.join() |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1553 | } |
| 1554 | ``` |
| 1555 | |
| 1556 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-exceptions-05.kt) |
| 1557 | |
| 1558 | The output of this code is: |
| 1559 | |
| 1560 | ```text |
| 1561 | Caught java.io.IOException with suppressed [java.lang.ArithmeticException] |
| 1562 | ``` |
| 1563 | <!--- TEST--> |
| 1564 | |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1565 | Note that this mechanism currently works only on Java version 1.7+. |
| 1566 | Limitation on JS and Native is temporary and will be fixed in the future. |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1567 | |
| 1568 | Cancellation exceptions are transparent and unwrapped by default: |
| 1569 | |
| 1570 | <!--- INCLUDE |
| 1571 | import kotlin.coroutines.experimental.* |
| 1572 | import java.io.* |
| 1573 | --> |
| 1574 | |
| 1575 | ```kotlin |
| 1576 | fun main(args: Array<String>) = runBlocking { |
Roman Elizarov | 563da40 | 2018-08-10 19:18:56 +0300 | [diff] [blame] | 1577 | val handler = CoroutineExceptionHandler { _, exception -> |
| 1578 | println("Caught original $exception") |
| 1579 | } |
| 1580 | val job = launch(handler) { |
| 1581 | val inner = launch(coroutineContext) { |
| 1582 | launch(coroutineContext) { |
| 1583 | launch(coroutineContext) { |
| 1584 | throw IOException() |
| 1585 | } |
| 1586 | } |
| 1587 | } |
| 1588 | try { |
| 1589 | inner.join() |
| 1590 | } catch (e: JobCancellationException) { |
| 1591 | println("Rethrowing JobCancellationException with original cause") |
| 1592 | throw e |
| 1593 | } |
| 1594 | } |
| 1595 | job.join() |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 1596 | } |
| 1597 | ``` |
| 1598 | |
| 1599 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-exceptions-06.kt) |
| 1600 | |
| 1601 | The output of this code is: |
| 1602 | |
| 1603 | ```text |
| 1604 | Rethrowing JobCancellationException with original cause |
| 1605 | Caught original java.io.IOException |
| 1606 | ``` |
| 1607 | <!--- TEST--> |
| 1608 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1609 | ## Channels |
Roman Elizarov | 7deefb8 | 2017-01-31 10:33:17 +0300 | [diff] [blame] | 1610 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1611 | Deferred values provide a convenient way to transfer a single value between coroutines. |
| 1612 | Channels provide a way to transfer a stream of values. |
| 1613 | |
| 1614 | <!--- INCLUDE .*/example-channel-([0-9]+).kt |
| 1615 | import kotlinx.coroutines.experimental.channels.* |
| 1616 | --> |
| 1617 | |
| 1618 | ### Channel basics |
| 1619 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 1620 | A [Channel] is conceptually very similar to `BlockingQueue`. One key difference is that |
| 1621 | instead of a blocking `put` operation it has a suspending [send][SendChannel.send], and instead of |
| 1622 | a blocking `take` operation it has a suspending [receive][ReceiveChannel.receive]. |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1623 | |
| 1624 | ```kotlin |
| 1625 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1626 | val channel = Channel<Int>() |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1627 | launch { |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1628 | // this might be heavy CPU-consuming computation or async logic, we'll just send five squares |
| 1629 | for (x in 1..5) channel.send(x * x) |
| 1630 | } |
| 1631 | // here we print five received integers: |
| 1632 | repeat(5) { println(channel.receive()) } |
| 1633 | println("Done!") |
| 1634 | } |
| 1635 | ``` |
| 1636 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 1637 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-channel-01.kt) |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1638 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1639 | The output of this code is: |
| 1640 | |
| 1641 | ```text |
| 1642 | 1 |
| 1643 | 4 |
| 1644 | 9 |
| 1645 | 16 |
| 1646 | 25 |
| 1647 | Done! |
| 1648 | ``` |
| 1649 | |
| 1650 | <!--- TEST --> |
| 1651 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1652 | ### Closing and iteration over channels |
| 1653 | |
| 1654 | Unlike a queue, a channel can be closed to indicate that no more elements are coming. |
| 1655 | On the receiver side it is convenient to use a regular `for` loop to receive elements |
| 1656 | from the channel. |
| 1657 | |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 1658 | Conceptually, a [close][SendChannel.close] is like sending a special close token to the channel. |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1659 | The iteration stops as soon as this close token is received, so there is a guarantee |
| 1660 | that all previously sent elements before the close are received: |
| 1661 | |
| 1662 | ```kotlin |
| 1663 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1664 | val channel = Channel<Int>() |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1665 | launch { |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1666 | for (x in 1..5) channel.send(x * x) |
| 1667 | channel.close() // we're done sending |
| 1668 | } |
| 1669 | // here we print received values using `for` loop (until the channel is closed) |
| 1670 | for (y in channel) println(y) |
| 1671 | println("Done!") |
| 1672 | } |
| 1673 | ``` |
| 1674 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 1675 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-channel-02.kt) |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1676 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1677 | <!--- TEST |
| 1678 | 1 |
| 1679 | 4 |
| 1680 | 9 |
| 1681 | 16 |
| 1682 | 25 |
| 1683 | Done! |
| 1684 | --> |
| 1685 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1686 | ### Building channel producers |
| 1687 | |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 1688 | The pattern where a coroutine is producing a sequence of elements is quite common. |
| 1689 | This is a part of _producer-consumer_ pattern that is often found in concurrent code. |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1690 | You could abstract such a producer into a function that takes channel as its parameter, but this goes contrary |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 1691 | to common sense that results must be returned from functions. |
| 1692 | |
Roman Elizarov | 86349be | 2017-03-17 16:47:37 +0300 | [diff] [blame] | 1693 | There is a convenience coroutine builder named [produce] that makes it easy to do it right on producer side, |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 1694 | and an extension function [consumeEach], that replaces a `for` loop on the consumer side: |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1695 | |
| 1696 | ```kotlin |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1697 | fun produceSquares() = produce<Int> { |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1698 | for (x in 1..5) send(x * x) |
| 1699 | } |
| 1700 | |
| 1701 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1702 | val squares = produceSquares() |
Roman Elizarov | 86349be | 2017-03-17 16:47:37 +0300 | [diff] [blame] | 1703 | squares.consumeEach { println(it) } |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1704 | println("Done!") |
| 1705 | } |
| 1706 | ``` |
| 1707 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 1708 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-channel-03.kt) |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1709 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1710 | <!--- TEST |
| 1711 | 1 |
| 1712 | 4 |
| 1713 | 9 |
| 1714 | 16 |
| 1715 | 25 |
| 1716 | Done! |
| 1717 | --> |
| 1718 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1719 | ### Pipelines |
| 1720 | |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1721 | A pipeline is a pattern where one coroutine is producing, possibly infinite, stream of values: |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1722 | |
| 1723 | ```kotlin |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1724 | fun produceNumbers() = produce<Int> { |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1725 | var x = 1 |
| 1726 | while (true) send(x++) // infinite stream of integers starting from 1 |
| 1727 | } |
| 1728 | ``` |
| 1729 | |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 1730 | And another coroutine or coroutines are consuming that stream, doing some processing, and producing some other results. |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1731 | In the below example the numbers are just squared: |
| 1732 | |
| 1733 | ```kotlin |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1734 | fun square(numbers: ReceiveChannel<Int>) = produce<Int> { |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1735 | for (x in numbers) send(x * x) |
| 1736 | } |
| 1737 | ``` |
| 1738 | |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 1739 | The main code starts and connects the whole pipeline: |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1740 | |
| 1741 | ```kotlin |
| 1742 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1743 | val numbers = produceNumbers() // produces integers from 1 and on |
| 1744 | val squares = square(numbers) // squares integers |
| 1745 | for (i in 1..5) println(squares.receive()) // print first five |
| 1746 | println("Done!") // we are done |
| 1747 | squares.cancel() // need to cancel these coroutines in a larger app |
| 1748 | numbers.cancel() |
| 1749 | } |
| 1750 | ``` |
| 1751 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 1752 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-channel-04.kt) |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1753 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1754 | <!--- TEST |
| 1755 | 1 |
| 1756 | 4 |
| 1757 | 9 |
| 1758 | 16 |
| 1759 | 25 |
| 1760 | Done! |
| 1761 | --> |
| 1762 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1763 | We don't have to cancel these coroutines in this example app, because |
| 1764 | [coroutines are like daemon threads](#coroutines-are-like-daemon-threads), |
| 1765 | but in a larger app we'll need to stop our pipeline if we don't need it anymore. |
| 1766 | Alternatively, we could have run pipeline coroutines as |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1767 | [children of a main coroutine](#children-of-a-coroutine) as is demonstrated in the following example. |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1768 | |
| 1769 | ### Prime numbers with pipeline |
| 1770 | |
Cedric Beust | fa0b28f | 2017-02-07 07:07:25 -0800 | [diff] [blame] | 1771 | Let's take pipelines to the extreme with an example that generates prime numbers using a pipeline |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1772 | of coroutines. We start with an infinite sequence of numbers. This time we introduce an |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1773 | explicit `context` parameter and pass it to [produce] builder, |
| 1774 | so that caller can control where our coroutines run: |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1775 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 1776 | <!--- INCLUDE |
| 1777 | import kotlin.coroutines.experimental.* |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1778 | --> |
| 1779 | |
| 1780 | ```kotlin |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 1781 | fun numbersFrom(context: CoroutineContext, start: Int) = produce<Int>(context) { |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1782 | var x = start |
| 1783 | while (true) send(x++) // infinite stream of integers from start |
| 1784 | } |
| 1785 | ``` |
| 1786 | |
| 1787 | The following pipeline stage filters an incoming stream of numbers, removing all the numbers |
| 1788 | that are divisible by the given prime number: |
| 1789 | |
| 1790 | ```kotlin |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 1791 | fun filter(context: CoroutineContext, numbers: ReceiveChannel<Int>, prime: Int) = produce<Int>(context) { |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1792 | for (x in numbers) if (x % prime != 0) send(x) |
| 1793 | } |
| 1794 | ``` |
| 1795 | |
| 1796 | Now we build our pipeline by starting a stream of numbers from 2, taking a prime number from the current channel, |
Roman Elizarov | 62500ba | 2017-02-09 18:55:40 +0300 | [diff] [blame] | 1797 | and launching new pipeline stage for each prime number found: |
| 1798 | |
| 1799 | ``` |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 1800 | numbersFrom(2) -> filter(2) -> filter(3) -> filter(5) -> filter(7) ... |
Roman Elizarov | 62500ba | 2017-02-09 18:55:40 +0300 | [diff] [blame] | 1801 | ``` |
| 1802 | |
| 1803 | The following example prints the first ten prime numbers, |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 1804 | running the whole pipeline in the context of the main thread. Since all the coroutines are launched as |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 1805 | children of the main [runBlocking] coroutine in its |
| 1806 | [coroutineContext](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.experimental/coroutine-context.html), |
| 1807 | we don't have to keep an explicit list of all the coroutines we have started. |
Roman Elizarov | 3e387b8 | 2017-12-04 13:49:11 +0300 | [diff] [blame] | 1808 | We use [cancelChildren][kotlin.coroutines.experimental.CoroutineContext.cancelChildren] |
| 1809 | extension function to cancel all the children coroutines. |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1810 | |
| 1811 | ```kotlin |
| 1812 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 1813 | var cur = numbersFrom(coroutineContext, 2) |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1814 | for (i in 1..10) { |
| 1815 | val prime = cur.receive() |
| 1816 | println(prime) |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 1817 | cur = filter(coroutineContext, cur, prime) |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1818 | } |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 1819 | coroutineContext.cancelChildren() // cancel all children to let main finish |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1820 | } |
| 1821 | ``` |
| 1822 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 1823 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-channel-05.kt) |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1824 | |
| 1825 | The output of this code is: |
| 1826 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1827 | ```text |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1828 | 2 |
| 1829 | 3 |
| 1830 | 5 |
| 1831 | 7 |
| 1832 | 11 |
| 1833 | 13 |
| 1834 | 17 |
| 1835 | 19 |
| 1836 | 23 |
| 1837 | 29 |
| 1838 | ``` |
| 1839 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1840 | <!--- TEST --> |
| 1841 | |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1842 | Note, that you can build the same pipeline using |
| 1843 | [`buildIterator`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.experimental/build-iterator.html) |
| 1844 | coroutine builder from the standard library. |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 1845 | Replace `produce` with `buildIterator`, `send` with `yield`, `receive` with `next`, |
Roman Elizarov | 62500ba | 2017-02-09 18:55:40 +0300 | [diff] [blame] | 1846 | `ReceiveChannel` with `Iterator`, and get rid of the context. You will not need `runBlocking` either. |
| 1847 | However, the benefit of a pipeline that uses channels as shown above is that it can actually use |
| 1848 | multiple CPU cores if you run it in [CommonPool] context. |
| 1849 | |
Roman Elizarov | a5e653f | 2017-02-13 13:49:55 +0300 | [diff] [blame] | 1850 | Anyway, this is an extremely impractical way to find prime numbers. In practice, pipelines do involve some |
Roman Elizarov | 62500ba | 2017-02-09 18:55:40 +0300 | [diff] [blame] | 1851 | other suspending invocations (like asynchronous calls to remote services) and these pipelines cannot be |
| 1852 | built using `buildSeqeunce`/`buildIterator`, because they do not allow arbitrary suspension, unlike |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1853 | `produce`, which is fully asynchronous. |
Roman Elizarov | 62500ba | 2017-02-09 18:55:40 +0300 | [diff] [blame] | 1854 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1855 | ### Fan-out |
| 1856 | |
| 1857 | Multiple coroutines may receive from the same channel, distributing work between themselves. |
| 1858 | Let us start with a producer coroutine that is periodically producing integers |
| 1859 | (ten numbers per second): |
| 1860 | |
| 1861 | ```kotlin |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1862 | fun produceNumbers() = produce<Int> { |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1863 | var x = 1 // start from 1 |
| 1864 | while (true) { |
| 1865 | send(x++) // produce next |
| 1866 | delay(100) // wait 0.1s |
| 1867 | } |
| 1868 | } |
| 1869 | ``` |
| 1870 | |
| 1871 | Then we can have several processor coroutines. In this example, they just print their id and |
| 1872 | received number: |
| 1873 | |
| 1874 | ```kotlin |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 1875 | fun launchProcessor(id: Int, channel: ReceiveChannel<Int>) = launch { |
bill | 58c61c7 | 2018-06-21 17:24:08 -0500 | [diff] [blame] | 1876 | for (msg in channel) { |
| 1877 | println("Processor #$id received $msg") |
Roman Elizarov | ec9384c | 2017-03-02 22:09:08 +0300 | [diff] [blame] | 1878 | } |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1879 | } |
| 1880 | ``` |
| 1881 | |
Roman Elizarov | 35d2c34 | 2017-07-20 14:54:39 +0300 | [diff] [blame] | 1882 | Now let us launch five processors and let them work for almost a second. See what happens: |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1883 | |
| 1884 | ```kotlin |
| 1885 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1886 | val producer = produceNumbers() |
| 1887 | repeat(5) { launchProcessor(it, producer) } |
Roman Elizarov | 35d2c34 | 2017-07-20 14:54:39 +0300 | [diff] [blame] | 1888 | delay(950) |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1889 | producer.cancel() // cancel producer coroutine and thus kill them all |
| 1890 | } |
| 1891 | ``` |
| 1892 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 1893 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-channel-06.kt) |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1894 | |
| 1895 | The output will be similar to the the following one, albeit the processor ids that receive |
| 1896 | each specific integer may be different: |
| 1897 | |
| 1898 | ``` |
| 1899 | Processor #2 received 1 |
| 1900 | Processor #4 received 2 |
| 1901 | Processor #0 received 3 |
| 1902 | Processor #1 received 4 |
| 1903 | Processor #3 received 5 |
| 1904 | Processor #2 received 6 |
| 1905 | Processor #4 received 7 |
| 1906 | Processor #0 received 8 |
| 1907 | Processor #1 received 9 |
| 1908 | Processor #3 received 10 |
| 1909 | ``` |
| 1910 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1911 | <!--- TEST lines.size == 10 && lines.withIndex().all { (i, line) -> line.startsWith("Processor #") && line.endsWith(" received ${i + 1}") } --> |
| 1912 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1913 | Note, that cancelling a producer coroutine closes its channel, thus eventually terminating iteration |
| 1914 | over the channel that processor coroutines are doing. |
| 1915 | |
Roman Elizarov | 1ce6c0b | 2018-06-28 10:37:20 +0300 | [diff] [blame] | 1916 | Also, pay attention to how we explicitly iterate over channel with `for` loop to perform fan-out in `launchProcessor` code. |
| 1917 | Unlike `consumeEach`, this `for` loop pattern is perfectly safe to use from multiple coroutines. If one of the processor |
| 1918 | coroutines fails, then others would still be processing the channel, while a processor that is written via `consumeEach` |
| 1919 | always consumes (cancels) the underlying channel on its normal or abnormal termination. |
| 1920 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1921 | ### Fan-in |
| 1922 | |
| 1923 | Multiple coroutines may send to the same channel. |
| 1924 | For example, let us have a channel of strings, and a suspending function that |
| 1925 | repeatedly sends a specified string to this channel with a specified delay: |
| 1926 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 1927 | <!--- INCLUDE |
| 1928 | import kotlin.coroutines.experimental.* |
| 1929 | --> |
| 1930 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1931 | ```kotlin |
| 1932 | suspend fun sendString(channel: SendChannel<String>, s: String, time: Long) { |
| 1933 | while (true) { |
| 1934 | delay(time) |
| 1935 | channel.send(s) |
| 1936 | } |
| 1937 | } |
| 1938 | ``` |
| 1939 | |
Cedric Beust | fa0b28f | 2017-02-07 07:07:25 -0800 | [diff] [blame] | 1940 | Now, let us see what happens if we launch a couple of coroutines sending strings |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 1941 | (in this example we launch them in the context of the main thread as main coroutine's children): |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1942 | |
| 1943 | ```kotlin |
| 1944 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1945 | val channel = Channel<String>() |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 1946 | launch(coroutineContext) { sendString(channel, "foo", 200L) } |
| 1947 | launch(coroutineContext) { sendString(channel, "BAR!", 500L) } |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1948 | repeat(6) { // receive first six |
| 1949 | println(channel.receive()) |
| 1950 | } |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 1951 | coroutineContext.cancelChildren() // cancel all children to let main finish |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1952 | } |
| 1953 | ``` |
| 1954 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 1955 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-channel-07.kt) |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1956 | |
| 1957 | The output is: |
| 1958 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1959 | ```text |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1960 | foo |
| 1961 | foo |
| 1962 | BAR! |
| 1963 | foo |
| 1964 | foo |
| 1965 | BAR! |
| 1966 | ``` |
| 1967 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 1968 | <!--- TEST --> |
| 1969 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1970 | ### Buffered channels |
| 1971 | |
| 1972 | The channels shown so far had no buffer. Unbuffered channels transfer elements when sender and receiver |
| 1973 | meet each other (aka rendezvous). If send is invoked first, then it is suspended until receive is invoked, |
| 1974 | if receive is invoked first, it is suspended until send is invoked. |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 1975 | |
Roman Elizarov | 8839673 | 2017-09-27 21:30:47 +0300 | [diff] [blame] | 1976 | Both [Channel()] factory function and [produce] builder take an optional `capacity` parameter to |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1977 | specify _buffer size_. Buffer allows senders to send multiple elements before suspending, |
| 1978 | similar to the `BlockingQueue` with a specified capacity, which blocks when buffer is full. |
| 1979 | |
| 1980 | Take a look at the behavior of the following code: |
| 1981 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 1982 | <!--- INCLUDE |
| 1983 | import kotlin.coroutines.experimental.* |
| 1984 | --> |
| 1985 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1986 | ```kotlin |
| 1987 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 1988 | val channel = Channel<Int>(4) // create buffered channel |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 1989 | val sender = launch(coroutineContext) { // launch sender coroutine |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1990 | repeat(10) { |
| 1991 | println("Sending $it") // print before sending each element |
| 1992 | channel.send(it) // will suspend when buffer is full |
| 1993 | } |
| 1994 | } |
| 1995 | // don't receive anything... just wait.... |
| 1996 | delay(1000) |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 1997 | sender.cancel() // cancel sender coroutine |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 1998 | } |
| 1999 | ``` |
| 2000 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2001 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-channel-08.kt) |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2002 | |
| 2003 | It prints "sending" _five_ times using a buffered channel with capacity of _four_: |
| 2004 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2005 | ```text |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2006 | Sending 0 |
| 2007 | Sending 1 |
| 2008 | Sending 2 |
| 2009 | Sending 3 |
| 2010 | Sending 4 |
| 2011 | ``` |
| 2012 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2013 | <!--- TEST --> |
| 2014 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 2015 | The first four elements are added to the buffer and the sender suspends when trying to send the fifth one. |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 2016 | |
Vsevolod Tolstopyatov | 03d2ff7 | 2018-05-29 17:28:20 +0300 | [diff] [blame] | 2017 | ### Ticker channels |
Vsevolod Tolstopyatov | 1dbc25e | 2018-04-18 14:50:26 +0300 | [diff] [blame] | 2018 | |
Roman Elizarov | b5328a7 | 2018-06-06 18:31:21 +0300 | [diff] [blame] | 2019 | Ticker channel is a special rendezvous channel that produces `Unit` every time given delay passes since last consumption from this channel. |
| 2020 | Though it may seem to be useless standalone, it is a useful building block to create complex time-based [produce] |
Roman Elizarov | 0c090ed | 2018-06-29 19:51:07 +0300 | [diff] [blame] | 2021 | pipelines and operators that do windowing and other time-dependent processing. |
Roman Elizarov | b5328a7 | 2018-06-06 18:31:21 +0300 | [diff] [blame] | 2022 | Ticker channel can be used in [select] to perform "on tick" action. |
Vsevolod Tolstopyatov | 1dbc25e | 2018-04-18 14:50:26 +0300 | [diff] [blame] | 2023 | |
Roman Elizarov | b5328a7 | 2018-06-06 18:31:21 +0300 | [diff] [blame] | 2024 | To create such channel use a factory method [ticker]. |
| 2025 | To indicate that no further elements are needed use [ReceiveChannel.cancel] method on it. |
Vsevolod Tolstopyatov | 1dbc25e | 2018-04-18 14:50:26 +0300 | [diff] [blame] | 2026 | |
| 2027 | Now let's see how it works in practice: |
Vsevolod Tolstopyatov | 1dbc25e | 2018-04-18 14:50:26 +0300 | [diff] [blame] | 2028 | |
| 2029 | ```kotlin |
| 2030 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | b5328a7 | 2018-06-06 18:31:21 +0300 | [diff] [blame] | 2031 | val tickerChannel = ticker(delay = 100, initialDelay = 0) // create ticker channel |
Vsevolod Tolstopyatov | 03d2ff7 | 2018-05-29 17:28:20 +0300 | [diff] [blame] | 2032 | var nextElement = withTimeoutOrNull(1) { tickerChannel.receive() } |
paolop | 1d6e493 | 2018-07-02 08:46:34 +0000 | [diff] [blame] | 2033 | println("Initial element is available immediately: $nextElement") // initial delay hasn't passed yet |
Vsevolod Tolstopyatov | 1dbc25e | 2018-04-18 14:50:26 +0300 | [diff] [blame] | 2034 | |
paolop | 1d6e493 | 2018-07-02 08:46:34 +0000 | [diff] [blame] | 2035 | nextElement = withTimeoutOrNull(50) { tickerChannel.receive() } // all subsequent elements has 100ms delay |
Vsevolod Tolstopyatov | 1dbc25e | 2018-04-18 14:50:26 +0300 | [diff] [blame] | 2036 | println("Next element is not ready in 50 ms: $nextElement") |
| 2037 | |
Roman Elizarov | b5328a7 | 2018-06-06 18:31:21 +0300 | [diff] [blame] | 2038 | nextElement = withTimeoutOrNull(60) { tickerChannel.receive() } |
Vsevolod Tolstopyatov | 1dbc25e | 2018-04-18 14:50:26 +0300 | [diff] [blame] | 2039 | println("Next element is ready in 100 ms: $nextElement") |
| 2040 | |
| 2041 | // Emulate large consumption delays |
Roman Elizarov | b5328a7 | 2018-06-06 18:31:21 +0300 | [diff] [blame] | 2042 | println("Consumer pauses for 150ms") |
Vsevolod Tolstopyatov | 1dbc25e | 2018-04-18 14:50:26 +0300 | [diff] [blame] | 2043 | delay(150) |
| 2044 | // Next element is available immediately |
Vsevolod Tolstopyatov | 03d2ff7 | 2018-05-29 17:28:20 +0300 | [diff] [blame] | 2045 | nextElement = withTimeoutOrNull(1) { tickerChannel.receive() } |
Vsevolod Tolstopyatov | 1dbc25e | 2018-04-18 14:50:26 +0300 | [diff] [blame] | 2046 | println("Next element is available immediately after large consumer delay: $nextElement") |
| 2047 | // Note that the pause between `receive` calls is taken into account and next element arrives faster |
Roman Elizarov | b5328a7 | 2018-06-06 18:31:21 +0300 | [diff] [blame] | 2048 | nextElement = withTimeoutOrNull(60) { tickerChannel.receive() } |
Vsevolod Tolstopyatov | 1dbc25e | 2018-04-18 14:50:26 +0300 | [diff] [blame] | 2049 | println("Next element is ready in 50ms after consumer pause in 150ms: $nextElement") |
| 2050 | |
Vsevolod Tolstopyatov | 03d2ff7 | 2018-05-29 17:28:20 +0300 | [diff] [blame] | 2051 | tickerChannel.cancel() // indicate that no more elements are needed |
Vsevolod Tolstopyatov | 1dbc25e | 2018-04-18 14:50:26 +0300 | [diff] [blame] | 2052 | } |
| 2053 | ``` |
| 2054 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2055 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-channel-10.kt) |
Vsevolod Tolstopyatov | 1dbc25e | 2018-04-18 14:50:26 +0300 | [diff] [blame] | 2056 | |
| 2057 | It prints following lines: |
| 2058 | |
| 2059 | ```text |
| 2060 | Initial element is available immediately: kotlin.Unit |
| 2061 | Next element is not ready in 50 ms: null |
| 2062 | Next element is ready in 100 ms: kotlin.Unit |
Roman Elizarov | b5328a7 | 2018-06-06 18:31:21 +0300 | [diff] [blame] | 2063 | Consumer pauses for 150ms |
Vsevolod Tolstopyatov | 1dbc25e | 2018-04-18 14:50:26 +0300 | [diff] [blame] | 2064 | Next element is available immediately after large consumer delay: kotlin.Unit |
| 2065 | Next element is ready in 50ms after consumer pause in 150ms: kotlin.Unit |
| 2066 | ``` |
| 2067 | |
| 2068 | <!--- TEST --> |
| 2069 | |
Roman Elizarov | b5328a7 | 2018-06-06 18:31:21 +0300 | [diff] [blame] | 2070 | Note that [ticker] is aware of possible consumer pauses and, by default, adjusts next produced element |
| 2071 | delay if a pause occurs, trying to maintain a fixed rate of produced elements. |
| 2072 | |
Roman Elizarov | 0c090ed | 2018-06-29 19:51:07 +0300 | [diff] [blame] | 2073 | Optionally, a `mode` parameter equal to [TickerMode.FIXED_DELAY] can be specified to maintain a fixed |
Roman Elizarov | b5328a7 | 2018-06-06 18:31:21 +0300 | [diff] [blame] | 2074 | delay between elements. |
Vsevolod Tolstopyatov | 1dbc25e | 2018-04-18 14:50:26 +0300 | [diff] [blame] | 2075 | |
Roman Elizarov | b0517ba | 2017-02-27 14:03:14 +0300 | [diff] [blame] | 2076 | ### Channels are fair |
| 2077 | |
| 2078 | Send and receive operations to channels are _fair_ with respect to the order of their invocation from |
| 2079 | multiple coroutines. They are served in first-in first-out order, e.g. the first coroutine to invoke `receive` |
| 2080 | gets the element. In the following example two coroutines "ping" and "pong" are |
| 2081 | receiving the "ball" object from the shared "table" channel. |
| 2082 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 2083 | <!--- INCLUDE |
| 2084 | import kotlin.coroutines.experimental.* |
| 2085 | --> |
| 2086 | |
Roman Elizarov | b0517ba | 2017-02-27 14:03:14 +0300 | [diff] [blame] | 2087 | ```kotlin |
| 2088 | data class Ball(var hits: Int) |
| 2089 | |
| 2090 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 2091 | val table = Channel<Ball>() // a shared table |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 2092 | launch(coroutineContext) { player("ping", table) } |
| 2093 | launch(coroutineContext) { player("pong", table) } |
Roman Elizarov | b0517ba | 2017-02-27 14:03:14 +0300 | [diff] [blame] | 2094 | table.send(Ball(0)) // serve the ball |
| 2095 | delay(1000) // delay 1 second |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 2096 | coroutineContext.cancelChildren() // game over, cancel them |
Roman Elizarov | b0517ba | 2017-02-27 14:03:14 +0300 | [diff] [blame] | 2097 | } |
| 2098 | |
| 2099 | suspend fun player(name: String, table: Channel<Ball>) { |
| 2100 | for (ball in table) { // receive the ball in a loop |
| 2101 | ball.hits++ |
| 2102 | println("$name $ball") |
Roman Elizarov | f526b13 | 2017-03-10 16:07:14 +0300 | [diff] [blame] | 2103 | delay(300) // wait a bit |
Roman Elizarov | b0517ba | 2017-02-27 14:03:14 +0300 | [diff] [blame] | 2104 | table.send(ball) // send the ball back |
| 2105 | } |
| 2106 | } |
| 2107 | ``` |
| 2108 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2109 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-channel-09.kt) |
Roman Elizarov | b0517ba | 2017-02-27 14:03:14 +0300 | [diff] [blame] | 2110 | |
| 2111 | The "ping" coroutine is started first, so it is the first one to receive the ball. Even though "ping" |
| 2112 | coroutine immediately starts receiving the ball again after sending it back to the table, the ball gets |
| 2113 | received by the "pong" coroutine, because it was already waiting for it: |
| 2114 | |
| 2115 | ```text |
| 2116 | ping Ball(hits=1) |
| 2117 | pong Ball(hits=2) |
| 2118 | ping Ball(hits=3) |
| 2119 | pong Ball(hits=4) |
Roman Elizarov | b0517ba | 2017-02-27 14:03:14 +0300 | [diff] [blame] | 2120 | ``` |
| 2121 | |
| 2122 | <!--- TEST --> |
| 2123 | |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 2124 | Note, that sometimes channels may produce executions that look unfair due to the nature of the executor |
| 2125 | that is being used. See [this issue](https://github.com/Kotlin/kotlinx.coroutines/issues/111) for details. |
| 2126 | |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2127 | ## Shared mutable state and concurrency |
| 2128 | |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 2129 | Coroutines can be executed concurrently using a multi-threaded dispatcher like the default [CommonPool]. It presents |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2130 | all the usual concurrency problems. The main problem being synchronization of access to **shared mutable state**. |
| 2131 | Some solutions to this problem in the land of coroutines are similar to the solutions in the multi-threaded world, |
| 2132 | but others are unique. |
| 2133 | |
| 2134 | ### The problem |
| 2135 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2136 | Let us launch a thousand coroutines all doing the same action thousand times (for a total of a million executions). |
| 2137 | We'll also measure their completion time for further comparisons: |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2138 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2139 | <!--- INCLUDE .*/example-sync-03.kt |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 2140 | import java.util.concurrent.atomic.* |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2141 | --> |
| 2142 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2143 | <!--- INCLUDE .*/example-sync-06.kt |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 2144 | import kotlinx.coroutines.experimental.sync.* |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2145 | --> |
| 2146 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2147 | <!--- INCLUDE .*/example-sync-07.kt |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2148 | import kotlinx.coroutines.experimental.channels.* |
| 2149 | --> |
| 2150 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 2151 | <!--- INCLUDE .*/example-sync-([0-9a-z]+).kt |
| 2152 | import kotlin.system.* |
| 2153 | import kotlin.coroutines.experimental.* |
| 2154 | --> |
| 2155 | |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2156 | ```kotlin |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2157 | suspend fun massiveRun(context: CoroutineContext, action: suspend () -> Unit) { |
| 2158 | val n = 1000 // number of coroutines to launch |
| 2159 | val k = 1000 // times an action is repeated by each coroutine |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2160 | val time = measureTimeMillis { |
| 2161 | val jobs = List(n) { |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2162 | launch(context) { |
| 2163 | repeat(k) { action() } |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2164 | } |
| 2165 | } |
| 2166 | jobs.forEach { it.join() } |
| 2167 | } |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2168 | println("Completed ${n * k} actions in $time ms") |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2169 | } |
| 2170 | ``` |
| 2171 | |
Roman Elizarov | 43e9011 | 2017-05-10 11:25:20 +0300 | [diff] [blame] | 2172 | <!--- INCLUDE .*/example-sync-([0-9a-z]+).kt --> |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2173 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2174 | We start with a very simple action that increments a shared mutable variable using |
| 2175 | multi-threaded [CommonPool] context. |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2176 | |
| 2177 | ```kotlin |
| 2178 | var counter = 0 |
| 2179 | |
| 2180 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2181 | massiveRun(CommonPool) { |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2182 | counter++ |
| 2183 | } |
| 2184 | println("Counter = $counter") |
| 2185 | } |
| 2186 | ``` |
| 2187 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2188 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-sync-01.kt) |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2189 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2190 | <!--- TEST LINES_START |
| 2191 | Completed 1000000 actions in |
| 2192 | Counter = |
| 2193 | --> |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2194 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2195 | What does it print at the end? It is highly unlikely to ever print "Counter = 1000000", because a thousand coroutines |
| 2196 | increment the `counter` concurrently from multiple threads without any synchronization. |
| 2197 | |
Roman Elizarov | 43e9011 | 2017-05-10 11:25:20 +0300 | [diff] [blame] | 2198 | > Note: if you have an old system with 2 or fewer CPUs, then you _will_ consistently see 1000000, because |
| 2199 | `CommonPool` is running in only one thread in this case. To reproduce the problem you'll need to make the |
| 2200 | following change: |
| 2201 | |
| 2202 | ```kotlin |
| 2203 | val mtContext = newFixedThreadPoolContext(2, "mtPool") // explicitly define context with two threads |
| 2204 | var counter = 0 |
| 2205 | |
| 2206 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 2207 | massiveRun(mtContext) { // use it instead of CommonPool in this sample and below |
| 2208 | counter++ |
| 2209 | } |
| 2210 | println("Counter = $counter") |
| 2211 | } |
| 2212 | ``` |
| 2213 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2214 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-sync-01b.kt) |
Roman Elizarov | 43e9011 | 2017-05-10 11:25:20 +0300 | [diff] [blame] | 2215 | |
| 2216 | <!--- TEST LINES_START |
| 2217 | Completed 1000000 actions in |
| 2218 | Counter = |
| 2219 | --> |
| 2220 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2221 | ### Volatiles are of no help |
| 2222 | |
| 2223 | There is common misconception that making a variable `volatile` solves concurrency problem. Let us try it: |
| 2224 | |
| 2225 | ```kotlin |
| 2226 | @Volatile // in Kotlin `volatile` is an annotation |
| 2227 | var counter = 0 |
| 2228 | |
| 2229 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 2230 | massiveRun(CommonPool) { |
| 2231 | counter++ |
| 2232 | } |
| 2233 | println("Counter = $counter") |
| 2234 | } |
| 2235 | ``` |
| 2236 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2237 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-sync-02.kt) |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2238 | |
| 2239 | <!--- TEST LINES_START |
| 2240 | Completed 1000000 actions in |
| 2241 | Counter = |
| 2242 | --> |
| 2243 | |
| 2244 | This code works slower, but we still don't get "Counter = 1000000" at the end, because volatile variables guarantee |
| 2245 | linearizable (this is a technical term for "atomic") reads and writes to the corresponding variable, but |
| 2246 | do not provide atomicity of larger actions (increment in our case). |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2247 | |
| 2248 | ### Thread-safe data structures |
| 2249 | |
| 2250 | The general solution that works both for threads and for coroutines is to use a thread-safe (aka synchronized, |
| 2251 | linearizable, or atomic) data structure that provides all the necessarily synchronization for the corresponding |
| 2252 | operations that needs to be performed on a shared state. |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2253 | In the case of a simple counter we can use `AtomicInteger` class which has atomic `incrementAndGet` operations: |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2254 | |
| 2255 | ```kotlin |
| 2256 | var counter = AtomicInteger() |
| 2257 | |
| 2258 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2259 | massiveRun(CommonPool) { |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2260 | counter.incrementAndGet() |
| 2261 | } |
| 2262 | println("Counter = ${counter.get()}") |
| 2263 | } |
| 2264 | ``` |
| 2265 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2266 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-sync-03.kt) |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2267 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2268 | <!--- TEST ARBITRARY_TIME |
| 2269 | Completed 1000000 actions in xxx ms |
| 2270 | Counter = 1000000 |
| 2271 | --> |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2272 | |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2273 | This is the fastest solution for this particular problem. It works for plain counters, collections, queues and other |
| 2274 | standard data structures and basic operations on them. However, it does not easily scale to complex |
| 2275 | state or to complex operations that do not have ready-to-use thread-safe implementations. |
| 2276 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2277 | ### Thread confinement fine-grained |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2278 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2279 | _Thread confinement_ is an approach to the problem of shared mutable state where all access to the particular shared |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2280 | state is confined to a single thread. It is typically used in UI applications, where all UI state is confined to |
| 2281 | the single event-dispatch/application thread. It is easy to apply with coroutines by using a |
| 2282 | single-threaded context: |
| 2283 | |
| 2284 | ```kotlin |
| 2285 | val counterContext = newSingleThreadContext("CounterContext") |
| 2286 | var counter = 0 |
| 2287 | |
| 2288 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2289 | massiveRun(CommonPool) { // run each coroutine in CommonPool |
Roman Elizarov | f9e13f5 | 2017-12-21 12:23:15 +0300 | [diff] [blame] | 2290 | withContext(counterContext) { // but confine each increment to the single-threaded context |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2291 | counter++ |
| 2292 | } |
| 2293 | } |
| 2294 | println("Counter = $counter") |
| 2295 | } |
| 2296 | ``` |
| 2297 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2298 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-sync-04.kt) |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2299 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2300 | <!--- TEST ARBITRARY_TIME |
| 2301 | Completed 1000000 actions in xxx ms |
| 2302 | Counter = 1000000 |
| 2303 | --> |
| 2304 | |
| 2305 | This code works very slowly, because it does _fine-grained_ thread-confinement. Each individual increment switches |
Roman Elizarov | f9e13f5 | 2017-12-21 12:23:15 +0300 | [diff] [blame] | 2306 | from multi-threaded `CommonPool` context to the single-threaded context using [withContext] block. |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2307 | |
| 2308 | ### Thread confinement coarse-grained |
| 2309 | |
| 2310 | In practice, thread confinement is performed in large chunks, e.g. big pieces of state-updating business logic |
| 2311 | are confined to the single thread. The following example does it like that, running each coroutine in |
| 2312 | the single-threaded context to start with. |
| 2313 | |
| 2314 | ```kotlin |
| 2315 | val counterContext = newSingleThreadContext("CounterContext") |
| 2316 | var counter = 0 |
| 2317 | |
| 2318 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 2319 | massiveRun(counterContext) { // run each coroutine in the single-threaded context |
| 2320 | counter++ |
| 2321 | } |
| 2322 | println("Counter = $counter") |
| 2323 | } |
| 2324 | ``` |
| 2325 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2326 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-sync-05.kt) |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2327 | |
| 2328 | <!--- TEST ARBITRARY_TIME |
| 2329 | Completed 1000000 actions in xxx ms |
| 2330 | Counter = 1000000 |
| 2331 | --> |
| 2332 | |
| 2333 | This now works much faster and produces correct result. |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2334 | |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2335 | ### Mutual exclusion |
| 2336 | |
| 2337 | Mutual exclusion solution to the problem is to protect all modifications of the shared state with a _critical section_ |
| 2338 | that is never executed concurrently. In a blocking world you'd typically use `synchronized` or `ReentrantLock` for that. |
| 2339 | Coroutine's alternative is called [Mutex]. It has [lock][Mutex.lock] and [unlock][Mutex.unlock] functions to |
paolop | 1d6e493 | 2018-07-02 08:46:34 +0000 | [diff] [blame] | 2340 | delimit a critical section. The key difference is that `Mutex.lock()` is a suspending function. It does not block a thread. |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2341 | |
Roman Elizarov | 8839673 | 2017-09-27 21:30:47 +0300 | [diff] [blame] | 2342 | There is also [withLock] extension function that conveniently represents |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 2343 | `mutex.lock(); try { ... } finally { mutex.unlock() }` pattern: |
| 2344 | |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2345 | ```kotlin |
| 2346 | val mutex = Mutex() |
| 2347 | var counter = 0 |
| 2348 | |
| 2349 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2350 | massiveRun(CommonPool) { |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 2351 | mutex.withLock { |
| 2352 | counter++ |
| 2353 | } |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2354 | } |
| 2355 | println("Counter = $counter") |
| 2356 | } |
| 2357 | ``` |
| 2358 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2359 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-sync-06.kt) |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2360 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2361 | <!--- TEST ARBITRARY_TIME |
| 2362 | Completed 1000000 actions in xxx ms |
| 2363 | Counter = 1000000 |
| 2364 | --> |
| 2365 | |
| 2366 | The locking in this example is fine-grained, so it pays the price. However, it is a good choice for some situations |
| 2367 | where you absolutely must modify some shared state periodically, but there is no natural thread that this state |
| 2368 | is confined to. |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2369 | |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2370 | ### Actors |
| 2371 | |
paolop | 1d6e493 | 2018-07-02 08:46:34 +0000 | [diff] [blame] | 2372 | An [actor](https://en.wikipedia.org/wiki/Actor_model) is an entity made up of a combination of a coroutine, the state that is confined and encapsulated into this coroutine, |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2373 | and a channel to communicate with other coroutines. A simple actor can be written as a function, |
| 2374 | but an actor with a complex state is better suited for a class. |
| 2375 | |
Roman Elizarov | c0e19f8 | 2017-02-27 11:59:14 +0300 | [diff] [blame] | 2376 | There is an [actor] coroutine builder that conveniently combines actor's mailbox channel into its |
| 2377 | scope to receive messages from and combines the send channel into the resulting job object, so that a |
| 2378 | single reference to the actor can be carried around as its handle. |
| 2379 | |
Roman Elizarov | 256812a | 2017-07-22 01:00:30 +0300 | [diff] [blame] | 2380 | The first step of using an actor is to define a class of messages that an actor is going to process. |
| 2381 | Kotlin's [sealed classes](https://kotlinlang.org/docs/reference/sealed-classes.html) are well suited for that purpose. |
| 2382 | We define `CounterMsg` sealed class with `IncCounter` message to increment a counter and `GetCounter` message |
| 2383 | to get its value. The later needs to send a response. A [CompletableDeferred] communication |
| 2384 | primitive, that represents a single value that will be known (communicated) in the future, |
| 2385 | is used here for that purpose. |
| 2386 | |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2387 | ```kotlin |
| 2388 | // Message types for counterActor |
| 2389 | sealed class CounterMsg |
| 2390 | object IncCounter : CounterMsg() // one-way message to increment counter |
Roman Elizarov | 256812a | 2017-07-22 01:00:30 +0300 | [diff] [blame] | 2391 | class GetCounter(val response: CompletableDeferred<Int>) : CounterMsg() // a request with reply |
| 2392 | ``` |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2393 | |
Roman Elizarov | 256812a | 2017-07-22 01:00:30 +0300 | [diff] [blame] | 2394 | Then we define a function that launches an actor using an [actor] coroutine builder: |
| 2395 | |
| 2396 | ```kotlin |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2397 | // This function launches a new counter actor |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 2398 | fun counterActor() = actor<CounterMsg> { |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2399 | var counter = 0 // actor state |
Roman Elizarov | c0e19f8 | 2017-02-27 11:59:14 +0300 | [diff] [blame] | 2400 | for (msg in channel) { // iterate over incoming messages |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2401 | when (msg) { |
| 2402 | is IncCounter -> counter++ |
Roman Elizarov | 256812a | 2017-07-22 01:00:30 +0300 | [diff] [blame] | 2403 | is GetCounter -> msg.response.complete(counter) |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2404 | } |
| 2405 | } |
| 2406 | } |
Roman Elizarov | 256812a | 2017-07-22 01:00:30 +0300 | [diff] [blame] | 2407 | ``` |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2408 | |
Roman Elizarov | 256812a | 2017-07-22 01:00:30 +0300 | [diff] [blame] | 2409 | The main code is straightforward: |
| 2410 | |
| 2411 | ```kotlin |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2412 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | c0e19f8 | 2017-02-27 11:59:14 +0300 | [diff] [blame] | 2413 | val counter = counterActor() // create the actor |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2414 | massiveRun(CommonPool) { |
Roman Elizarov | c0e19f8 | 2017-02-27 11:59:14 +0300 | [diff] [blame] | 2415 | counter.send(IncCounter) |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2416 | } |
Roman Elizarov | 256812a | 2017-07-22 01:00:30 +0300 | [diff] [blame] | 2417 | // send a message to get a counter value from an actor |
| 2418 | val response = CompletableDeferred<Int>() |
Roman Elizarov | c0e19f8 | 2017-02-27 11:59:14 +0300 | [diff] [blame] | 2419 | counter.send(GetCounter(response)) |
Roman Elizarov | 256812a | 2017-07-22 01:00:30 +0300 | [diff] [blame] | 2420 | println("Counter = ${response.await()}") |
Roman Elizarov | c0e19f8 | 2017-02-27 11:59:14 +0300 | [diff] [blame] | 2421 | counter.close() // shutdown the actor |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2422 | } |
| 2423 | ``` |
| 2424 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2425 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-sync-07.kt) |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2426 | |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2427 | <!--- TEST ARBITRARY_TIME |
| 2428 | Completed 1000000 actions in xxx ms |
| 2429 | Counter = 1000000 |
| 2430 | --> |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2431 | |
Roman Elizarov | c0e19f8 | 2017-02-27 11:59:14 +0300 | [diff] [blame] | 2432 | It does not matter (for correctness) what context the actor itself is executed in. An actor is |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2433 | a coroutine and a coroutine is executed sequentially, so confinement of the state to the specific coroutine |
paolop | 1d6e493 | 2018-07-02 08:46:34 +0000 | [diff] [blame] | 2434 | works as a solution to the problem of shared mutable state. Indeed, actors may modify their own private state, but can only affect each other through messages (avoiding the need for any locks). |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2435 | |
Roman Elizarov | c0e19f8 | 2017-02-27 11:59:14 +0300 | [diff] [blame] | 2436 | Actor is more efficient than locking under load, because in this case it always has work to do and it does not |
| 2437 | have to switch to a different context at all. |
| 2438 | |
| 2439 | > Note, that an [actor] coroutine builder is a dual of [produce] coroutine builder. An actor is associated |
| 2440 | with the channel that it receives messages from, while a producer is associated with the channel that it |
| 2441 | sends elements to. |
Roman Elizarov | 1e45960 | 2017-02-27 11:05:17 +0300 | [diff] [blame] | 2442 | |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2443 | ## Select expression |
| 2444 | |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2445 | Select expression makes it possible to await multiple suspending functions simultaneously and _select_ |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2446 | the first one that becomes available. |
| 2447 | |
| 2448 | <!--- INCLUDE .*/example-select-([0-9]+).kt |
| 2449 | import kotlinx.coroutines.experimental.channels.* |
| 2450 | import kotlinx.coroutines.experimental.selects.* |
| 2451 | --> |
| 2452 | |
| 2453 | ### Selecting from channels |
| 2454 | |
Roman Elizarov | 5785720 | 2017-03-02 23:17:25 +0300 | [diff] [blame] | 2455 | Let us have two producers of strings: `fizz` and `buzz`. The `fizz` produces "Fizz" string every 300 ms: |
| 2456 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 2457 | <!--- INCLUDE |
| 2458 | import kotlinx.coroutines.experimental.* |
| 2459 | import kotlin.coroutines.experimental.* |
Roman Elizarov | 5785720 | 2017-03-02 23:17:25 +0300 | [diff] [blame] | 2460 | --> |
| 2461 | |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2462 | ```kotlin |
Roman Elizarov | 5785720 | 2017-03-02 23:17:25 +0300 | [diff] [blame] | 2463 | fun fizz(context: CoroutineContext) = produce<String>(context) { |
| 2464 | while (true) { // sends "Fizz" every 300 ms |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2465 | delay(300) |
| 2466 | send("Fizz") |
| 2467 | } |
| 2468 | } |
| 2469 | ``` |
| 2470 | |
Roman Elizarov | 5785720 | 2017-03-02 23:17:25 +0300 | [diff] [blame] | 2471 | And the `buzz` produces "Buzz!" string every 500 ms: |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2472 | |
| 2473 | ```kotlin |
Roman Elizarov | 5785720 | 2017-03-02 23:17:25 +0300 | [diff] [blame] | 2474 | fun buzz(context: CoroutineContext) = produce<String>(context) { |
| 2475 | while (true) { // sends "Buzz!" every 500 ms |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2476 | delay(500) |
| 2477 | send("Buzz!") |
| 2478 | } |
| 2479 | } |
| 2480 | ``` |
| 2481 | |
| 2482 | Using [receive][ReceiveChannel.receive] suspending function we can receive _either_ from one channel or the |
| 2483 | other. But [select] expression allows us to receive from _both_ simultaneously using its |
Roman Elizarov | 8a5564d | 2017-09-06 18:48:22 +0300 | [diff] [blame] | 2484 | [onReceive][ReceiveChannel.onReceive] clauses: |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2485 | |
| 2486 | ```kotlin |
Roman Elizarov | 5785720 | 2017-03-02 23:17:25 +0300 | [diff] [blame] | 2487 | suspend fun selectFizzBuzz(fizz: ReceiveChannel<String>, buzz: ReceiveChannel<String>) { |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2488 | select<Unit> { // <Unit> means that this select expression does not produce any result |
| 2489 | fizz.onReceive { value -> // this is the first select clause |
| 2490 | println("fizz -> '$value'") |
| 2491 | } |
| 2492 | buzz.onReceive { value -> // this is the second select clause |
| 2493 | println("buzz -> '$value'") |
| 2494 | } |
| 2495 | } |
| 2496 | } |
| 2497 | ``` |
| 2498 | |
Roman Elizarov | 5785720 | 2017-03-02 23:17:25 +0300 | [diff] [blame] | 2499 | Let us run it all seven times: |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2500 | |
| 2501 | ```kotlin |
| 2502 | fun main(args: Array<String>) = runBlocking<Unit> { |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 2503 | val fizz = fizz(coroutineContext) |
| 2504 | val buzz = buzz(coroutineContext) |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2505 | repeat(7) { |
Roman Elizarov | 5785720 | 2017-03-02 23:17:25 +0300 | [diff] [blame] | 2506 | selectFizzBuzz(fizz, buzz) |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2507 | } |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 2508 | coroutineContext.cancelChildren() // cancel fizz & buzz coroutines |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2509 | } |
| 2510 | ``` |
| 2511 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2512 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-select-01.kt) |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2513 | |
| 2514 | The result of this code is: |
| 2515 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2516 | ```text |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2517 | fizz -> 'Fizz' |
| 2518 | buzz -> 'Buzz!' |
| 2519 | fizz -> 'Fizz' |
| 2520 | fizz -> 'Fizz' |
| 2521 | buzz -> 'Buzz!' |
| 2522 | fizz -> 'Fizz' |
| 2523 | buzz -> 'Buzz!' |
| 2524 | ``` |
| 2525 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2526 | <!--- TEST --> |
| 2527 | |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2528 | ### Selecting on close |
| 2529 | |
paolop | 1d6e493 | 2018-07-02 08:46:34 +0000 | [diff] [blame] | 2530 | The [onReceive][ReceiveChannel.onReceive] clause in `select` fails when the channel is closed causing the corresponding |
| 2531 | `select` to throw an exception. We can use [onReceiveOrNull][ReceiveChannel.onReceiveOrNull] clause to perform a |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2532 | specific action when the channel is closed. The following example also shows that `select` is an expression that returns |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2533 | the result of its selected clause: |
| 2534 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 2535 | <!--- INCLUDE |
| 2536 | import kotlin.coroutines.experimental.* |
| 2537 | --> |
| 2538 | |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2539 | ```kotlin |
| 2540 | suspend fun selectAorB(a: ReceiveChannel<String>, b: ReceiveChannel<String>): String = |
| 2541 | select<String> { |
| 2542 | a.onReceiveOrNull { value -> |
| 2543 | if (value == null) |
| 2544 | "Channel 'a' is closed" |
| 2545 | else |
| 2546 | "a -> '$value'" |
| 2547 | } |
| 2548 | b.onReceiveOrNull { value -> |
| 2549 | if (value == null) |
| 2550 | "Channel 'b' is closed" |
| 2551 | else |
| 2552 | "b -> '$value'" |
| 2553 | } |
| 2554 | } |
| 2555 | ``` |
| 2556 | |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2557 | Let's use it with channel `a` that produces "Hello" string four times and |
| 2558 | channel `b` that produces "World" four times: |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2559 | |
| 2560 | ```kotlin |
| 2561 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 2562 | // we are using the context of the main thread in this example for predictability ... |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 2563 | val a = produce<String>(coroutineContext) { |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2564 | repeat(4) { send("Hello $it") } |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2565 | } |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 2566 | val b = produce<String>(coroutineContext) { |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2567 | repeat(4) { send("World $it") } |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2568 | } |
| 2569 | repeat(8) { // print first eight results |
| 2570 | println(selectAorB(a, b)) |
| 2571 | } |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 2572 | coroutineContext.cancelChildren() |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2573 | } |
| 2574 | ``` |
| 2575 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2576 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-select-02.kt) |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2577 | |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2578 | The result of this code is quite interesting, so we'll analyze it in mode detail: |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2579 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2580 | ```text |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2581 | a -> 'Hello 0' |
| 2582 | a -> 'Hello 1' |
| 2583 | b -> 'World 0' |
| 2584 | a -> 'Hello 2' |
| 2585 | a -> 'Hello 3' |
| 2586 | b -> 'World 1' |
| 2587 | Channel 'a' is closed |
| 2588 | Channel 'a' is closed |
| 2589 | ``` |
| 2590 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2591 | <!--- TEST --> |
| 2592 | |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2593 | There are couple of observations to make out of it. |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2594 | |
| 2595 | First of all, `select` is _biased_ to the first clause. When several clauses are selectable at the same time, |
| 2596 | the first one among them gets selected. Here, both channels are constantly producing strings, so `a` channel, |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2597 | being the first clause in select, wins. However, because we are using unbuffered channel, the `a` gets suspended from |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2598 | time to time on its [send][SendChannel.send] invocation and gives a chance for `b` to send, too. |
| 2599 | |
Roman Elizarov | 8a5564d | 2017-09-06 18:48:22 +0300 | [diff] [blame] | 2600 | The second observation, is that [onReceiveOrNull][ReceiveChannel.onReceiveOrNull] gets immediately selected when the |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2601 | channel is already closed. |
| 2602 | |
| 2603 | ### Selecting to send |
| 2604 | |
Roman Elizarov | 8a5564d | 2017-09-06 18:48:22 +0300 | [diff] [blame] | 2605 | Select expression has [onSend][SendChannel.onSend] clause that can be used for a great good in combination |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2606 | with a biased nature of selection. |
| 2607 | |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2608 | Let us write an example of producer of integers that sends its values to a `side` channel when |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2609 | the consumers on its primary channel cannot keep up with it: |
| 2610 | |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 2611 | <!--- INCLUDE |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 2612 | import kotlin.coroutines.experimental.* |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 2613 | --> |
| 2614 | |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2615 | ```kotlin |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 2616 | fun produceNumbers(context: CoroutineContext, side: SendChannel<Int>) = produce<Int>(context) { |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2617 | for (num in 1..10) { // produce 10 numbers from 1 to 10 |
| 2618 | delay(100) // every 100 ms |
| 2619 | select<Unit> { |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2620 | onSend(num) {} // Send to the primary channel |
| 2621 | side.onSend(num) {} // or to the side channel |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2622 | } |
| 2623 | } |
| 2624 | } |
| 2625 | ``` |
| 2626 | |
| 2627 | Consumer is going to be quite slow, taking 250 ms to process each number: |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 2628 | |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2629 | ```kotlin |
| 2630 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 2631 | val side = Channel<Int>() // allocate side channel |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 2632 | launch(coroutineContext) { // this is a very fast consumer for the side channel |
Roman Elizarov | 86349be | 2017-03-17 16:47:37 +0300 | [diff] [blame] | 2633 | side.consumeEach { println("Side channel has $it") } |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2634 | } |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 2635 | produceNumbers(coroutineContext, side).consumeEach { |
Roman Elizarov | 86349be | 2017-03-17 16:47:37 +0300 | [diff] [blame] | 2636 | println("Consuming $it") |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2637 | delay(250) // let us digest the consumed number properly, do not hurry |
| 2638 | } |
| 2639 | println("Done consuming") |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 2640 | coroutineContext.cancelChildren() |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2641 | } |
| 2642 | ``` |
| 2643 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2644 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-select-03.kt) |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2645 | |
| 2646 | So let us see what happens: |
| 2647 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2648 | ```text |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2649 | Consuming 1 |
| 2650 | Side channel has 2 |
| 2651 | Side channel has 3 |
| 2652 | Consuming 4 |
| 2653 | Side channel has 5 |
| 2654 | Side channel has 6 |
| 2655 | Consuming 7 |
| 2656 | Side channel has 8 |
| 2657 | Side channel has 9 |
| 2658 | Consuming 10 |
| 2659 | Done consuming |
| 2660 | ``` |
| 2661 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2662 | <!--- TEST --> |
| 2663 | |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2664 | ### Selecting deferred values |
| 2665 | |
Roman Elizarov | 8a5564d | 2017-09-06 18:48:22 +0300 | [diff] [blame] | 2666 | Deferred values can be selected using [onAwait][Deferred.onAwait] clause. |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2667 | Let us start with an async function that returns a deferred string value after |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2668 | a random delay: |
| 2669 | |
| 2670 | <!--- INCLUDE .*/example-select-04.kt |
| 2671 | import java.util.* |
| 2672 | --> |
| 2673 | |
| 2674 | ```kotlin |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 2675 | fun asyncString(time: Int) = async { |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2676 | delay(time.toLong()) |
| 2677 | "Waited for $time ms" |
| 2678 | } |
| 2679 | ``` |
| 2680 | |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2681 | Let us start a dozen of them with a random delay. |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2682 | |
| 2683 | ```kotlin |
| 2684 | fun asyncStringsList(): List<Deferred<String>> { |
| 2685 | val random = Random(3) |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2686 | return List(12) { asyncString(random.nextInt(1000)) } |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2687 | } |
| 2688 | ``` |
| 2689 | |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2690 | Now the main function awaits for the first of them to complete and counts the number of deferred values |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2691 | that are still active. Note, that we've used here the fact that `select` expression is a Kotlin DSL, |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2692 | so we can provide clauses for it using an arbitrary code. In this case we iterate over a list |
| 2693 | of deferred values to provide `onAwait` clause for each deferred value. |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2694 | |
| 2695 | ```kotlin |
| 2696 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 2697 | val list = asyncStringsList() |
| 2698 | val result = select<String> { |
| 2699 | list.withIndex().forEach { (index, deferred) -> |
| 2700 | deferred.onAwait { answer -> |
| 2701 | "Deferred $index produced answer '$answer'" |
| 2702 | } |
| 2703 | } |
| 2704 | } |
| 2705 | println(result) |
Roman Elizarov | 7c864d8 | 2017-02-27 10:17:50 +0300 | [diff] [blame] | 2706 | val countActive = list.count { it.isActive } |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2707 | println("$countActive coroutines are still active") |
| 2708 | } |
| 2709 | ``` |
| 2710 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2711 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-select-04.kt) |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2712 | |
| 2713 | The output is: |
| 2714 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2715 | ```text |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2716 | Deferred 4 produced answer 'Waited for 128 ms' |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2717 | 11 coroutines are still active |
| 2718 | ``` |
| 2719 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2720 | <!--- TEST --> |
| 2721 | |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2722 | ### Switch over a channel of deferred values |
| 2723 | |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2724 | Let us write a channel producer function that consumes a channel of deferred string values, waits for each received |
| 2725 | deferred value, but only until the next deferred value comes over or the channel is closed. This example puts together |
Roman Elizarov | 8a5564d | 2017-09-06 18:48:22 +0300 | [diff] [blame] | 2726 | [onReceiveOrNull][ReceiveChannel.onReceiveOrNull] and [onAwait][Deferred.onAwait] clauses in the same `select`: |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2727 | |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 2728 | <!--- INCLUDE |
| 2729 | import kotlin.coroutines.experimental.* |
| 2730 | --> |
| 2731 | |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2732 | ```kotlin |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 2733 | fun switchMapDeferreds(input: ReceiveChannel<Deferred<String>>) = produce<String> { |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2734 | var current = input.receive() // start with first received deferred value |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2735 | while (isActive) { // loop while not cancelled/closed |
| 2736 | val next = select<Deferred<String>?> { // return next deferred value from this select or null |
| 2737 | input.onReceiveOrNull { update -> |
| 2738 | update // replaces next value to wait |
| 2739 | } |
| 2740 | current.onAwait { value -> |
| 2741 | send(value) // send value that current deferred has produced |
| 2742 | input.receiveOrNull() // and use the next deferred from the input channel |
| 2743 | } |
| 2744 | } |
| 2745 | if (next == null) { |
| 2746 | println("Channel was closed") |
| 2747 | break // out of loop |
| 2748 | } else { |
| 2749 | current = next |
| 2750 | } |
| 2751 | } |
| 2752 | } |
| 2753 | ``` |
| 2754 | |
| 2755 | To test it, we'll use a simple async function that resolves to a specified string after a specified time: |
| 2756 | |
| 2757 | ```kotlin |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 2758 | fun asyncString(str: String, time: Long) = async { |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2759 | delay(time) |
| 2760 | str |
| 2761 | } |
| 2762 | ``` |
| 2763 | |
| 2764 | The main function just launches a coroutine to print results of `switchMapDeferreds` and sends some test |
| 2765 | data to it: |
| 2766 | |
| 2767 | ```kotlin |
| 2768 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 2769 | val chan = Channel<Deferred<String>>() // the channel for test |
Roman Elizarov | 43e3af7 | 2017-07-21 16:01:31 +0300 | [diff] [blame] | 2770 | launch(coroutineContext) { // launch printing coroutine |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2771 | for (s in switchMapDeferreds(chan)) |
| 2772 | println(s) // print each received string |
| 2773 | } |
| 2774 | chan.send(asyncString("BEGIN", 100)) |
| 2775 | delay(200) // enough time for "BEGIN" to be produced |
| 2776 | chan.send(asyncString("Slow", 500)) |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2777 | delay(100) // not enough time to produce slow |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2778 | chan.send(asyncString("Replace", 100)) |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2779 | delay(500) // give it time before the last one |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2780 | chan.send(asyncString("END", 500)) |
| 2781 | delay(1000) // give it time to process |
Roman Elizarov | a84730b | 2017-02-22 11:58:50 +0300 | [diff] [blame] | 2782 | chan.close() // close the channel ... |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2783 | delay(500) // and wait some time to let it finish |
| 2784 | } |
| 2785 | ``` |
| 2786 | |
Vsevolod Tolstopyatov | c1eb19f | 2018-06-19 17:04:09 +0300 | [diff] [blame] | 2787 | > You can get full code [here](core/kotlinx-coroutines-core/test/guide/example-select-05.kt) |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2788 | |
| 2789 | The result of this code: |
| 2790 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2791 | ```text |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2792 | BEGIN |
| 2793 | Replace |
| 2794 | END |
| 2795 | Channel was closed |
| 2796 | ``` |
| 2797 | |
Roman Elizarov | 731f0ad | 2017-02-22 20:48:45 +0300 | [diff] [blame] | 2798 | <!--- TEST --> |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2799 | |
Roman Elizarov | 8db1733 | 2017-03-09 12:40:45 +0300 | [diff] [blame] | 2800 | ## Further reading |
| 2801 | |
| 2802 | * [Guide to UI programming with coroutines](ui/coroutines-guide-ui.md) |
Roman Elizarov | 8a4a8e1 | 2017-03-09 19:52:58 +0300 | [diff] [blame] | 2803 | * [Guide to reactive streams with coroutines](reactive/coroutines-guide-reactive.md) |
Roman Elizarov | 8db1733 | 2017-03-09 12:40:45 +0300 | [diff] [blame] | 2804 | * [Coroutines design document (KEEP)](https://github.com/Kotlin/kotlin-coroutines/blob/master/kotlin-coroutines-informal.md) |
| 2805 | * [Full kotlinx.coroutines API reference](http://kotlin.github.io/kotlinx.coroutines) |
| 2806 | |
Roman Elizarov | e7e2ad1 | 2017-05-17 14:47:31 +0300 | [diff] [blame] | 2807 | <!--- MODULE kotlinx-coroutines-core --> |
Roman Elizarov | e0c817d | 2017-02-10 10:22:01 +0300 | [diff] [blame] | 2808 | <!--- INDEX kotlinx.coroutines.experimental --> |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2809 | [launch]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/launch.html |
| 2810 | [delay]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/delay.html |
| 2811 | [runBlocking]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/run-blocking.html |
Roman Elizarov | e82dee7 | 2017-08-18 16:49:09 +0300 | [diff] [blame] | 2812 | [Job]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-job/index.html |
Roman Elizarov | 8b38fa2 | 2017-09-27 17:44:31 +0300 | [diff] [blame] | 2813 | [cancelAndJoin]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/cancel-and-join.html |
Roman Elizarov | 8839673 | 2017-09-27 21:30:47 +0300 | [diff] [blame] | 2814 | [Job.cancel]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-job/cancel.html |
| 2815 | [Job.join]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-job/join.html |
Roman Elizarov | cbb602d | 2017-12-23 14:24:26 +0300 | [diff] [blame] | 2816 | [CancellationException]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-cancellation-exception/index.html |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2817 | [yield]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/yield.html |
Roman Elizarov | bff3f37 | 2017-03-01 18:12:27 +0300 | [diff] [blame] | 2818 | [CoroutineScope.isActive]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-coroutine-scope/is-active.html |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2819 | [CoroutineScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-coroutine-scope/index.html |
Roman Elizarov | f9e13f5 | 2017-12-21 12:23:15 +0300 | [diff] [blame] | 2820 | [withContext]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/with-context.html |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2821 | [NonCancellable]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-non-cancellable/index.html |
| 2822 | [withTimeout]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/with-timeout.html |
Roman Elizarov | 63f6ea2 | 2017-09-06 18:42:34 +0300 | [diff] [blame] | 2823 | [withTimeoutOrNull]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/with-timeout-or-null.html |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2824 | [async]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/async.html |
| 2825 | [Deferred]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-deferred/index.html |
Roman Elizarov | ecda27f | 2017-04-06 23:06:26 +0300 | [diff] [blame] | 2826 | [CoroutineStart.LAZY]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-coroutine-start/-l-a-z-y.html |
Roman Elizarov | bff3f37 | 2017-03-01 18:12:27 +0300 | [diff] [blame] | 2827 | [Deferred.await]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-deferred/await.html |
| 2828 | [Job.start]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-job/start.html |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 2829 | [CoroutineDispatcher]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-coroutine-dispatcher/index.html |
Roman Elizarov | d9ae2bc | 2017-10-20 17:36:56 +0800 | [diff] [blame] | 2830 | [DefaultDispatcher]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-default-dispatcher.html |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 2831 | [CommonPool]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-common-pool/index.html |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 2832 | [Unconfined]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-unconfined/index.html |
Roman Elizarov | d9ae2bc | 2017-10-20 17:36:56 +0800 | [diff] [blame] | 2833 | [newSingleThreadContext]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/new-single-thread-context.html |
| 2834 | [ThreadPoolDispatcher.close]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-thread-pool-dispatcher/close.html |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 2835 | [newCoroutineContext]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/new-coroutine-context.html |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2836 | [CoroutineName]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-coroutine-name/index.html |
Roman Elizarov | 8839673 | 2017-09-27 21:30:47 +0300 | [diff] [blame] | 2837 | [Job()]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-job.html |
Vsevolod Tolstopyatov | e342597 | 2018-08-22 19:41:57 +0300 | [diff] [blame^] | 2838 | [asContextElement]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/java.lang.-thread-local/as-context-element.html |
| 2839 | [ThreadContextElement]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-thread-context-element/index.html |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 2840 | [CoroutineExceptionHandler]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-coroutine-exception-handler/index.html |
Roman Elizarov | 3e387b8 | 2017-12-04 13:49:11 +0300 | [diff] [blame] | 2841 | [kotlin.coroutines.experimental.CoroutineContext.cancelChildren]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/kotlin.coroutines.experimental.-coroutine-context/cancel-children.html |
Roman Elizarov | e82dee7 | 2017-08-18 16:49:09 +0300 | [diff] [blame] | 2842 | [CompletableDeferred]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-completable-deferred/index.html |
Roman Elizarov | 8a5564d | 2017-09-06 18:48:22 +0300 | [diff] [blame] | 2843 | [Deferred.onAwait]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-deferred/on-await.html |
Roman Elizarov | f5bc047 | 2017-02-22 11:38:13 +0300 | [diff] [blame] | 2844 | <!--- INDEX kotlinx.coroutines.experimental.sync --> |
Roman Elizarov | e82dee7 | 2017-08-18 16:49:09 +0300 | [diff] [blame] | 2845 | [Mutex]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.sync/-mutex/index.html |
Roman Elizarov | bff3f37 | 2017-03-01 18:12:27 +0300 | [diff] [blame] | 2846 | [Mutex.lock]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.sync/-mutex/lock.html |
| 2847 | [Mutex.unlock]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.sync/-mutex/unlock.html |
Roman Elizarov | 8839673 | 2017-09-27 21:30:47 +0300 | [diff] [blame] | 2848 | [withLock]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.sync/with-lock.html |
Roman Elizarov | e0c817d | 2017-02-10 10:22:01 +0300 | [diff] [blame] | 2849 | <!--- INDEX kotlinx.coroutines.experimental.channels --> |
Vsevolod Tolstopyatov | 590696d | 2018-08-08 15:22:33 +0300 | [diff] [blame] | 2850 | [actor]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/actor.html |
| 2851 | [produce]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/produce.html |
| 2852 | [ReceiveChannel.receive]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-receive-channel/receive.html |
Roman Elizarov | e82dee7 | 2017-08-18 16:49:09 +0300 | [diff] [blame] | 2853 | [Channel]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-channel/index.html |
Roman Elizarov | bff3f37 | 2017-03-01 18:12:27 +0300 | [diff] [blame] | 2854 | [SendChannel.send]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-send-channel/send.html |
Roman Elizarov | bff3f37 | 2017-03-01 18:12:27 +0300 | [diff] [blame] | 2855 | [SendChannel.close]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-send-channel/close.html |
Roman Elizarov | 86349be | 2017-03-17 16:47:37 +0300 | [diff] [blame] | 2856 | [consumeEach]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/consume-each.html |
Roman Elizarov | 8839673 | 2017-09-27 21:30:47 +0300 | [diff] [blame] | 2857 | [Channel()]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-channel.html |
Vsevolod Tolstopyatov | 03d2ff7 | 2018-05-29 17:28:20 +0300 | [diff] [blame] | 2858 | [ticker]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/ticker.html |
Vsevolod Tolstopyatov | 1dbc25e | 2018-04-18 14:50:26 +0300 | [diff] [blame] | 2859 | [ReceiveChannel.cancel]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-receive-channel/cancel.html |
Roman Elizarov | 0c090ed | 2018-06-29 19:51:07 +0300 | [diff] [blame] | 2860 | [TickerMode.FIXED_DELAY]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-ticker-mode/-f-i-x-e-d_-d-e-l-a-y.html |
Roman Elizarov | b5328a7 | 2018-06-06 18:31:21 +0300 | [diff] [blame] | 2861 | [ReceiveChannel.onReceive]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-receive-channel/on-receive.html |
Roman Elizarov | 8a5564d | 2017-09-06 18:48:22 +0300 | [diff] [blame] | 2862 | [ReceiveChannel.onReceiveOrNull]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-receive-channel/on-receive-or-null.html |
| 2863 | [SendChannel.onSend]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-send-channel/on-send.html |
Roman Elizarov | d4dcbe2 | 2017-02-22 09:57:46 +0300 | [diff] [blame] | 2864 | <!--- INDEX kotlinx.coroutines.experimental.selects --> |
| 2865 | [select]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.selects/select.html |
Roman Elizarov | 419a6c8 | 2017-02-09 18:36:22 +0300 | [diff] [blame] | 2866 | <!--- END --> |