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