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