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