blob: 4681f889f2890724ccbff92f56a8fc986056543a [file] [log] [blame] [view]
Roman Elizarov43e90112017-05-10 11:25:20 +03001<!--- INCLUDE .*/example-([a-z]+)-([0-9a-z]+)\.kt
Roman Elizarova5e653f2017-02-13 13:49:55 +03002/*
3 * Copyright 2016-2017 JetBrains s.r.o.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
Roman Elizarovf16fd272017-02-07 11:26:00 +030017
Roman Elizarova5e653f2017-02-13 13:49:55 +030018// This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit.
19package guide.$$1.example$$2
Roman Elizarovf16fd272017-02-07 11:26:00 +030020
Roman Elizarova5e653f2017-02-13 13:49:55 +030021import kotlinx.coroutines.experimental.*
Roman Elizarovf16fd272017-02-07 11:26:00 +030022-->
Roman Elizarov731f0ad2017-02-22 20:48:45 +030023<!--- KNIT kotlinx-coroutines-core/src/test/kotlin/guide/.*\.kt -->
24<!--- TEST_OUT kotlinx-coroutines-core/src/test/kotlin/guide/test/GuideTest.kt
25// This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit.
26package guide.test
27
28import org.junit.Test
29
30class GuideTest {
31-->
Roman Elizarovf16fd272017-02-07 11:26:00 +030032
Roman Elizarov7deefb82017-01-31 10:33:17 +030033# Guide to kotlinx.coroutines by example
34
35This is a short guide on core features of `kotlinx.coroutines` with a series of examples.
36
Roman Elizarov2a638922017-03-04 10:22:43 +030037## Introduction and setup
38
39Kotlin, as a language, provides only minimal low-level APIs in its standard library to enable various other
40libraries to utilize coroutines. Unlike many other languages with similar capabilities, `async` and `await`
41are not keywords in Kotlin and are not even part of its standard library.
42
Robert Hencke497d3432017-04-11 00:14:29 -040043`kotlinx.coroutines` is one such rich library. It contains a number of high-level
Roman Elizarov2a638922017-03-04 10:22:43 +030044coroutine-enabled primitives that this guide covers, including `async` and `await`.
45You need to add a dependency on `kotlinx-coroutines-core` module as explained
46[here](README.md#using-in-your-projects) to use primitives from this guide in your projects.
47
Roman Elizarov1293ccd2017-02-01 18:49:54 +030048## Table of contents
49
Roman Elizarovfa7723e2017-02-06 11:17:51 +030050<!--- TOC -->
51
Roman Elizarov1293ccd2017-02-01 18:49:54 +030052* [Coroutine basics](#coroutine-basics)
53 * [Your first coroutine](#your-first-coroutine)
54 * [Bridging blocking and non-blocking worlds](#bridging-blocking-and-non-blocking-worlds)
55 * [Waiting for a job](#waiting-for-a-job)
56 * [Extract function refactoring](#extract-function-refactoring)
57 * [Coroutines ARE light-weight](#coroutines-are-light-weight)
58 * [Coroutines are like daemon threads](#coroutines-are-like-daemon-threads)
59* [Cancellation and timeouts](#cancellation-and-timeouts)
60 * [Cancelling coroutine execution](#cancelling-coroutine-execution)
61 * [Cancellation is cooperative](#cancellation-is-cooperative)
62 * [Making computation code cancellable](#making-computation-code-cancellable)
63 * [Closing resources with finally](#closing-resources-with-finally)
64 * [Run non-cancellable block](#run-non-cancellable-block)
65 * [Timeout](#timeout)
66* [Composing suspending functions](#composing-suspending-functions)
67 * [Sequential by default](#sequential-by-default)
Roman Elizarov32d95322017-02-09 15:57:31 +030068 * [Concurrent using async](#concurrent-using-async)
69 * [Lazily started async](#lazily-started-async)
70 * [Async-style functions](#async-style-functions)
Roman Elizarov2f6d7c92017-02-03 15:16:07 +030071* [Coroutine context and dispatchers](#coroutine-context-and-dispatchers)
Roman Elizarovfa7723e2017-02-06 11:17:51 +030072 * [Dispatchers and threads](#dispatchers-and-threads)
Roman Elizarov2f6d7c92017-02-03 15:16:07 +030073 * [Unconfined vs confined dispatcher](#unconfined-vs-confined-dispatcher)
74 * [Debugging coroutines and threads](#debugging-coroutines-and-threads)
75 * [Jumping between threads](#jumping-between-threads)
76 * [Job in the context](#job-in-the-context)
77 * [Children of a coroutine](#children-of-a-coroutine)
78 * [Combining contexts](#combining-contexts)
79 * [Naming coroutines for debugging](#naming-coroutines-for-debugging)
Roman Elizarov2fd7cb32017-02-11 23:18:59 +030080 * [Cancellation via explicit job](#cancellation-via-explicit-job)
Roman Elizarovb7721cf2017-02-03 19:23:08 +030081* [Channels](#channels)
82 * [Channel basics](#channel-basics)
83 * [Closing and iteration over channels](#closing-and-iteration-over-channels)
84 * [Building channel producers](#building-channel-producers)
85 * [Pipelines](#pipelines)
86 * [Prime numbers with pipeline](#prime-numbers-with-pipeline)
87 * [Fan-out](#fan-out)
88 * [Fan-in](#fan-in)
89 * [Buffered channels](#buffered-channels)
Roman Elizarovb0517ba2017-02-27 14:03:14 +030090 * [Channels are fair](#channels-are-fair)
Roman Elizarovf5bc0472017-02-22 11:38:13 +030091* [Shared mutable state and concurrency](#shared-mutable-state-and-concurrency)
92 * [The problem](#the-problem)
Roman Elizarov1e459602017-02-27 11:05:17 +030093 * [Volatiles are of no help](#volatiles-are-of-no-help)
Roman Elizarovf5bc0472017-02-22 11:38:13 +030094 * [Thread-safe data structures](#thread-safe-data-structures)
Roman Elizarov1e459602017-02-27 11:05:17 +030095 * [Thread confinement fine-grained](#thread-confinement-fine-grained)
96 * [Thread confinement coarse-grained](#thread-confinement-coarse-grained)
Roman Elizarovf5bc0472017-02-22 11:38:13 +030097 * [Mutual exclusion](#mutual-exclusion)
98 * [Actors](#actors)
Roman Elizarovd4dcbe22017-02-22 09:57:46 +030099* [Select expression](#select-expression)
100 * [Selecting from channels](#selecting-from-channels)
101 * [Selecting on close](#selecting-on-close)
102 * [Selecting to send](#selecting-to-send)
103 * [Selecting deferred values](#selecting-deferred-values)
104 * [Switch over a channel of deferred values](#switch-over-a-channel-of-deferred-values)
Roman Elizarov8db17332017-03-09 12:40:45 +0300105* [Further reading](#further-reading)
Roman Elizarovfa7723e2017-02-06 11:17:51 +0300106
Roman Elizarova5e653f2017-02-13 13:49:55 +0300107<!--- END_TOC -->
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300108
109## Coroutine basics
110
111This section covers basic coroutine concepts.
112
113### Your first coroutine
Roman Elizarov7deefb82017-01-31 10:33:17 +0300114
115Run the following code:
116
117```kotlin
118fun main(args: Array<String>) {
119 launch(CommonPool) { // create new coroutine in common thread pool
120 delay(1000L) // non-blocking delay for 1 second (default time unit is ms)
121 println("World!") // print after delay
122 }
123 println("Hello,") // main function continues while coroutine is delayed
124 Thread.sleep(2000L) // block main thread for 2 seconds to keep JVM alive
125}
126```
127
Roman Elizarovfa7723e2017-02-06 11:17:51 +0300128> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-basic-01.kt)
Roman Elizarov7deefb82017-01-31 10:33:17 +0300129
130Run this code:
131
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300132```text
Roman Elizarov7deefb82017-01-31 10:33:17 +0300133Hello,
134World!
135```
136
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300137<!--- TEST -->
138
Roman Elizarov419a6c82017-02-09 18:36:22 +0300139Essentially, coroutines are light-weight threads.
140They are launched with [launch] _coroutine builder_.
141You can achieve the same result replacing
Roman Elizarov7deefb82017-01-31 10:33:17 +0300142`launch(CommonPool) { ... }` with `thread { ... }` and `delay(...)` with `Thread.sleep(...)`. Try it.
143
144If you start by replacing `launch(CommonPool)` by `thread`, the compiler produces the following error:
145
146```
147Error: Kotlin: Suspend functions are only allowed to be called from a coroutine or another suspend function
148```
149
Roman Elizarov419a6c82017-02-09 18:36:22 +0300150That is because [delay] is a special _suspending function_ that does not block a thread, but _suspends_
Roman Elizarov7deefb82017-01-31 10:33:17 +0300151coroutine and it can be only used from a coroutine.
152
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300153### Bridging blocking and non-blocking worlds
Roman Elizarov7deefb82017-01-31 10:33:17 +0300154
155The first example mixes _non-blocking_ `delay(...)` and _blocking_ `Thread.sleep(...)` in the same
156code of `main` function. It is easy to get lost. Let's cleanly separate blocking and non-blocking
Roman Elizarov419a6c82017-02-09 18:36:22 +0300157worlds by using [runBlocking]:
Roman Elizarov7deefb82017-01-31 10:33:17 +0300158
159```kotlin
160fun main(args: Array<String>) = runBlocking<Unit> { // start main coroutine
161 launch(CommonPool) { // create new coroutine in common thread pool
162 delay(1000L)
163 println("World!")
164 }
165 println("Hello,") // main coroutine continues while child is delayed
166 delay(2000L) // non-blocking delay for 2 seconds to keep JVM alive
167}
168```
169
Roman Elizarovfa7723e2017-02-06 11:17:51 +0300170> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-basic-02.kt)
Roman Elizarov7deefb82017-01-31 10:33:17 +0300171
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300172<!--- TEST
173Hello,
174World!
175-->
176
Roman Elizarov419a6c82017-02-09 18:36:22 +0300177The result is the same, but this code uses only non-blocking [delay].
Roman Elizarov7deefb82017-01-31 10:33:17 +0300178
179`runBlocking { ... }` works as an adaptor that is used here to start the top-level main coroutine.
180The regular code outside of `runBlocking` _blocks_, until the coroutine inside `runBlocking` is active.
181
182This is also a way to write unit-tests for suspending functions:
183
184```kotlin
185class MyTest {
186 @Test
187 fun testMySuspendingFunction() = runBlocking<Unit> {
188 // here we can use suspending functions using any assertion style that we like
189 }
190}
191```
Roman Elizarovb3d55a52017-02-03 12:47:21 +0300192
193<!--- CLEAR -->
Roman Elizarov7deefb82017-01-31 10:33:17 +0300194
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300195### Waiting for a job
Roman Elizarov7deefb82017-01-31 10:33:17 +0300196
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300197Delaying for a time while another coroutine is working is not a good approach. Let's explicitly
Roman Elizarov419a6c82017-02-09 18:36:22 +0300198wait (in a non-blocking way) until the background [Job] that we have launched is complete:
Roman Elizarov7deefb82017-01-31 10:33:17 +0300199
200```kotlin
201fun main(args: Array<String>) = runBlocking<Unit> {
202 val job = launch(CommonPool) { // create new coroutine and keep a reference to its Job
203 delay(1000L)
204 println("World!")
205 }
206 println("Hello,")
207 job.join() // wait until child coroutine completes
208}
209```
210
Roman Elizarovfa7723e2017-02-06 11:17:51 +0300211> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-basic-03.kt)
Roman Elizarov7deefb82017-01-31 10:33:17 +0300212
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300213<!--- TEST
214Hello,
215World!
216-->
217
Roman Elizarov7deefb82017-01-31 10:33:17 +0300218Now the result is still the same, but the code of the main coroutine is not tied to the duration of
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300219the background job in any way. Much better.
Roman Elizarov7deefb82017-01-31 10:33:17 +0300220
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300221### Extract function refactoring
Roman Elizarov7deefb82017-01-31 10:33:17 +0300222
Kafji48fd6282017-05-28 08:25:10 +0700223Let's extract the block of code inside `launch(CommonPool) { ... }` into a separate function. When you
Roman Elizarov7deefb82017-01-31 10:33:17 +0300224perform "Extract function" refactoring on this code you get a new function with `suspend` modifier.
225That is your first _suspending function_. Suspending functions can be used inside coroutines
226just like regular functions, but their additional feature is that they can, in turn,
227use other suspending functions, like `delay` in this example, to _suspend_ execution of a coroutine.
228
229```kotlin
230fun main(args: Array<String>) = runBlocking<Unit> {
231 val job = launch(CommonPool) { doWorld() }
232 println("Hello,")
233 job.join()
234}
235
236// this is your first suspending function
237suspend fun doWorld() {
238 delay(1000L)
239 println("World!")
240}
241```
242
Roman Elizarovfa7723e2017-02-06 11:17:51 +0300243> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-basic-04.kt)
Roman Elizarov7deefb82017-01-31 10:33:17 +0300244
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300245<!--- TEST
246Hello,
247World!
248-->
249
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300250### Coroutines ARE light-weight
Roman Elizarov7deefb82017-01-31 10:33:17 +0300251
252Run the following code:
253
254```kotlin
255fun main(args: Array<String>) = runBlocking<Unit> {
256 val jobs = List(100_000) { // create a lot of coroutines and list their jobs
257 launch(CommonPool) {
258 delay(1000L)
259 print(".")
260 }
261 }
262 jobs.forEach { it.join() } // wait for all jobs to complete
263}
264```
265
Roman Elizarovfa7723e2017-02-06 11:17:51 +0300266> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-basic-05.kt)
Roman Elizarov7deefb82017-01-31 10:33:17 +0300267
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300268<!--- TEST lines.size == 1 && lines[0] == ".".repeat(100_000) -->
269
Roman Elizarov7deefb82017-01-31 10:33:17 +0300270It starts 100K coroutines and, after a second, each coroutine prints a dot.
271Now, try that with threads. What would happen? (Most likely your code will produce some sort of out-of-memory error)
272
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300273### Coroutines are like daemon threads
Roman Elizarov7deefb82017-01-31 10:33:17 +0300274
275The following code launches a long-running coroutine that prints "I'm sleeping" twice a second and then
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300276returns from the main function after some delay:
Roman Elizarov7deefb82017-01-31 10:33:17 +0300277
278```kotlin
279fun main(args: Array<String>) = runBlocking<Unit> {
280 launch(CommonPool) {
281 repeat(1000) { i ->
282 println("I'm sleeping $i ...")
283 delay(500L)
284 }
285 }
286 delay(1300L) // just quit after delay
287}
288```
289
Roman Elizarovfa7723e2017-02-06 11:17:51 +0300290> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-basic-06.kt)
Roman Elizarov7deefb82017-01-31 10:33:17 +0300291
292You can run and see that it prints three lines and terminates:
293
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300294```text
Roman Elizarov7deefb82017-01-31 10:33:17 +0300295I'm sleeping 0 ...
296I'm sleeping 1 ...
297I'm sleeping 2 ...
298```
299
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300300<!--- TEST -->
301
Roman Elizarov7deefb82017-01-31 10:33:17 +0300302Active coroutines do not keep the process alive. They are like daemon threads.
303
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300304## Cancellation and timeouts
305
306This section covers coroutine cancellation and timeouts.
307
308### Cancelling coroutine execution
Roman Elizarov7deefb82017-01-31 10:33:17 +0300309
310In small application the return from "main" method might sound like a good idea to get all coroutines
311implicitly terminated. In a larger, long-running application, you need finer-grained control.
Roman Elizarov419a6c82017-02-09 18:36:22 +0300312The [launch] function returns a [Job] that can be used to cancel running coroutine:
Roman Elizarov7deefb82017-01-31 10:33:17 +0300313
314```kotlin
315fun main(args: Array<String>) = runBlocking<Unit> {
316 val job = launch(CommonPool) {
317 repeat(1000) { i ->
318 println("I'm sleeping $i ...")
319 delay(500L)
320 }
321 }
322 delay(1300L) // delay a bit
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300323 println("main: I'm tired of waiting!")
Roman Elizarov7deefb82017-01-31 10:33:17 +0300324 job.cancel() // cancels the job
325 delay(1300L) // delay a bit to ensure it was cancelled indeed
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300326 println("main: Now I can quit.")
Roman Elizarov7deefb82017-01-31 10:33:17 +0300327}
328```
329
Roman Elizarovfa7723e2017-02-06 11:17:51 +0300330> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-cancel-01.kt)
Roman Elizarov7deefb82017-01-31 10:33:17 +0300331
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300332It produces the following output:
333
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300334```text
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300335I'm sleeping 0 ...
336I'm sleeping 1 ...
337I'm sleeping 2 ...
338main: I'm tired of waiting!
339main: Now I can quit.
340```
341
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300342<!--- TEST -->
343
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300344As soon as main invokes `job.cancel`, we don't see any output from the other coroutine because it was cancelled.
345
346### Cancellation is cooperative
Roman Elizarov7deefb82017-01-31 10:33:17 +0300347
Tair Rzayevaf734622017-02-01 22:30:16 +0200348Coroutine cancellation is _cooperative_. A coroutine code has to cooperate to be cancellable.
Roman Elizarov7deefb82017-01-31 10:33:17 +0300349All the suspending functions in `kotlinx.coroutines` are _cancellable_. They check for cancellation of
Roman Elizarov419a6c82017-02-09 18:36:22 +0300350coroutine and throw [CancellationException] when cancelled. However, if a coroutine is working in
Roman Elizarov7deefb82017-01-31 10:33:17 +0300351a computation and does not check for cancellation, then it cannot be cancelled, like the following
352example shows:
353
354```kotlin
355fun main(args: Array<String>) = runBlocking<Unit> {
Roman Elizarov24cd6542017-08-03 21:20:04 -0700356 val startTime = System.currentTimeMillis()
Roman Elizarov7deefb82017-01-31 10:33:17 +0300357 val job = launch(CommonPool) {
Roman Elizarov24cd6542017-08-03 21:20:04 -0700358 var nextPrintTime = startTime
Roman Elizarov7deefb82017-01-31 10:33:17 +0300359 var i = 0
Roman Elizarov24cd6542017-08-03 21:20:04 -0700360 while (i < 10) { // computation loop, just wastes CPU
361 // print a message twice a second
362 if (System.currentTimeMillis() >= nextPrintTime) {
Roman Elizarov7deefb82017-01-31 10:33:17 +0300363 println("I'm sleeping ${i++} ...")
Roman Elizarov35d2c342017-07-20 14:54:39 +0300364 nextPrintTime += 500L
Roman Elizarov7deefb82017-01-31 10:33:17 +0300365 }
366 }
367 }
368 delay(1300L) // delay a bit
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300369 println("main: I'm tired of waiting!")
Roman Elizarov7deefb82017-01-31 10:33:17 +0300370 job.cancel() // cancels the job
371 delay(1300L) // delay a bit to see if it was cancelled....
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300372 println("main: Now I can quit.")
Roman Elizarov7deefb82017-01-31 10:33:17 +0300373}
374```
375
Roman Elizarovfa7723e2017-02-06 11:17:51 +0300376> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-cancel-02.kt)
Roman Elizarov7deefb82017-01-31 10:33:17 +0300377
378Run it to see that it continues to print "I'm sleeping" even after cancellation.
379
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300380<!--- TEST
381I'm sleeping 0 ...
382I'm sleeping 1 ...
383I'm sleeping 2 ...
384main: I'm tired of waiting!
385I'm sleeping 3 ...
386I'm sleeping 4 ...
387I'm sleeping 5 ...
388main: Now I can quit.
389-->
390
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300391### Making computation code cancellable
Roman Elizarov7deefb82017-01-31 10:33:17 +0300392
393There are two approaches to making computation code cancellable. The first one is to periodically
Roman Elizarov419a6c82017-02-09 18:36:22 +0300394invoke a suspending function. There is a [yield] function that is a good choice for that purpose.
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300395The other one is to explicitly check the cancellation status. Let us try the later approach.
Roman Elizarov7deefb82017-01-31 10:33:17 +0300396
Roman Elizarov24cd6542017-08-03 21:20:04 -0700397Replace `while (i < 10)` in the previous example with `while (isActive)` and rerun it.
Roman Elizarov7deefb82017-01-31 10:33:17 +0300398
Roman Elizarovb3d55a52017-02-03 12:47:21 +0300399```kotlin
400fun main(args: Array<String>) = runBlocking<Unit> {
Roman Elizarov24cd6542017-08-03 21:20:04 -0700401 val startTime = System.currentTimeMillis()
Roman Elizarovb3d55a52017-02-03 12:47:21 +0300402 val job = launch(CommonPool) {
Roman Elizarov24cd6542017-08-03 21:20:04 -0700403 var nextPrintTime = startTime
Roman Elizarovb3d55a52017-02-03 12:47:21 +0300404 var i = 0
405 while (isActive) { // cancellable computation loop
Roman Elizarov24cd6542017-08-03 21:20:04 -0700406 // print a message twice a second
407 if (System.currentTimeMillis() >= nextPrintTime) {
Roman Elizarovb3d55a52017-02-03 12:47:21 +0300408 println("I'm sleeping ${i++} ...")
Roman Elizarov24cd6542017-08-03 21:20:04 -0700409 nextPrintTime += 500L
Roman Elizarovb3d55a52017-02-03 12:47:21 +0300410 }
411 }
412 }
413 delay(1300L) // delay a bit
414 println("main: I'm tired of waiting!")
415 job.cancel() // cancels the job
416 delay(1300L) // delay a bit to see if it was cancelled....
417 println("main: Now I can quit.")
418}
419```
420
Roman Elizarovfa7723e2017-02-06 11:17:51 +0300421> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-cancel-03.kt)
Roman Elizarov7deefb82017-01-31 10:33:17 +0300422
Roman Elizarov419a6c82017-02-09 18:36:22 +0300423As you can see, now this loop can be cancelled. [isActive][CoroutineScope.isActive] is a property that is available inside
424the code of coroutines via [CoroutineScope] object.
Roman Elizarov7deefb82017-01-31 10:33:17 +0300425
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300426<!--- TEST
427I'm sleeping 0 ...
428I'm sleeping 1 ...
429I'm sleeping 2 ...
430main: I'm tired of waiting!
431main: Now I can quit.
432-->
433
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300434### Closing resources with finally
435
Roman Elizarov419a6c82017-02-09 18:36:22 +0300436Cancellable suspending functions throw [CancellationException] on cancellation which can be handled in
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300437all the usual way. For example, the `try {...} finally {...}` and Kotlin `use` function execute their
438finalization actions normally when coroutine is cancelled:
439
440```kotlin
441fun main(args: Array<String>) = runBlocking<Unit> {
442 val job = launch(CommonPool) {
443 try {
444 repeat(1000) { i ->
445 println("I'm sleeping $i ...")
446 delay(500L)
447 }
448 } finally {
449 println("I'm running finally")
450 }
451 }
452 delay(1300L) // delay a bit
453 println("main: I'm tired of waiting!")
454 job.cancel() // cancels the job
455 delay(1300L) // delay a bit to ensure it was cancelled indeed
456 println("main: Now I can quit.")
457}
458```
459
Roman Elizarovfa7723e2017-02-06 11:17:51 +0300460> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-cancel-04.kt)
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300461
462The example above produces the following output:
463
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300464```text
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300465I'm sleeping 0 ...
466I'm sleeping 1 ...
467I'm sleeping 2 ...
468main: I'm tired of waiting!
469I'm running finally
470main: Now I can quit.
471```
472
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300473<!--- TEST -->
474
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300475### Run non-cancellable block
476
477Any attempt to use a suspending function in the `finally` block of the previous example will cause
Roman Elizarov419a6c82017-02-09 18:36:22 +0300478[CancellationException], because the coroutine running this code is cancelled. Usually, this is not a
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300479problem, since all well-behaving closing operations (closing a file, cancelling a job, or closing any kind of a
480communication channel) are usually non-blocking and do not involve any suspending functions. However, in the
481rare case when you need to suspend in the cancelled coroutine you can wrap the corresponding code in
Roman Elizarov419a6c82017-02-09 18:36:22 +0300482`run(NonCancellable) {...}` using [run] function and [NonCancellable] context as the following example shows:
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300483
484```kotlin
485fun main(args: Array<String>) = runBlocking<Unit> {
486 val job = launch(CommonPool) {
487 try {
488 repeat(1000) { i ->
489 println("I'm sleeping $i ...")
490 delay(500L)
491 }
492 } finally {
493 run(NonCancellable) {
494 println("I'm running finally")
495 delay(1000L)
496 println("And I've just delayed for 1 sec because I'm non-cancellable")
497 }
498 }
499 }
500 delay(1300L) // delay a bit
501 println("main: I'm tired of waiting!")
502 job.cancel() // cancels the job
503 delay(1300L) // delay a bit to ensure it was cancelled indeed
504 println("main: Now I can quit.")
505}
506```
507
Roman Elizarovfa7723e2017-02-06 11:17:51 +0300508> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-cancel-05.kt)
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300509
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300510<!--- TEST
511I'm sleeping 0 ...
512I'm sleeping 1 ...
513I'm sleeping 2 ...
514main: I'm tired of waiting!
515I'm running finally
516And I've just delayed for 1 sec because I'm non-cancellable
517main: Now I can quit.
518-->
519
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300520### Timeout
521
522The most obvious reason to cancel coroutine execution in practice,
523is because its execution time has exceeded some timeout.
Roman Elizarov419a6c82017-02-09 18:36:22 +0300524While you can manually track the reference to the corresponding [Job] and launch a separate coroutine to cancel
525the tracked one after delay, there is a ready to use [withTimeout] function that does it.
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300526Look at the following example:
527
528```kotlin
529fun main(args: Array<String>) = runBlocking<Unit> {
530 withTimeout(1300L) {
531 repeat(1000) { i ->
532 println("I'm sleeping $i ...")
533 delay(500L)
534 }
535 }
536}
537```
538
Roman Elizarovfa7723e2017-02-06 11:17:51 +0300539> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-cancel-06.kt)
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300540
541It produces the following output:
542
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300543```text
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300544I'm sleeping 0 ...
545I'm sleeping 1 ...
546I'm sleeping 2 ...
Roman Elizarovca9d5be2017-04-20 19:23:18 +0300547Exception in thread "main" kotlinx.coroutines.experimental.TimeoutException: Timed out waiting for 1300 MILLISECONDS
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300548```
549
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300550<!--- TEST STARTS_WITH -->
551
Roman Elizarovca9d5be2017-04-20 19:23:18 +0300552The `TimeoutException` that is thrown by [withTimeout] is a private subclass of [CancellationException].
553We have not seen its stack trace printed on the console before. That is because
Roman Elizarov7c864d82017-02-27 10:17:50 +0300554inside a cancelled coroutine `CancellationException` is considered to be a normal reason for coroutine completion.
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300555However, in this example we have used `withTimeout` right inside the `main` function.
556
557Because cancellation is just an exception, all the resources will be closed in a usual way.
558You can wrap the code with timeout in `try {...} catch (e: CancellationException) {...}` block if
559you need to do some additional action specifically on timeout.
560
561## Composing suspending functions
562
563This section covers various approaches to composition of suspending functions.
564
565### Sequential by default
566
567Assume that we have two suspending functions defined elsewhere that do something useful like some kind of
Roman Elizarovb7721cf2017-02-03 19:23:08 +0300568remote service call or computation. We just pretend they are useful, but actually each one just
569delays for a second for the purpose of this example:
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300570
Roman Elizarovfa7723e2017-02-06 11:17:51 +0300571<!--- INCLUDE .*/example-compose-([0-9]+).kt
572import kotlin.system.measureTimeMillis
573-->
574
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300575```kotlin
576suspend fun doSomethingUsefulOne(): Int {
577 delay(1000L) // pretend we are doing something useful here
578 return 13
579}
580
581suspend fun doSomethingUsefulTwo(): Int {
582 delay(1000L) // pretend we are doing something useful here, too
583 return 29
584}
585```
586
Roman Elizarovfa7723e2017-02-06 11:17:51 +0300587<!--- INCLUDE .*/example-compose-([0-9]+).kt -->
588
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300589What do we do if need to invoke them _sequentially_ -- first `doSomethingUsefulOne` _and then_
590`doSomethingUsefulTwo` and compute the sum of their results?
591In practise we do this if we use the results of the first function to make a decision on whether we need
592to invoke the second one or to decide on how to invoke it.
593
594We just use a normal sequential invocation, because the code in the coroutine, just like in the regular
Roman Elizarov32d95322017-02-09 15:57:31 +0300595code, is _sequential_ by default. The following example demonstrates it by measuring the total
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300596time it takes to execute both suspending functions:
597
598```kotlin
599fun main(args: Array<String>) = runBlocking<Unit> {
600 val time = measureTimeMillis {
601 val one = doSomethingUsefulOne()
602 val two = doSomethingUsefulTwo()
603 println("The answer is ${one + two}")
604 }
605 println("Completed in $time ms")
606}
607```
608
Roman Elizarovfa7723e2017-02-06 11:17:51 +0300609> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-compose-01.kt)
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300610
611It produces something like this:
612
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300613```text
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300614The answer is 42
615Completed in 2017 ms
616```
617
Roman Elizarov35d2c342017-07-20 14:54:39 +0300618<!--- TEST ARBITRARY_TIME -->
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300619
Roman Elizarov32d95322017-02-09 15:57:31 +0300620### Concurrent using async
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300621
622What if there are no dependencies between invocation of `doSomethingUsefulOne` and `doSomethingUsefulTwo` and
Roman Elizarov419a6c82017-02-09 18:36:22 +0300623we want to get the answer faster, by doing both _concurrently_? This is where [async] comes to help.
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300624
Roman Elizarov419a6c82017-02-09 18:36:22 +0300625Conceptually, [async] is just like [launch]. It starts a separate coroutine which is a light-weight thread
626that works concurrently with all the other coroutines. The difference is that `launch` returns a [Job] and
627does not carry any resulting value, while `async` returns a [Deferred] -- a light-weight non-blocking future
Roman Elizarov32d95322017-02-09 15:57:31 +0300628that represents a promise to provide a result later. You can use `.await()` on a deferred value to get its eventual result,
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300629but `Deferred` is also a `Job`, so you can cancel it if needed.
630
631```kotlin
632fun main(args: Array<String>) = runBlocking<Unit> {
633 val time = measureTimeMillis {
Roman Elizarov32d95322017-02-09 15:57:31 +0300634 val one = async(CommonPool) { doSomethingUsefulOne() }
635 val two = async(CommonPool) { doSomethingUsefulTwo() }
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300636 println("The answer is ${one.await() + two.await()}")
637 }
638 println("Completed in $time ms")
639}
640```
641
Roman Elizarovfa7723e2017-02-06 11:17:51 +0300642> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-compose-02.kt)
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300643
644It produces something like this:
645
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300646```text
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300647The answer is 42
648Completed in 1017 ms
649```
650
Roman Elizarov35d2c342017-07-20 14:54:39 +0300651<!--- TEST ARBITRARY_TIME -->
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300652
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300653This is twice as fast, because we have concurrent execution of two coroutines.
654Note, that concurrency with coroutines is always explicit.
655
Roman Elizarov32d95322017-02-09 15:57:31 +0300656### Lazily started async
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300657
Roman Elizarovecda27f2017-04-06 23:06:26 +0300658There is a laziness option to [async] with [CoroutineStart.LAZY] parameter.
Roman Elizarov419a6c82017-02-09 18:36:22 +0300659It starts coroutine only when its result is needed by some
660[await][Deferred.await] or if a [start][Job.start] function
Roman Elizarov32d95322017-02-09 15:57:31 +0300661is invoked. Run the following example that differs from the previous one only by this option:
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300662
663```kotlin
664fun main(args: Array<String>) = runBlocking<Unit> {
665 val time = measureTimeMillis {
Roman Elizarovecda27f2017-04-06 23:06:26 +0300666 val one = async(CommonPool, CoroutineStart.LAZY) { doSomethingUsefulOne() }
667 val two = async(CommonPool, CoroutineStart.LAZY) { doSomethingUsefulTwo() }
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300668 println("The answer is ${one.await() + two.await()}")
669 }
670 println("Completed in $time ms")
671}
672```
673
Roman Elizarovfa7723e2017-02-06 11:17:51 +0300674> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-compose-03.kt)
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300675
676It produces something like this:
677
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300678```text
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300679The answer is 42
680Completed in 2017 ms
681```
682
Roman Elizarov35d2c342017-07-20 14:54:39 +0300683<!--- TEST ARBITRARY_TIME -->
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300684
Roman Elizarov32d95322017-02-09 15:57:31 +0300685So, we are back to sequential execution, because we _first_ start and await for `one`, _and then_ start and await
686for `two`. It is not the intended use-case for laziness. It is designed as a replacement for
687the standard `lazy` function in cases when computation of the value involves suspending functions.
688
689### Async-style functions
690
691We can define async-style functions that invoke `doSomethingUsefulOne` and `doSomethingUsefulTwo`
Roman Elizarov419a6c82017-02-09 18:36:22 +0300692_asynchronously_ using [async] coroutine builder. It is a good style to name such functions with
Roman Elizarov32d95322017-02-09 15:57:31 +0300693either "async" prefix of "Async" suffix to highlight the fact that they only start asynchronous
694computation and one needs to use the resulting deferred value to get the result.
695
696```kotlin
697// The result type of asyncSomethingUsefulOne is Deferred<Int>
698fun asyncSomethingUsefulOne() = async(CommonPool) {
699 doSomethingUsefulOne()
700}
701
702// The result type of asyncSomethingUsefulTwo is Deferred<Int>
703fun asyncSomethingUsefulTwo() = async(CommonPool) {
704 doSomethingUsefulTwo()
705}
706```
707
708Note, that these `asyncXXX` function are **not** _suspending_ functions. They can be used from anywhere.
709However, their use always implies asynchronous (here meaning _concurrent_) execution of their action
710with the invoking code.
711
712The following example shows their use outside of coroutine:
713
714```kotlin
715// note, that we don't have `runBlocking` to the right of `main` in this example
716fun main(args: Array<String>) {
717 val time = measureTimeMillis {
718 // we can initiate async actions outside of a coroutine
719 val one = asyncSomethingUsefulOne()
720 val two = asyncSomethingUsefulTwo()
721 // but waiting for a result must involve either suspending or blocking.
722 // here we use `runBlocking { ... }` to block the main thread while waiting for the result
723 runBlocking {
724 println("The answer is ${one.await() + two.await()}")
725 }
726 }
727 println("Completed in $time ms")
728}
729```
730
731> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-compose-04.kt)
Roman Elizarov1293ccd2017-02-01 18:49:54 +0300732
Roman Elizarov35d2c342017-07-20 14:54:39 +0300733<!--- TEST ARBITRARY_TIME
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300734The answer is 42
735Completed in 1085 ms
736-->
737
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300738## Coroutine context and dispatchers
739
Roman Elizarov32d95322017-02-09 15:57:31 +0300740We've already seen `launch(CommonPool) {...}`, `async(CommonPool) {...}`, `run(NonCancellable) {...}`, etc.
Roman Elizarov419a6c82017-02-09 18:36:22 +0300741In these code snippets [CommonPool] and [NonCancellable] are _coroutine contexts_.
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300742This section covers other available choices.
743
744### Dispatchers and threads
745
Roman Elizarov419a6c82017-02-09 18:36:22 +0300746Coroutine context includes a [_coroutine dispatcher_][CoroutineDispatcher] which determines what thread or threads
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300747the corresponding coroutine uses for its execution. Coroutine dispatcher can confine coroutine execution
748to a specific thread, dispatch it to a thread pool, or let it run unconfined. Try the following example:
749
750```kotlin
751fun main(args: Array<String>) = runBlocking<Unit> {
752 val jobs = arrayListOf<Job>()
753 jobs += launch(Unconfined) { // not confined -- will work with main thread
Roman Elizarov43e3af72017-07-21 16:01:31 +0300754 println(" 'Unconfined': I'm working in thread ${Thread.currentThread().name}")
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300755 }
Roman Elizarov43e3af72017-07-21 16:01:31 +0300756 jobs += launch(coroutineContext) { // context of the parent, runBlocking coroutine
757 println("'coroutineContext': I'm working in thread ${Thread.currentThread().name}")
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300758 }
759 jobs += launch(CommonPool) { // will get dispatched to ForkJoinPool.commonPool (or equivalent)
Roman Elizarov43e3af72017-07-21 16:01:31 +0300760 println(" 'CommonPool': I'm working in thread ${Thread.currentThread().name}")
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300761 }
762 jobs += launch(newSingleThreadContext("MyOwnThread")) { // will get its own new thread
Roman Elizarov43e3af72017-07-21 16:01:31 +0300763 println(" 'newSTC': I'm working in thread ${Thread.currentThread().name}")
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300764 }
765 jobs.forEach { it.join() }
766}
767```
768
Roman Elizarovfa7723e2017-02-06 11:17:51 +0300769> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-context-01.kt)
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300770
771It produces the following output (maybe in different order):
772
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300773```text
Roman Elizarov43e3af72017-07-21 16:01:31 +0300774 'Unconfined': I'm working in thread main
775 'CommonPool': I'm working in thread ForkJoinPool.commonPool-worker-1
776 'newSTC': I'm working in thread MyOwnThread
777'coroutineContext': I'm working in thread main
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300778```
779
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300780<!--- TEST LINES_START_UNORDERED -->
781
Roman Elizarov43e3af72017-07-21 16:01:31 +0300782The difference between parent [coroutineContext][CoroutineScope.coroutineContext] and
783[Unconfined] context will be shown later.
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300784
785### Unconfined vs confined dispatcher
786
Roman Elizarov419a6c82017-02-09 18:36:22 +0300787The [Unconfined] coroutine dispatcher starts coroutine in the caller thread, but only until the
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300788first suspension point. After suspension it resumes in the thread that is fully determined by the
789suspending function that was invoked. Unconfined dispatcher is appropriate when coroutine does not
790consume CPU time nor updates any shared data (like UI) that is confined to a specific thread.
791
Roman Elizarov43e3af72017-07-21 16:01:31 +0300792On the other side, [coroutineContext][CoroutineScope.coroutineContext] property that is available inside the block of any coroutine
Roman Elizarov419a6c82017-02-09 18:36:22 +0300793via [CoroutineScope] interface, is a reference to a context of this particular coroutine.
794This way, a parent context can be inherited. The default context of [runBlocking], in particular,
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300795is confined to be invoker thread, so inheriting it has the effect of confining execution to
796this thread with a predictable FIFO scheduling.
797
798```kotlin
799fun main(args: Array<String>) = runBlocking<Unit> {
800 val jobs = arrayListOf<Job>()
801 jobs += launch(Unconfined) { // not confined -- will work with main thread
Roman Elizarov43e3af72017-07-21 16:01:31 +0300802 println(" 'Unconfined': I'm working in thread ${Thread.currentThread().name}")
Roman Elizarovd0021622017-03-10 15:43:38 +0300803 delay(500)
Roman Elizarov43e3af72017-07-21 16:01:31 +0300804 println(" 'Unconfined': After delay in thread ${Thread.currentThread().name}")
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300805 }
Roman Elizarov43e3af72017-07-21 16:01:31 +0300806 jobs += launch(coroutineContext) { // context of the parent, runBlocking coroutine
807 println("'coroutineContext': I'm working in thread ${Thread.currentThread().name}")
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300808 delay(1000)
Roman Elizarov43e3af72017-07-21 16:01:31 +0300809 println("'coroutineContext': After delay in thread ${Thread.currentThread().name}")
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300810 }
811 jobs.forEach { it.join() }
812}
813```
814
Roman Elizarovd0021622017-03-10 15:43:38 +0300815> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-context-02.kt)
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300816
817Produces the output:
818
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300819```text
Roman Elizarov43e3af72017-07-21 16:01:31 +0300820 'Unconfined': I'm working in thread main
821'coroutineContext': I'm working in thread main
822 'Unconfined': After delay in thread kotlinx.coroutines.DefaultExecutor
823'coroutineContext': After delay in thread main
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300824```
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300825
826<!--- TEST LINES_START -->
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300827
Roman Elizarov43e3af72017-07-21 16:01:31 +0300828So, the coroutine that had inherited `coroutineContext` of `runBlocking {...}` continues to execute
829in the `main` thread, while the unconfined one had resumed in the default executor thread that [delay]
830function is using.
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300831
832### Debugging coroutines and threads
833
Roman Elizarov419a6c82017-02-09 18:36:22 +0300834Coroutines can suspend on one thread and resume on another thread with [Unconfined] dispatcher or
835with a multi-threaded dispatcher like [CommonPool]. Even with a single-threaded dispatcher it might be hard to
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300836figure out what coroutine was doing what, where, and when. The common approach to debugging applications with
837threads is to print the thread name in the log file on each log statement. This feature is universally supported
838by logging frameworks. When using coroutines, the thread name alone does not give much of a context, so
839`kotlinx.coroutines` includes debugging facilities to make it easier.
840
841Run the following code with `-Dkotlinx.coroutines.debug` JVM option:
842
843```kotlin
844fun log(msg: String) = println("[${Thread.currentThread().name}] $msg")
845
846fun main(args: Array<String>) = runBlocking<Unit> {
Roman Elizarov43e3af72017-07-21 16:01:31 +0300847 val a = async(coroutineContext) {
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300848 log("I'm computing a piece of the answer")
849 6
850 }
Roman Elizarov43e3af72017-07-21 16:01:31 +0300851 val b = async(coroutineContext) {
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300852 log("I'm computing another piece of the answer")
853 7
854 }
855 log("The answer is ${a.await() * b.await()}")
856}
857```
858
Roman Elizarovfa7723e2017-02-06 11:17:51 +0300859> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-context-03.kt)
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300860
Roman Elizarovb7721cf2017-02-03 19:23:08 +0300861There are three coroutines. The main coroutine (#1) -- `runBlocking` one,
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300862and two coroutines computing deferred values `a` (#2) and `b` (#3).
863They are all executing in the context of `runBlocking` and are confined to the main thread.
864The output of this code is:
865
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300866```text
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300867[main @coroutine#2] I'm computing a piece of the answer
868[main @coroutine#3] I'm computing another piece of the answer
869[main @coroutine#1] The answer is 42
870```
871
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300872<!--- TEST -->
873
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300874The `log` function prints the name of the thread in square brackets and you can see, that it is the `main`
875thread, but the identifier of the currently executing coroutine is appended to it. This identifier
876is consecutively assigned to all created coroutines when debugging mode is turned on.
877
Roman Elizarov419a6c82017-02-09 18:36:22 +0300878You can read more about debugging facilities in the documentation for [newCoroutineContext] function.
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300879
880### Jumping between threads
881
882Run the following code with `-Dkotlinx.coroutines.debug` JVM option:
883
884```kotlin
885fun log(msg: String) = println("[${Thread.currentThread().name}] $msg")
886
887fun main(args: Array<String>) {
888 val ctx1 = newSingleThreadContext("Ctx1")
889 val ctx2 = newSingleThreadContext("Ctx2")
890 runBlocking(ctx1) {
891 log("Started in ctx1")
892 run(ctx2) {
893 log("Working in ctx2")
894 }
895 log("Back to ctx1")
896 }
897}
898```
899
Roman Elizarovfa7723e2017-02-06 11:17:51 +0300900> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-context-04.kt)
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300901
Roman Elizarov419a6c82017-02-09 18:36:22 +0300902It demonstrates two new techniques. One is using [runBlocking] with an explicitly specified context, and
903the second one is using [run] function to change a context of a coroutine while still staying in the
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300904same coroutine as you can see in the output below:
905
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300906```text
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300907[Ctx1 @coroutine#1] Started in ctx1
908[Ctx2 @coroutine#1] Working in ctx2
909[Ctx1 @coroutine#1] Back to ctx1
910```
911
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300912<!--- TEST -->
913
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300914### Job in the context
915
Roman Elizarov419a6c82017-02-09 18:36:22 +0300916The coroutine [Job] is part of its context. The coroutine can retrieve it from its own context
Roman Elizarov43e3af72017-07-21 16:01:31 +0300917using `coroutineContext[Job]` expression:
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300918
919```kotlin
920fun main(args: Array<String>) = runBlocking<Unit> {
Roman Elizarov43e3af72017-07-21 16:01:31 +0300921 println("My job is ${coroutineContext[Job]}")
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300922}
923```
924
Roman Elizarovfa7723e2017-02-06 11:17:51 +0300925> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-context-05.kt)
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300926
shifujun81a6f232017-06-18 15:37:59 +0800927It produces something like
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300928
929```
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300930My job is BlockingCoroutine{Active}@65ae6ba4
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300931```
932
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300933<!--- TEST lines.size == 1 && lines[0].startsWith("My job is BlockingCoroutine{Active}@") -->
934
Roman Elizarov43e3af72017-07-21 16:01:31 +0300935So, [isActive][CoroutineScope.isActive] in [CoroutineScope] is just a convenient shortcut for
936`coroutineContext[Job]!!.isActive`.
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300937
938### Children of a coroutine
939
Roman Elizarov43e3af72017-07-21 16:01:31 +0300940When [coroutineContext][CoroutineScope.coroutineContext] of a coroutine is used to launch another coroutine,
Roman Elizarov419a6c82017-02-09 18:36:22 +0300941the [Job] of the new coroutine becomes
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300942a _child_ of the parent coroutine's job. When the parent coroutine is cancelled, all its children
943are recursively cancelled, too.
944
945```kotlin
946fun main(args: Array<String>) = runBlocking<Unit> {
947 // start a coroutine to process some kind of incoming request
948 val request = launch(CommonPool) {
949 // it spawns two other jobs, one with its separate context
950 val job1 = launch(CommonPool) {
951 println("job1: I have my own context and execute independently!")
952 delay(1000)
953 println("job1: I am not affected by cancellation of the request")
954 }
955 // and the other inherits the parent context
Roman Elizarov43e3af72017-07-21 16:01:31 +0300956 val job2 = launch(coroutineContext) {
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300957 println("job2: I am a child of the request coroutine")
958 delay(1000)
959 println("job2: I will not execute this line if my parent request is cancelled")
960 }
961 // request completes when both its sub-jobs complete:
962 job1.join()
963 job2.join()
964 }
965 delay(500)
966 request.cancel() // cancel processing of the request
967 delay(1000) // delay a second to see what happens
968 println("main: Who has survived request cancellation?")
969}
970```
971
Roman Elizarovfa7723e2017-02-06 11:17:51 +0300972> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-context-06.kt)
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300973
974The output of this code is:
975
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300976```text
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300977job1: I have my own context and execute independently!
978job2: I am a child of the request coroutine
979job1: I am not affected by cancellation of the request
980main: Who has survived request cancellation?
981```
982
Roman Elizarov731f0ad2017-02-22 20:48:45 +0300983<!--- TEST -->
984
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300985### Combining contexts
986
987Coroutine context can be combined using `+` operator. The context on the right-hand side replaces relevant entries
Roman Elizarov419a6c82017-02-09 18:36:22 +0300988of the context on the left-hand side. For example, a [Job] of the parent coroutine can be inherited, while
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300989its dispatcher replaced:
990
991```kotlin
992fun main(args: Array<String>) = runBlocking<Unit> {
993 // start a coroutine to process some kind of incoming request
Roman Elizarov43e3af72017-07-21 16:01:31 +0300994 val request = launch(coroutineContext) { // use the context of `runBlocking`
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300995 // spawns CPU-intensive child job in CommonPool !!!
Roman Elizarov43e3af72017-07-21 16:01:31 +0300996 val job = launch(coroutineContext + CommonPool) {
Roman Elizarov2f6d7c92017-02-03 15:16:07 +0300997 println("job: I am a child of the request coroutine, but with a different dispatcher")
998 delay(1000)
999 println("job: I will not execute this line if my parent request is cancelled")
1000 }
1001 job.join() // request completes when its sub-job completes
1002 }
1003 delay(500)
1004 request.cancel() // cancel processing of the request
1005 delay(1000) // delay a second to see what happens
1006 println("main: Who has survived request cancellation?")
1007}
1008```
1009
Roman Elizarovfa7723e2017-02-06 11:17:51 +03001010> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-context-07.kt)
Roman Elizarov2f6d7c92017-02-03 15:16:07 +03001011
1012The expected outcome of this code is:
1013
Roman Elizarov731f0ad2017-02-22 20:48:45 +03001014```text
Roman Elizarov2f6d7c92017-02-03 15:16:07 +03001015job: I am a child of the request coroutine, but with a different dispatcher
1016main: Who has survived request cancellation?
1017```
1018
Roman Elizarov731f0ad2017-02-22 20:48:45 +03001019<!--- TEST -->
1020
Roman Elizarov2f6d7c92017-02-03 15:16:07 +03001021### Naming coroutines for debugging
1022
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001023Automatically assigned ids are good when coroutines log often and you just need to correlate log records
Roman Elizarov2f6d7c92017-02-03 15:16:07 +03001024coming from the same coroutine. However, when coroutine is tied to the processing of a specific request
1025or doing some specific background task, it is better to name it explicitly for debugging purposes.
Roman Elizarov419a6c82017-02-09 18:36:22 +03001026[CoroutineName] serves the same function as a thread name. It'll get displayed in the thread name that
Victor Osolovskiyed5ed492017-06-25 00:03:35 +03001027is executing this coroutine when debugging mode is turned on.
Roman Elizarov2f6d7c92017-02-03 15:16:07 +03001028
1029The following example demonstrates this concept:
1030
1031```kotlin
1032fun log(msg: String) = println("[${Thread.currentThread().name}] $msg")
1033
1034fun main(args: Array<String>) = runBlocking(CoroutineName("main")) {
1035 log("Started main coroutine")
1036 // run two background value computations
Roman Elizarov32d95322017-02-09 15:57:31 +03001037 val v1 = async(CommonPool + CoroutineName("v1coroutine")) {
Roman Elizarov2f6d7c92017-02-03 15:16:07 +03001038 log("Computing v1")
1039 delay(500)
1040 252
1041 }
Roman Elizarov32d95322017-02-09 15:57:31 +03001042 val v2 = async(CommonPool + CoroutineName("v2coroutine")) {
Roman Elizarov2f6d7c92017-02-03 15:16:07 +03001043 log("Computing v2")
1044 delay(1000)
1045 6
1046 }
1047 log("The answer for v1 / v2 = ${v1.await() / v2.await()}")
1048}
1049```
1050
Roman Elizarovfa7723e2017-02-06 11:17:51 +03001051> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-context-08.kt)
Roman Elizarov2f6d7c92017-02-03 15:16:07 +03001052
1053The output it produces with `-Dkotlinx.coroutines.debug` JVM option is similar to:
1054
Roman Elizarov731f0ad2017-02-22 20:48:45 +03001055```text
Roman Elizarov2f6d7c92017-02-03 15:16:07 +03001056[main @main#1] Started main coroutine
1057[ForkJoinPool.commonPool-worker-1 @v1coroutine#2] Computing v1
1058[ForkJoinPool.commonPool-worker-2 @v2coroutine#3] Computing v2
1059[main @main#1] The answer for v1 / v2 = 42
1060```
Roman Elizarov1293ccd2017-02-01 18:49:54 +03001061
Roman Elizarov731f0ad2017-02-22 20:48:45 +03001062<!--- TEST FLEXIBLE_THREAD -->
1063
Roman Elizarov2fd7cb32017-02-11 23:18:59 +03001064### Cancellation via explicit job
1065
1066Let us put our knowledge about contexts, children and jobs together. Assume that our application has
1067an object with a lifecycle, but that object is not a coroutine. For example, we are writing an Android application
1068and launch various coroutines in the context of an Android activity to perform asynchronous operations to fetch
1069and update data, do animations, etc. All of these coroutines must be cancelled when activity is destroyed
1070to avoid memory leaks.
1071
1072We can manage a lifecycle of our coroutines by creating an instance of [Job] that is tied to
Roman Elizarov256812a2017-07-22 01:00:30 +03001073the lifecycle of our activity. A job instance is created using [`Job()`][Job] factory function
Roman Elizarov2fd7cb32017-02-11 23:18:59 +03001074as the following example shows. We need to make sure that all the coroutines are started
1075with this job in their context and then a single invocation of [Job.cancel] terminates them all.
1076
1077```kotlin
1078fun main(args: Array<String>) = runBlocking<Unit> {
1079 val job = Job() // create a job object to manage our lifecycle
1080 // now launch ten coroutines for a demo, each working for a different time
1081 val coroutines = List(10) { i ->
1082 // they are all children of our job object
Roman Elizarov43e3af72017-07-21 16:01:31 +03001083 launch(coroutineContext + job) { // we use the context of main runBlocking thread, but with our own job object
Roman Elizarov2fd7cb32017-02-11 23:18:59 +03001084 delay(i * 200L) // variable delay 0ms, 200ms, 400ms, ... etc
1085 println("Coroutine $i is done")
1086 }
1087 }
1088 println("Launched ${coroutines.size} coroutines")
1089 delay(500L) // delay for half a second
1090 println("Cancelling job!")
1091 job.cancel() // cancel our job.. !!!
1092 delay(1000L) // delay for more to see if our coroutines are still working
1093}
1094```
1095
1096> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-context-09.kt)
1097
1098The output of this example is:
1099
Roman Elizarov731f0ad2017-02-22 20:48:45 +03001100```text
Roman Elizarov2fd7cb32017-02-11 23:18:59 +03001101Launched 10 coroutines
1102Coroutine 0 is done
1103Coroutine 1 is done
1104Coroutine 2 is done
1105Cancelling job!
1106```
1107
Roman Elizarov731f0ad2017-02-22 20:48:45 +03001108<!--- TEST -->
1109
Roman Elizarov2fd7cb32017-02-11 23:18:59 +03001110As you can see, only the first three coroutines had printed a message and the others were cancelled
1111by a single invocation of `job.cancel()`. So all we need to do in our hypothetical Android
1112application is to create a parent job object when activity is created, use it for child coroutines,
1113and cancel it when activity is destroyed.
1114
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001115## Channels
Roman Elizarov7deefb82017-01-31 10:33:17 +03001116
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001117Deferred values provide a convenient way to transfer a single value between coroutines.
1118Channels provide a way to transfer a stream of values.
1119
1120<!--- INCLUDE .*/example-channel-([0-9]+).kt
1121import kotlinx.coroutines.experimental.channels.*
1122-->
1123
1124### Channel basics
1125
Roman Elizarov419a6c82017-02-09 18:36:22 +03001126A [Channel] is conceptually very similar to `BlockingQueue`. One key difference is that
1127instead of a blocking `put` operation it has a suspending [send][SendChannel.send], and instead of
1128a blocking `take` operation it has a suspending [receive][ReceiveChannel.receive].
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001129
1130```kotlin
1131fun main(args: Array<String>) = runBlocking<Unit> {
1132 val channel = Channel<Int>()
1133 launch(CommonPool) {
1134 // this might be heavy CPU-consuming computation or async logic, we'll just send five squares
1135 for (x in 1..5) channel.send(x * x)
1136 }
1137 // here we print five received integers:
1138 repeat(5) { println(channel.receive()) }
1139 println("Done!")
1140}
1141```
1142
1143> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-channel-01.kt)
1144
Roman Elizarov731f0ad2017-02-22 20:48:45 +03001145The output of this code is:
1146
1147```text
11481
11494
11509
115116
115225
1153Done!
1154```
1155
1156<!--- TEST -->
1157
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001158### Closing and iteration over channels
1159
1160Unlike a queue, a channel can be closed to indicate that no more elements are coming.
1161On the receiver side it is convenient to use a regular `for` loop to receive elements
1162from the channel.
1163
Roman Elizarov419a6c82017-02-09 18:36:22 +03001164Conceptually, a [close][SendChannel.close] is like sending a special close token to the channel.
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001165The iteration stops as soon as this close token is received, so there is a guarantee
1166that all previously sent elements before the close are received:
1167
1168```kotlin
1169fun main(args: Array<String>) = runBlocking<Unit> {
1170 val channel = Channel<Int>()
1171 launch(CommonPool) {
1172 for (x in 1..5) channel.send(x * x)
1173 channel.close() // we're done sending
1174 }
1175 // here we print received values using `for` loop (until the channel is closed)
1176 for (y in channel) println(y)
1177 println("Done!")
1178}
1179```
1180
1181> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-channel-02.kt)
1182
Roman Elizarov731f0ad2017-02-22 20:48:45 +03001183<!--- TEST
11841
11854
11869
118716
118825
1189Done!
1190-->
1191
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001192### Building channel producers
1193
Roman Elizarova5e653f2017-02-13 13:49:55 +03001194The pattern where a coroutine is producing a sequence of elements is quite common.
1195This is a part of _producer-consumer_ pattern that is often found in concurrent code.
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001196You could abstract such a producer into a function that takes channel as its parameter, but this goes contrary
Roman Elizarova5e653f2017-02-13 13:49:55 +03001197to common sense that results must be returned from functions.
1198
Roman Elizarov86349be2017-03-17 16:47:37 +03001199There is a convenience coroutine builder named [produce] that makes it easy to do it right on producer side,
1200and an extension function [consumeEach], that can replace a `for` loop on the consumer side:
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001201
1202```kotlin
Roman Elizarova5e653f2017-02-13 13:49:55 +03001203fun produceSquares() = produce<Int>(CommonPool) {
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001204 for (x in 1..5) send(x * x)
1205}
1206
1207fun main(args: Array<String>) = runBlocking<Unit> {
1208 val squares = produceSquares()
Roman Elizarov86349be2017-03-17 16:47:37 +03001209 squares.consumeEach { println(it) }
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001210 println("Done!")
1211}
1212```
1213
1214> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-channel-03.kt)
1215
Roman Elizarov731f0ad2017-02-22 20:48:45 +03001216<!--- TEST
12171
12184
12199
122016
122125
1222Done!
1223-->
1224
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001225### Pipelines
1226
1227Pipeline is a pattern where one coroutine is producing, possibly infinite, stream of values:
1228
1229```kotlin
Roman Elizarova5e653f2017-02-13 13:49:55 +03001230fun produceNumbers() = produce<Int>(CommonPool) {
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001231 var x = 1
1232 while (true) send(x++) // infinite stream of integers starting from 1
1233}
1234```
1235
Roman Elizarova5e653f2017-02-13 13:49:55 +03001236And another coroutine or coroutines are consuming that stream, doing some processing, and producing some other results.
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001237In the below example the numbers are just squared:
1238
1239```kotlin
Roman Elizarova5e653f2017-02-13 13:49:55 +03001240fun square(numbers: ReceiveChannel<Int>) = produce<Int>(CommonPool) {
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001241 for (x in numbers) send(x * x)
1242}
1243```
1244
Roman Elizarova5e653f2017-02-13 13:49:55 +03001245The main code starts and connects the whole pipeline:
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001246
1247```kotlin
1248fun main(args: Array<String>) = runBlocking<Unit> {
1249 val numbers = produceNumbers() // produces integers from 1 and on
1250 val squares = square(numbers) // squares integers
1251 for (i in 1..5) println(squares.receive()) // print first five
1252 println("Done!") // we are done
1253 squares.cancel() // need to cancel these coroutines in a larger app
1254 numbers.cancel()
1255}
1256```
1257
1258> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-channel-04.kt)
1259
Roman Elizarov731f0ad2017-02-22 20:48:45 +03001260<!--- TEST
12611
12624
12639
126416
126525
1266Done!
1267-->
1268
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001269We don't have to cancel these coroutines in this example app, because
1270[coroutines are like daemon threads](#coroutines-are-like-daemon-threads),
1271but in a larger app we'll need to stop our pipeline if we don't need it anymore.
1272Alternatively, we could have run pipeline coroutines as
1273[children of a coroutine](#children-of-a-coroutine).
1274
1275### Prime numbers with pipeline
1276
Cedric Beustfa0b28f2017-02-07 07:07:25 -08001277Let's take pipelines to the extreme with an example that generates prime numbers using a pipeline
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001278of coroutines. We start with an infinite sequence of numbers. This time we introduce an
1279explicit context parameter, so that caller can control where our coroutines run:
1280
1281<!--- INCLUDE kotlinx-coroutines-core/src/test/kotlin/guide/example-channel-05.kt
1282import kotlin.coroutines.experimental.CoroutineContext
1283-->
1284
1285```kotlin
Roman Elizarova5e653f2017-02-13 13:49:55 +03001286fun numbersFrom(context: CoroutineContext, start: Int) = produce<Int>(context) {
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001287 var x = start
1288 while (true) send(x++) // infinite stream of integers from start
1289}
1290```
1291
1292The following pipeline stage filters an incoming stream of numbers, removing all the numbers
1293that are divisible by the given prime number:
1294
1295```kotlin
Roman Elizarova5e653f2017-02-13 13:49:55 +03001296fun filter(context: CoroutineContext, numbers: ReceiveChannel<Int>, prime: Int) = produce<Int>(context) {
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001297 for (x in numbers) if (x % prime != 0) send(x)
1298}
1299```
1300
1301Now we build our pipeline by starting a stream of numbers from 2, taking a prime number from the current channel,
Roman Elizarov62500ba2017-02-09 18:55:40 +03001302and launching new pipeline stage for each prime number found:
1303
1304```
Roman Elizarova5e653f2017-02-13 13:49:55 +03001305numbersFrom(2) -> filter(2) -> filter(3) -> filter(5) -> filter(7) ...
Roman Elizarov62500ba2017-02-09 18:55:40 +03001306```
1307
1308The following example prints the first ten prime numbers,
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001309running the whole pipeline in the context of the main thread:
1310
1311```kotlin
1312fun main(args: Array<String>) = runBlocking<Unit> {
Roman Elizarov43e3af72017-07-21 16:01:31 +03001313 var cur = numbersFrom(coroutineContext, 2)
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001314 for (i in 1..10) {
1315 val prime = cur.receive()
1316 println(prime)
Roman Elizarov43e3af72017-07-21 16:01:31 +03001317 cur = filter(coroutineContext, cur, prime)
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001318 }
1319}
1320```
1321
1322> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-channel-05.kt)
1323
1324The output of this code is:
1325
Roman Elizarov731f0ad2017-02-22 20:48:45 +03001326```text
Roman Elizarovb7721cf2017-02-03 19:23:08 +030013272
13283
13295
13307
133111
133213
133317
133419
133523
133629
1337```
1338
Roman Elizarov731f0ad2017-02-22 20:48:45 +03001339<!--- TEST -->
1340
Roman Elizarova5e653f2017-02-13 13:49:55 +03001341Note, that you can build the same pipeline using `buildIterator` coroutine builder from the standard library.
1342Replace `produce` with `buildIterator`, `send` with `yield`, `receive` with `next`,
Roman Elizarov62500ba2017-02-09 18:55:40 +03001343`ReceiveChannel` with `Iterator`, and get rid of the context. You will not need `runBlocking` either.
1344However, the benefit of a pipeline that uses channels as shown above is that it can actually use
1345multiple CPU cores if you run it in [CommonPool] context.
1346
Roman Elizarova5e653f2017-02-13 13:49:55 +03001347Anyway, this is an extremely impractical way to find prime numbers. In practice, pipelines do involve some
Roman Elizarov62500ba2017-02-09 18:55:40 +03001348other suspending invocations (like asynchronous calls to remote services) and these pipelines cannot be
1349built using `buildSeqeunce`/`buildIterator`, because they do not allow arbitrary suspension, unlike
Roman Elizarova5e653f2017-02-13 13:49:55 +03001350`produce` which is fully asynchronous.
Roman Elizarov62500ba2017-02-09 18:55:40 +03001351
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001352### Fan-out
1353
1354Multiple coroutines may receive from the same channel, distributing work between themselves.
1355Let us start with a producer coroutine that is periodically producing integers
1356(ten numbers per second):
1357
1358```kotlin
Roman Elizarova5e653f2017-02-13 13:49:55 +03001359fun produceNumbers() = produce<Int>(CommonPool) {
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001360 var x = 1 // start from 1
1361 while (true) {
1362 send(x++) // produce next
1363 delay(100) // wait 0.1s
1364 }
1365}
1366```
1367
1368Then we can have several processor coroutines. In this example, they just print their id and
1369received number:
1370
1371```kotlin
1372fun launchProcessor(id: Int, channel: ReceiveChannel<Int>) = launch(CommonPool) {
Roman Elizarov86349be2017-03-17 16:47:37 +03001373 channel.consumeEach {
1374 println("Processor #$id received $it")
Roman Elizarovec9384c2017-03-02 22:09:08 +03001375 }
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001376}
1377```
1378
Roman Elizarov35d2c342017-07-20 14:54:39 +03001379Now let us launch five processors and let them work for almost a second. See what happens:
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001380
1381```kotlin
1382fun main(args: Array<String>) = runBlocking<Unit> {
1383 val producer = produceNumbers()
1384 repeat(5) { launchProcessor(it, producer) }
Roman Elizarov35d2c342017-07-20 14:54:39 +03001385 delay(950)
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001386 producer.cancel() // cancel producer coroutine and thus kill them all
1387}
1388```
1389
1390> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-channel-06.kt)
1391
1392The output will be similar to the the following one, albeit the processor ids that receive
1393each specific integer may be different:
1394
1395```
1396Processor #2 received 1
1397Processor #4 received 2
1398Processor #0 received 3
1399Processor #1 received 4
1400Processor #3 received 5
1401Processor #2 received 6
1402Processor #4 received 7
1403Processor #0 received 8
1404Processor #1 received 9
1405Processor #3 received 10
1406```
1407
Roman Elizarov731f0ad2017-02-22 20:48:45 +03001408<!--- TEST lines.size == 10 && lines.withIndex().all { (i, line) -> line.startsWith("Processor #") && line.endsWith(" received ${i + 1}") } -->
1409
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001410Note, that cancelling a producer coroutine closes its channel, thus eventually terminating iteration
1411over the channel that processor coroutines are doing.
1412
1413### Fan-in
1414
1415Multiple coroutines may send to the same channel.
1416For example, let us have a channel of strings, and a suspending function that
1417repeatedly sends a specified string to this channel with a specified delay:
1418
1419```kotlin
1420suspend fun sendString(channel: SendChannel<String>, s: String, time: Long) {
1421 while (true) {
1422 delay(time)
1423 channel.send(s)
1424 }
1425}
1426```
1427
Cedric Beustfa0b28f2017-02-07 07:07:25 -08001428Now, let us see what happens if we launch a couple of coroutines sending strings
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001429(in this example we launch them in the context of the main thread):
1430
1431```kotlin
1432fun main(args: Array<String>) = runBlocking<Unit> {
1433 val channel = Channel<String>()
Roman Elizarov43e3af72017-07-21 16:01:31 +03001434 launch(coroutineContext) { sendString(channel, "foo", 200L) }
1435 launch(coroutineContext) { sendString(channel, "BAR!", 500L) }
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001436 repeat(6) { // receive first six
1437 println(channel.receive())
1438 }
1439}
1440```
1441
1442> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-channel-07.kt)
1443
1444The output is:
1445
Roman Elizarov731f0ad2017-02-22 20:48:45 +03001446```text
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001447foo
1448foo
1449BAR!
1450foo
1451foo
1452BAR!
1453```
1454
Roman Elizarov731f0ad2017-02-22 20:48:45 +03001455<!--- TEST -->
1456
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001457### Buffered channels
1458
1459The channels shown so far had no buffer. Unbuffered channels transfer elements when sender and receiver
1460meet each other (aka rendezvous). If send is invoked first, then it is suspended until receive is invoked,
1461if receive is invoked first, it is suspended until send is invoked.
Roman Elizarov419a6c82017-02-09 18:36:22 +03001462
Roman Elizarov256812a2017-07-22 01:00:30 +03001463Both [`Channel()`][Channel] factory function and [produce] builder take an optional `capacity` parameter to
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001464specify _buffer size_. Buffer allows senders to send multiple elements before suspending,
1465similar to the `BlockingQueue` with a specified capacity, which blocks when buffer is full.
1466
1467Take a look at the behavior of the following code:
1468
1469```kotlin
1470fun main(args: Array<String>) = runBlocking<Unit> {
1471 val channel = Channel<Int>(4) // create buffered channel
Roman Elizarov43e3af72017-07-21 16:01:31 +03001472 launch(coroutineContext) { // launch sender coroutine
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001473 repeat(10) {
1474 println("Sending $it") // print before sending each element
1475 channel.send(it) // will suspend when buffer is full
1476 }
1477 }
1478 // don't receive anything... just wait....
1479 delay(1000)
1480}
1481```
1482
1483> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-channel-08.kt)
1484
1485It prints "sending" _five_ times using a buffered channel with capacity of _four_:
1486
Roman Elizarov731f0ad2017-02-22 20:48:45 +03001487```text
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001488Sending 0
1489Sending 1
1490Sending 2
1491Sending 3
1492Sending 4
1493```
1494
Roman Elizarov731f0ad2017-02-22 20:48:45 +03001495<!--- TEST -->
1496
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001497The first four elements are added to the buffer and the sender suspends when trying to send the fifth one.
Roman Elizarov419a6c82017-02-09 18:36:22 +03001498
Roman Elizarovb0517ba2017-02-27 14:03:14 +03001499
1500### Channels are fair
1501
1502Send and receive operations to channels are _fair_ with respect to the order of their invocation from
1503multiple coroutines. They are served in first-in first-out order, e.g. the first coroutine to invoke `receive`
1504gets the element. In the following example two coroutines "ping" and "pong" are
1505receiving the "ball" object from the shared "table" channel.
1506
1507```kotlin
1508data class Ball(var hits: Int)
1509
1510fun main(args: Array<String>) = runBlocking<Unit> {
1511 val table = Channel<Ball>() // a shared table
Roman Elizarov43e3af72017-07-21 16:01:31 +03001512 launch(coroutineContext) { player("ping", table) }
1513 launch(coroutineContext) { player("pong", table) }
Roman Elizarovb0517ba2017-02-27 14:03:14 +03001514 table.send(Ball(0)) // serve the ball
1515 delay(1000) // delay 1 second
1516 table.receive() // game over, grab the ball
1517}
1518
1519suspend fun player(name: String, table: Channel<Ball>) {
1520 for (ball in table) { // receive the ball in a loop
1521 ball.hits++
1522 println("$name $ball")
Roman Elizarovf526b132017-03-10 16:07:14 +03001523 delay(300) // wait a bit
Roman Elizarovb0517ba2017-02-27 14:03:14 +03001524 table.send(ball) // send the ball back
1525 }
1526}
1527```
1528
1529> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-channel-09.kt)
1530
1531The "ping" coroutine is started first, so it is the first one to receive the ball. Even though "ping"
1532coroutine immediately starts receiving the ball again after sending it back to the table, the ball gets
1533received by the "pong" coroutine, because it was already waiting for it:
1534
1535```text
1536ping Ball(hits=1)
1537pong Ball(hits=2)
1538ping Ball(hits=3)
1539pong Ball(hits=4)
1540ping Ball(hits=5)
Roman Elizarovb0517ba2017-02-27 14:03:14 +03001541```
1542
1543<!--- TEST -->
1544
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001545## Shared mutable state and concurrency
1546
1547Coroutines can be executed concurrently using a multi-threaded dispatcher like [CommonPool]. It presents
1548all the usual concurrency problems. The main problem being synchronization of access to **shared mutable state**.
1549Some solutions to this problem in the land of coroutines are similar to the solutions in the multi-threaded world,
1550but others are unique.
1551
1552### The problem
1553
Roman Elizarov1e459602017-02-27 11:05:17 +03001554Let us launch a thousand coroutines all doing the same action thousand times (for a total of a million executions).
1555We'll also measure their completion time for further comparisons:
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001556
Roman Elizarov43e90112017-05-10 11:25:20 +03001557<!--- INCLUDE .*/example-sync-([0-9a-z]+).kt
Roman Elizarov1e459602017-02-27 11:05:17 +03001558import kotlin.coroutines.experimental.CoroutineContext
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001559import kotlin.system.measureTimeMillis
1560-->
1561
Roman Elizarov1e459602017-02-27 11:05:17 +03001562<!--- INCLUDE .*/example-sync-03.kt
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001563import java.util.concurrent.atomic.AtomicInteger
1564-->
1565
Roman Elizarov1e459602017-02-27 11:05:17 +03001566<!--- INCLUDE .*/example-sync-06.kt
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001567import kotlinx.coroutines.experimental.sync.Mutex
1568-->
1569
Roman Elizarov1e459602017-02-27 11:05:17 +03001570<!--- INCLUDE .*/example-sync-07.kt
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001571import kotlinx.coroutines.experimental.channels.*
1572-->
1573
1574```kotlin
Roman Elizarov1e459602017-02-27 11:05:17 +03001575suspend fun massiveRun(context: CoroutineContext, action: suspend () -> Unit) {
1576 val n = 1000 // number of coroutines to launch
1577 val k = 1000 // times an action is repeated by each coroutine
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001578 val time = measureTimeMillis {
1579 val jobs = List(n) {
Roman Elizarov1e459602017-02-27 11:05:17 +03001580 launch(context) {
1581 repeat(k) { action() }
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001582 }
1583 }
1584 jobs.forEach { it.join() }
1585 }
Roman Elizarov1e459602017-02-27 11:05:17 +03001586 println("Completed ${n * k} actions in $time ms")
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001587}
1588```
1589
Roman Elizarov43e90112017-05-10 11:25:20 +03001590<!--- INCLUDE .*/example-sync-([0-9a-z]+).kt -->
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001591
Roman Elizarov1e459602017-02-27 11:05:17 +03001592We start with a very simple action that increments a shared mutable variable using
1593multi-threaded [CommonPool] context.
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001594
1595```kotlin
1596var counter = 0
1597
1598fun main(args: Array<String>) = runBlocking<Unit> {
Roman Elizarov1e459602017-02-27 11:05:17 +03001599 massiveRun(CommonPool) {
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001600 counter++
1601 }
1602 println("Counter = $counter")
1603}
1604```
1605
1606> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-sync-01.kt)
1607
Roman Elizarov1e459602017-02-27 11:05:17 +03001608<!--- TEST LINES_START
1609Completed 1000000 actions in
1610Counter =
1611-->
Roman Elizarov731f0ad2017-02-22 20:48:45 +03001612
Roman Elizarov1e459602017-02-27 11:05:17 +03001613What does it print at the end? It is highly unlikely to ever print "Counter = 1000000", because a thousand coroutines
1614increment the `counter` concurrently from multiple threads without any synchronization.
1615
Roman Elizarov43e90112017-05-10 11:25:20 +03001616> Note: if you have an old system with 2 or fewer CPUs, then you _will_ consistently see 1000000, because
1617`CommonPool` is running in only one thread in this case. To reproduce the problem you'll need to make the
1618following change:
1619
1620```kotlin
1621val mtContext = newFixedThreadPoolContext(2, "mtPool") // explicitly define context with two threads
1622var counter = 0
1623
1624fun main(args: Array<String>) = runBlocking<Unit> {
1625 massiveRun(mtContext) { // use it instead of CommonPool in this sample and below
1626 counter++
1627 }
1628 println("Counter = $counter")
1629}
1630```
1631
1632> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-sync-01b.kt)
1633
1634<!--- TEST LINES_START
1635Completed 1000000 actions in
1636Counter =
1637-->
1638
Roman Elizarov1e459602017-02-27 11:05:17 +03001639### Volatiles are of no help
1640
1641There is common misconception that making a variable `volatile` solves concurrency problem. Let us try it:
1642
1643```kotlin
1644@Volatile // in Kotlin `volatile` is an annotation
1645var counter = 0
1646
1647fun main(args: Array<String>) = runBlocking<Unit> {
1648 massiveRun(CommonPool) {
1649 counter++
1650 }
1651 println("Counter = $counter")
1652}
1653```
1654
1655> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-sync-02.kt)
1656
1657<!--- TEST LINES_START
1658Completed 1000000 actions in
1659Counter =
1660-->
1661
1662This code works slower, but we still don't get "Counter = 1000000" at the end, because volatile variables guarantee
1663linearizable (this is a technical term for "atomic") reads and writes to the corresponding variable, but
1664do not provide atomicity of larger actions (increment in our case).
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001665
1666### Thread-safe data structures
1667
1668The general solution that works both for threads and for coroutines is to use a thread-safe (aka synchronized,
1669linearizable, or atomic) data structure that provides all the necessarily synchronization for the corresponding
1670operations that needs to be performed on a shared state.
Roman Elizarov1e459602017-02-27 11:05:17 +03001671In the case of a simple counter we can use `AtomicInteger` class which has atomic `incrementAndGet` operations:
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001672
1673```kotlin
1674var counter = AtomicInteger()
1675
1676fun main(args: Array<String>) = runBlocking<Unit> {
Roman Elizarov1e459602017-02-27 11:05:17 +03001677 massiveRun(CommonPool) {
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001678 counter.incrementAndGet()
1679 }
1680 println("Counter = ${counter.get()}")
1681}
1682```
1683
Roman Elizarov1e459602017-02-27 11:05:17 +03001684> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-sync-03.kt)
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001685
Roman Elizarov1e459602017-02-27 11:05:17 +03001686<!--- TEST ARBITRARY_TIME
1687Completed 1000000 actions in xxx ms
1688Counter = 1000000
1689-->
Roman Elizarov731f0ad2017-02-22 20:48:45 +03001690
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001691This is the fastest solution for this particular problem. It works for plain counters, collections, queues and other
1692standard data structures and basic operations on them. However, it does not easily scale to complex
1693state or to complex operations that do not have ready-to-use thread-safe implementations.
1694
Roman Elizarov1e459602017-02-27 11:05:17 +03001695### Thread confinement fine-grained
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001696
Roman Elizarov1e459602017-02-27 11:05:17 +03001697_Thread confinement_ is an approach to the problem of shared mutable state where all access to the particular shared
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001698state is confined to a single thread. It is typically used in UI applications, where all UI state is confined to
1699the single event-dispatch/application thread. It is easy to apply with coroutines by using a
1700single-threaded context:
1701
1702```kotlin
1703val counterContext = newSingleThreadContext("CounterContext")
1704var counter = 0
1705
1706fun main(args: Array<String>) = runBlocking<Unit> {
Roman Elizarov1e459602017-02-27 11:05:17 +03001707 massiveRun(CommonPool) { // run each coroutine in CommonPool
1708 run(counterContext) { // but confine each increment to the single-threaded context
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001709 counter++
1710 }
1711 }
1712 println("Counter = $counter")
1713}
1714```
1715
Roman Elizarov1e459602017-02-27 11:05:17 +03001716> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-sync-04.kt)
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001717
Roman Elizarov1e459602017-02-27 11:05:17 +03001718<!--- TEST ARBITRARY_TIME
1719Completed 1000000 actions in xxx ms
1720Counter = 1000000
1721-->
1722
1723This code works very slowly, because it does _fine-grained_ thread-confinement. Each individual increment switches
1724from multi-threaded `CommonPool` context to the single-threaded context using [run] block.
1725
1726### Thread confinement coarse-grained
1727
1728In practice, thread confinement is performed in large chunks, e.g. big pieces of state-updating business logic
1729are confined to the single thread. The following example does it like that, running each coroutine in
1730the single-threaded context to start with.
1731
1732```kotlin
1733val counterContext = newSingleThreadContext("CounterContext")
1734var counter = 0
1735
1736fun main(args: Array<String>) = runBlocking<Unit> {
1737 massiveRun(counterContext) { // run each coroutine in the single-threaded context
1738 counter++
1739 }
1740 println("Counter = $counter")
1741}
1742```
1743
1744> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-sync-05.kt)
1745
1746<!--- TEST ARBITRARY_TIME
1747Completed 1000000 actions in xxx ms
1748Counter = 1000000
1749-->
1750
1751This now works much faster and produces correct result.
Roman Elizarov731f0ad2017-02-22 20:48:45 +03001752
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001753### Mutual exclusion
1754
1755Mutual exclusion solution to the problem is to protect all modifications of the shared state with a _critical section_
1756that is never executed concurrently. In a blocking world you'd typically use `synchronized` or `ReentrantLock` for that.
1757Coroutine's alternative is called [Mutex]. It has [lock][Mutex.lock] and [unlock][Mutex.unlock] functions to
1758delimit a critical section. The key difference is that `Mutex.lock` is a suspending function. It does not block a thread.
1759
1760```kotlin
1761val mutex = Mutex()
1762var counter = 0
1763
1764fun main(args: Array<String>) = runBlocking<Unit> {
Roman Elizarov1e459602017-02-27 11:05:17 +03001765 massiveRun(CommonPool) {
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001766 mutex.lock()
1767 try { counter++ }
1768 finally { mutex.unlock() }
1769 }
1770 println("Counter = $counter")
1771}
1772```
1773
Roman Elizarov1e459602017-02-27 11:05:17 +03001774> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-sync-06.kt)
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001775
Roman Elizarov1e459602017-02-27 11:05:17 +03001776<!--- TEST ARBITRARY_TIME
1777Completed 1000000 actions in xxx ms
1778Counter = 1000000
1779-->
1780
1781The locking in this example is fine-grained, so it pays the price. However, it is a good choice for some situations
1782where you absolutely must modify some shared state periodically, but there is no natural thread that this state
1783is confined to.
Roman Elizarov731f0ad2017-02-22 20:48:45 +03001784
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001785### Actors
1786
1787An actor is a combination of a coroutine, the state that is confined and is encapsulated into this coroutine,
1788and a channel to communicate with other coroutines. A simple actor can be written as a function,
1789but an actor with a complex state is better suited for a class.
1790
Roman Elizarovc0e19f82017-02-27 11:59:14 +03001791There is an [actor] coroutine builder that conveniently combines actor's mailbox channel into its
1792scope to receive messages from and combines the send channel into the resulting job object, so that a
1793single reference to the actor can be carried around as its handle.
1794
Roman Elizarov256812a2017-07-22 01:00:30 +03001795The first step of using an actor is to define a class of messages that an actor is going to process.
1796Kotlin's [sealed classes](https://kotlinlang.org/docs/reference/sealed-classes.html) are well suited for that purpose.
1797We define `CounterMsg` sealed class with `IncCounter` message to increment a counter and `GetCounter` message
1798to get its value. The later needs to send a response. A [CompletableDeferred] communication
1799primitive, that represents a single value that will be known (communicated) in the future,
1800is used here for that purpose.
1801
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001802```kotlin
1803// Message types for counterActor
1804sealed class CounterMsg
1805object IncCounter : CounterMsg() // one-way message to increment counter
Roman Elizarov256812a2017-07-22 01:00:30 +03001806class GetCounter(val response: CompletableDeferred<Int>) : CounterMsg() // a request with reply
1807```
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001808
Roman Elizarov256812a2017-07-22 01:00:30 +03001809Then we define a function that launches an actor using an [actor] coroutine builder:
1810
1811```kotlin
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001812// This function launches a new counter actor
Roman Elizarovc0e19f82017-02-27 11:59:14 +03001813fun counterActor() = actor<CounterMsg>(CommonPool) {
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001814 var counter = 0 // actor state
Roman Elizarovc0e19f82017-02-27 11:59:14 +03001815 for (msg in channel) { // iterate over incoming messages
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001816 when (msg) {
1817 is IncCounter -> counter++
Roman Elizarov256812a2017-07-22 01:00:30 +03001818 is GetCounter -> msg.response.complete(counter)
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001819 }
1820 }
1821}
Roman Elizarov256812a2017-07-22 01:00:30 +03001822```
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001823
Roman Elizarov256812a2017-07-22 01:00:30 +03001824The main code is straightforward:
1825
1826```kotlin
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001827fun main(args: Array<String>) = runBlocking<Unit> {
Roman Elizarovc0e19f82017-02-27 11:59:14 +03001828 val counter = counterActor() // create the actor
Roman Elizarov1e459602017-02-27 11:05:17 +03001829 massiveRun(CommonPool) {
Roman Elizarovc0e19f82017-02-27 11:59:14 +03001830 counter.send(IncCounter)
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001831 }
Roman Elizarov256812a2017-07-22 01:00:30 +03001832 // send a message to get a counter value from an actor
1833 val response = CompletableDeferred<Int>()
Roman Elizarovc0e19f82017-02-27 11:59:14 +03001834 counter.send(GetCounter(response))
Roman Elizarov256812a2017-07-22 01:00:30 +03001835 println("Counter = ${response.await()}")
Roman Elizarovc0e19f82017-02-27 11:59:14 +03001836 counter.close() // shutdown the actor
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001837}
1838```
1839
Roman Elizarov1e459602017-02-27 11:05:17 +03001840> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-sync-07.kt)
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001841
Roman Elizarov1e459602017-02-27 11:05:17 +03001842<!--- TEST ARBITRARY_TIME
1843Completed 1000000 actions in xxx ms
1844Counter = 1000000
1845-->
Roman Elizarov731f0ad2017-02-22 20:48:45 +03001846
Roman Elizarovc0e19f82017-02-27 11:59:14 +03001847It does not matter (for correctness) what context the actor itself is executed in. An actor is
Roman Elizarovf5bc0472017-02-22 11:38:13 +03001848a coroutine and a coroutine is executed sequentially, so confinement of the state to the specific coroutine
1849works as a solution to the problem of shared mutable state.
1850
Roman Elizarovc0e19f82017-02-27 11:59:14 +03001851Actor is more efficient than locking under load, because in this case it always has work to do and it does not
1852have to switch to a different context at all.
1853
1854> Note, that an [actor] coroutine builder is a dual of [produce] coroutine builder. An actor is associated
1855 with the channel that it receives messages from, while a producer is associated with the channel that it
1856 sends elements to.
Roman Elizarov1e459602017-02-27 11:05:17 +03001857
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03001858## Select expression
1859
Roman Elizarova84730b2017-02-22 11:58:50 +03001860Select expression makes it possible to await multiple suspending functions simultaneously and _select_
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03001861the first one that becomes available.
1862
1863<!--- INCLUDE .*/example-select-([0-9]+).kt
1864import kotlinx.coroutines.experimental.channels.*
1865import kotlinx.coroutines.experimental.selects.*
1866-->
1867
1868### Selecting from channels
1869
Roman Elizarov57857202017-03-02 23:17:25 +03001870Let us have two producers of strings: `fizz` and `buzz`. The `fizz` produces "Fizz" string every 300 ms:
1871
1872<!--- INCLUDE .*/example-select-01.kt
1873import kotlin.coroutines.experimental.CoroutineContext
1874-->
1875
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03001876```kotlin
Roman Elizarov57857202017-03-02 23:17:25 +03001877fun fizz(context: CoroutineContext) = produce<String>(context) {
1878 while (true) { // sends "Fizz" every 300 ms
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03001879 delay(300)
1880 send("Fizz")
1881 }
1882}
1883```
1884
Roman Elizarov57857202017-03-02 23:17:25 +03001885And the `buzz` produces "Buzz!" string every 500 ms:
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03001886
1887```kotlin
Roman Elizarov57857202017-03-02 23:17:25 +03001888fun buzz(context: CoroutineContext) = produce<String>(context) {
1889 while (true) { // sends "Buzz!" every 500 ms
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03001890 delay(500)
1891 send("Buzz!")
1892 }
1893}
1894```
1895
1896Using [receive][ReceiveChannel.receive] suspending function we can receive _either_ from one channel or the
1897other. But [select] expression allows us to receive from _both_ simultaneously using its
1898[onReceive][SelectBuilder.onReceive] clauses:
1899
1900```kotlin
Roman Elizarov57857202017-03-02 23:17:25 +03001901suspend fun selectFizzBuzz(fizz: ReceiveChannel<String>, buzz: ReceiveChannel<String>) {
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03001902 select<Unit> { // <Unit> means that this select expression does not produce any result
1903 fizz.onReceive { value -> // this is the first select clause
1904 println("fizz -> '$value'")
1905 }
1906 buzz.onReceive { value -> // this is the second select clause
1907 println("buzz -> '$value'")
1908 }
1909 }
1910}
1911```
1912
Roman Elizarov57857202017-03-02 23:17:25 +03001913Let us run it all seven times:
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03001914
1915```kotlin
1916fun main(args: Array<String>) = runBlocking<Unit> {
Roman Elizarov43e3af72017-07-21 16:01:31 +03001917 val fizz = fizz(coroutineContext)
1918 val buzz = buzz(coroutineContext)
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03001919 repeat(7) {
Roman Elizarov57857202017-03-02 23:17:25 +03001920 selectFizzBuzz(fizz, buzz)
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03001921 }
1922}
1923```
1924
1925> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-select-01.kt)
1926
1927The result of this code is:
1928
Roman Elizarov731f0ad2017-02-22 20:48:45 +03001929```text
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03001930fizz -> 'Fizz'
1931buzz -> 'Buzz!'
1932fizz -> 'Fizz'
1933fizz -> 'Fizz'
1934buzz -> 'Buzz!'
1935fizz -> 'Fizz'
1936buzz -> 'Buzz!'
1937```
1938
Roman Elizarov731f0ad2017-02-22 20:48:45 +03001939<!--- TEST -->
1940
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03001941### Selecting on close
1942
1943The [onReceive][SelectBuilder.onReceive] clause in `select` fails when the channel is closed and the corresponding
1944`select` throws an exception. We can use [onReceiveOrNull][SelectBuilder.onReceiveOrNull] clause to perform a
Roman Elizarova84730b2017-02-22 11:58:50 +03001945specific action when the channel is closed. The following example also shows that `select` is an expression that returns
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03001946the result of its selected clause:
1947
1948```kotlin
1949suspend fun selectAorB(a: ReceiveChannel<String>, b: ReceiveChannel<String>): String =
1950 select<String> {
1951 a.onReceiveOrNull { value ->
1952 if (value == null)
1953 "Channel 'a' is closed"
1954 else
1955 "a -> '$value'"
1956 }
1957 b.onReceiveOrNull { value ->
1958 if (value == null)
1959 "Channel 'b' is closed"
1960 else
1961 "b -> '$value'"
1962 }
1963 }
1964```
1965
Roman Elizarova84730b2017-02-22 11:58:50 +03001966Let's use it with channel `a` that produces "Hello" string four times and
1967channel `b` that produces "World" four times:
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03001968
1969```kotlin
1970fun main(args: Array<String>) = runBlocking<Unit> {
1971 // we are using the context of the main thread in this example for predictability ...
Roman Elizarov43e3af72017-07-21 16:01:31 +03001972 val a = produce<String>(coroutineContext) {
Roman Elizarova84730b2017-02-22 11:58:50 +03001973 repeat(4) { send("Hello $it") }
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03001974 }
Roman Elizarov43e3af72017-07-21 16:01:31 +03001975 val b = produce<String>(coroutineContext) {
Roman Elizarova84730b2017-02-22 11:58:50 +03001976 repeat(4) { send("World $it") }
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03001977 }
1978 repeat(8) { // print first eight results
1979 println(selectAorB(a, b))
1980 }
1981}
1982```
1983
1984> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-select-02.kt)
1985
Roman Elizarova84730b2017-02-22 11:58:50 +03001986The result of this code is quite interesting, so we'll analyze it in mode detail:
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03001987
Roman Elizarov731f0ad2017-02-22 20:48:45 +03001988```text
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03001989a -> 'Hello 0'
1990a -> 'Hello 1'
1991b -> 'World 0'
1992a -> 'Hello 2'
1993a -> 'Hello 3'
1994b -> 'World 1'
1995Channel 'a' is closed
1996Channel 'a' is closed
1997```
1998
Roman Elizarov731f0ad2017-02-22 20:48:45 +03001999<!--- TEST -->
2000
Roman Elizarova84730b2017-02-22 11:58:50 +03002001There are couple of observations to make out of it.
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03002002
2003First of all, `select` is _biased_ to the first clause. When several clauses are selectable at the same time,
2004the first one among them gets selected. Here, both channels are constantly producing strings, so `a` channel,
Roman Elizarova84730b2017-02-22 11:58:50 +03002005being the first clause in select, wins. However, because we are using unbuffered channel, the `a` gets suspended from
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03002006time to time on its [send][SendChannel.send] invocation and gives a chance for `b` to send, too.
2007
2008The second observation, is that [onReceiveOrNull][SelectBuilder.onReceiveOrNull] gets immediately selected when the
2009channel is already closed.
2010
2011### Selecting to send
2012
2013Select expression has [onSend][SelectBuilder.onSend] clause that can be used for a great good in combination
2014with a biased nature of selection.
2015
Roman Elizarova84730b2017-02-22 11:58:50 +03002016Let us write an example of producer of integers that sends its values to a `side` channel when
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03002017the consumers on its primary channel cannot keep up with it:
2018
2019```kotlin
2020fun produceNumbers(side: SendChannel<Int>) = produce<Int>(CommonPool) {
2021 for (num in 1..10) { // produce 10 numbers from 1 to 10
2022 delay(100) // every 100 ms
2023 select<Unit> {
Roman Elizarova84730b2017-02-22 11:58:50 +03002024 onSend(num) {} // Send to the primary channel
2025 side.onSend(num) {} // or to the side channel
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03002026 }
2027 }
2028}
2029```
2030
2031Consumer is going to be quite slow, taking 250 ms to process each number:
2032
2033```kotlin
2034fun main(args: Array<String>) = runBlocking<Unit> {
2035 val side = Channel<Int>() // allocate side channel
Roman Elizarov43e3af72017-07-21 16:01:31 +03002036 launch(coroutineContext) { // this is a very fast consumer for the side channel
Roman Elizarov86349be2017-03-17 16:47:37 +03002037 side.consumeEach { println("Side channel has $it") }
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03002038 }
Roman Elizarov86349be2017-03-17 16:47:37 +03002039 produceNumbers(side).consumeEach {
2040 println("Consuming $it")
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03002041 delay(250) // let us digest the consumed number properly, do not hurry
2042 }
2043 println("Done consuming")
2044}
2045```
2046
2047> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-select-03.kt)
2048
2049So let us see what happens:
2050
Roman Elizarov731f0ad2017-02-22 20:48:45 +03002051```text
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03002052Consuming 1
2053Side channel has 2
2054Side channel has 3
2055Consuming 4
2056Side channel has 5
2057Side channel has 6
2058Consuming 7
2059Side channel has 8
2060Side channel has 9
2061Consuming 10
2062Done consuming
2063```
2064
Roman Elizarov731f0ad2017-02-22 20:48:45 +03002065<!--- TEST -->
2066
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03002067### Selecting deferred values
2068
Roman Elizarova84730b2017-02-22 11:58:50 +03002069Deferred values can be selected using [onAwait][SelectBuilder.onAwait] clause.
2070Let us start with an async function that returns a deferred string value after
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03002071a random delay:
2072
2073<!--- INCLUDE .*/example-select-04.kt
2074import java.util.*
2075-->
2076
2077```kotlin
2078fun asyncString(time: Int) = async(CommonPool) {
2079 delay(time.toLong())
2080 "Waited for $time ms"
2081}
2082```
2083
Roman Elizarova84730b2017-02-22 11:58:50 +03002084Let us start a dozen of them with a random delay.
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03002085
2086```kotlin
2087fun asyncStringsList(): List<Deferred<String>> {
2088 val random = Random(3)
Roman Elizarova84730b2017-02-22 11:58:50 +03002089 return List(12) { asyncString(random.nextInt(1000)) }
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03002090}
2091```
2092
Roman Elizarova84730b2017-02-22 11:58:50 +03002093Now the main function awaits for the first of them to complete and counts the number of deferred values
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03002094that are still active. Note, that we've used here the fact that `select` expression is a Kotlin DSL,
Roman Elizarova84730b2017-02-22 11:58:50 +03002095so we can provide clauses for it using an arbitrary code. In this case we iterate over a list
2096of deferred values to provide `onAwait` clause for each deferred value.
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03002097
2098```kotlin
2099fun main(args: Array<String>) = runBlocking<Unit> {
2100 val list = asyncStringsList()
2101 val result = select<String> {
2102 list.withIndex().forEach { (index, deferred) ->
2103 deferred.onAwait { answer ->
2104 "Deferred $index produced answer '$answer'"
2105 }
2106 }
2107 }
2108 println(result)
Roman Elizarov7c864d82017-02-27 10:17:50 +03002109 val countActive = list.count { it.isActive }
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03002110 println("$countActive coroutines are still active")
2111}
2112```
2113
2114> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-select-04.kt)
2115
2116The output is:
2117
Roman Elizarov731f0ad2017-02-22 20:48:45 +03002118```text
Roman Elizarova84730b2017-02-22 11:58:50 +03002119Deferred 4 produced answer 'Waited for 128 ms'
Roman Elizarovd4dcbe22017-02-22 09:57:46 +0300212011 coroutines are still active
2121```
2122
Roman Elizarov731f0ad2017-02-22 20:48:45 +03002123<!--- TEST -->
2124
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03002125### Switch over a channel of deferred values
2126
Roman Elizarova84730b2017-02-22 11:58:50 +03002127Let us write a channel producer function that consumes a channel of deferred string values, waits for each received
2128deferred value, but only until the next deferred value comes over or the channel is closed. This example puts together
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03002129[onReceiveOrNull][SelectBuilder.onReceiveOrNull] and [onAwait][SelectBuilder.onAwait] clauses in the same `select`:
2130
2131```kotlin
2132fun switchMapDeferreds(input: ReceiveChannel<Deferred<String>>) = produce<String>(CommonPool) {
Roman Elizarova84730b2017-02-22 11:58:50 +03002133 var current = input.receive() // start with first received deferred value
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03002134 while (isActive) { // loop while not cancelled/closed
2135 val next = select<Deferred<String>?> { // return next deferred value from this select or null
2136 input.onReceiveOrNull { update ->
2137 update // replaces next value to wait
2138 }
2139 current.onAwait { value ->
2140 send(value) // send value that current deferred has produced
2141 input.receiveOrNull() // and use the next deferred from the input channel
2142 }
2143 }
2144 if (next == null) {
2145 println("Channel was closed")
2146 break // out of loop
2147 } else {
2148 current = next
2149 }
2150 }
2151}
2152```
2153
2154To test it, we'll use a simple async function that resolves to a specified string after a specified time:
2155
2156```kotlin
2157fun asyncString(str: String, time: Long) = async(CommonPool) {
2158 delay(time)
2159 str
2160}
2161```
2162
2163The main function just launches a coroutine to print results of `switchMapDeferreds` and sends some test
2164data to it:
2165
2166```kotlin
2167fun main(args: Array<String>) = runBlocking<Unit> {
2168 val chan = Channel<Deferred<String>>() // the channel for test
Roman Elizarov43e3af72017-07-21 16:01:31 +03002169 launch(coroutineContext) { // launch printing coroutine
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03002170 for (s in switchMapDeferreds(chan))
2171 println(s) // print each received string
2172 }
2173 chan.send(asyncString("BEGIN", 100))
2174 delay(200) // enough time for "BEGIN" to be produced
2175 chan.send(asyncString("Slow", 500))
Roman Elizarova84730b2017-02-22 11:58:50 +03002176 delay(100) // not enough time to produce slow
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03002177 chan.send(asyncString("Replace", 100))
Roman Elizarova84730b2017-02-22 11:58:50 +03002178 delay(500) // give it time before the last one
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03002179 chan.send(asyncString("END", 500))
2180 delay(1000) // give it time to process
Roman Elizarova84730b2017-02-22 11:58:50 +03002181 chan.close() // close the channel ...
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03002182 delay(500) // and wait some time to let it finish
2183}
2184```
2185
2186> You can get full code [here](kotlinx-coroutines-core/src/test/kotlin/guide/example-select-05.kt)
2187
2188The result of this code:
2189
Roman Elizarov731f0ad2017-02-22 20:48:45 +03002190```text
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03002191BEGIN
2192Replace
2193END
2194Channel was closed
2195```
2196
Roman Elizarov731f0ad2017-02-22 20:48:45 +03002197<!--- TEST -->
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03002198
Roman Elizarov8db17332017-03-09 12:40:45 +03002199## Further reading
2200
2201* [Guide to UI programming with coroutines](ui/coroutines-guide-ui.md)
Roman Elizarov8a4a8e12017-03-09 19:52:58 +03002202* [Guide to reactive streams with coroutines](reactive/coroutines-guide-reactive.md)
Roman Elizarov8db17332017-03-09 12:40:45 +03002203* [Coroutines design document (KEEP)](https://github.com/Kotlin/kotlin-coroutines/blob/master/kotlin-coroutines-informal.md)
2204* [Full kotlinx.coroutines API reference](http://kotlin.github.io/kotlinx.coroutines)
2205
Roman Elizarove7e2ad12017-05-17 14:47:31 +03002206<!--- MODULE kotlinx-coroutines-core -->
Roman Elizarove0c817d2017-02-10 10:22:01 +03002207<!--- INDEX kotlinx.coroutines.experimental -->
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03002208[launch]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/launch.html
2209[delay]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/delay.html
2210[runBlocking]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/run-blocking.html
Roman Elizarov256812a2017-07-22 01:00:30 +03002211[Job]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-job.html
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03002212[CancellationException]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-cancellation-exception.html
2213[yield]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/yield.html
Roman Elizarovbff3f372017-03-01 18:12:27 +03002214[CoroutineScope.isActive]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-coroutine-scope/is-active.html
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03002215[CoroutineScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-coroutine-scope/index.html
2216[run]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/run.html
2217[NonCancellable]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-non-cancellable/index.html
2218[withTimeout]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/with-timeout.html
2219[async]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/async.html
2220[Deferred]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-deferred/index.html
Roman Elizarovecda27f2017-04-06 23:06:26 +03002221[CoroutineStart.LAZY]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-coroutine-start/-l-a-z-y.html
Roman Elizarovbff3f372017-03-01 18:12:27 +03002222[Deferred.await]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-deferred/await.html
2223[Job.start]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-job/start.html
Roman Elizarov419a6c82017-02-09 18:36:22 +03002224[CommonPool]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-common-pool/index.html
2225[CoroutineDispatcher]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-coroutine-dispatcher/index.html
Roman Elizarov43e3af72017-07-21 16:01:31 +03002226[CoroutineScope.coroutineContext]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-coroutine-scope/coroutine-context.html
Roman Elizarov419a6c82017-02-09 18:36:22 +03002227[Unconfined]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-unconfined/index.html
Roman Elizarov419a6c82017-02-09 18:36:22 +03002228[newCoroutineContext]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/new-coroutine-context.html
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03002229[CoroutineName]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-coroutine-name/index.html
Roman Elizarovbff3f372017-03-01 18:12:27 +03002230[Job.cancel]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-job/cancel.html
Roman Elizarov256812a2017-07-22 01:00:30 +03002231[CompletableDeferred]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-completable-deferred.html
Roman Elizarovf5bc0472017-02-22 11:38:13 +03002232<!--- INDEX kotlinx.coroutines.experimental.sync -->
Roman Elizarov256812a2017-07-22 01:00:30 +03002233[Mutex]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.sync/-mutex.html
Roman Elizarovbff3f372017-03-01 18:12:27 +03002234[Mutex.lock]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.sync/-mutex/lock.html
2235[Mutex.unlock]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.sync/-mutex/unlock.html
Roman Elizarove0c817d2017-02-10 10:22:01 +03002236<!--- INDEX kotlinx.coroutines.experimental.channels -->
Roman Elizarov256812a2017-07-22 01:00:30 +03002237[Channel]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-channel.html
Roman Elizarovbff3f372017-03-01 18:12:27 +03002238[SendChannel.send]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-send-channel/send.html
2239[ReceiveChannel.receive]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-receive-channel/receive.html
2240[SendChannel.close]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-send-channel/close.html
Roman Elizarova5e653f2017-02-13 13:49:55 +03002241[produce]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/produce.html
Roman Elizarov86349be2017-03-17 16:47:37 +03002242[consumeEach]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/consume-each.html
Roman Elizarovc0e19f82017-02-27 11:59:14 +03002243[actor]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/actor.html
Roman Elizarovd4dcbe22017-02-22 09:57:46 +03002244<!--- INDEX kotlinx.coroutines.experimental.selects -->
2245[select]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.selects/select.html
Roman Elizarovbff3f372017-03-01 18:12:27 +03002246[SelectBuilder.onReceive]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.selects/-select-builder/on-receive.html
2247[SelectBuilder.onReceiveOrNull]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.selects/-select-builder/on-receive-or-null.html
2248[SelectBuilder.onSend]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.selects/-select-builder/on-send.html
2249[SelectBuilder.onAwait]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.selects/-select-builder/on-await.html
Roman Elizarov419a6c82017-02-09 18:36:22 +03002250<!--- END -->