Skip to content

Commit f991742

Browse files
authored
docs: clarify section on coroutine memory consumption (#3225)
Updates the section "Coroutines are light-weight" to clarify its comparison of the resource-intensiveness of coroutines and threads. The content is much the same. This commit also makes the code sample in this section runnable and omits the surrounding runBlocking block.
1 parent b545807 commit f991742

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

docs/topics/coroutines-basics.md

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -245,14 +245,17 @@ Done
245245

246246
<!--- TEST -->
247247

248-
## Coroutines ARE light-weight
248+
## Coroutines are light-weight
249249

250-
Run the following code:
250+
Coroutines are less resource-intensive than JVM threads. Code that exhausts the
251+
JVM's available memory when using threads can be expressed using coroutines
252+
without hitting resource limits. For example, the following code launches
253+
100000 distinct coroutines that each wait 5 seconds and then print a period
254+
('.') while consuming very little memory:
251255

252256
```kotlin
253257
import kotlinx.coroutines.*
254258

255-
//sampleStart
256259
fun main() = runBlocking {
257260
repeat(100_000) { // launch a lot of coroutines
258261
launch {
@@ -261,19 +264,19 @@ fun main() = runBlocking {
261264
}
262265
}
263266
}
264-
//sampleEnd
265267
```
268+
<!-- While coroutines do have a smaller memory footprint than threads, this
269+
example will exhaust the playground's heap memory; don't make it runnable. -->
266270

267271
> You can get the full code [here](../../kotlinx-coroutines-core/jvm/test/guide/example-basic-06.kt).
268272
>
269273
{type="note"}
270274

271275
<!--- TEST lines.size == 1 && lines[0] == ".".repeat(100_000) -->
272276

273-
It launches 100K coroutines and, after 5 seconds, each coroutine prints a dot.
274-
275-
Now, try that with threads (remove `runBlocking`, replace `launch` with `thread`, and replace `delay` with `Thread.sleep`).
276-
What would happen? (Most likely your code will produce some sort of out-of-memory error)
277+
If you write the same program using threads (remove `runBlocking`, replace
278+
`launch` with `thread`, and replace `delay` with `Thread.sleep`), it will
279+
likely consume too much memory and throw an out-of-memory error.
277280

278281
<!--- MODULE kotlinx-coroutines-core -->
279282
<!--- INDEX kotlinx.coroutines -->

0 commit comments

Comments
 (0)