Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: clarify section on coroutine memory consumption #3225

Merged
merged 2 commits into from Mar 31, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 11 additions & 8 deletions docs/topics/coroutines-basics.md
Expand Up @@ -245,14 +245,17 @@ Done

<!--- TEST -->

## Coroutines ARE light-weight
## Coroutines are light-weight

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

```kotlin
import kotlinx.coroutines.*

//sampleStart
fun main() = runBlocking {
repeat(100_000) { // launch a lot of coroutines
launch {
Expand All @@ -261,19 +264,19 @@ fun main() = runBlocking {
}
}
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Given that the code is not runnable, I think a better choice would be to remove //sampleStart and //sampleEnd, given how they aren't recognized for code that is not runnable: https://kotlinlang.org/docs/coroutines-basics.html#coroutines-are-light-weight

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, thanks!

//sampleEnd
```
<!-- While coroutines do have a smaller memory footprint than threads, this
example will exhaust the playground's heap memory; don't make it runnable. -->

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

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

It launches 100K coroutines and, after 5 seconds, each coroutine prints a dot.

Now, try that with threads (remove `runBlocking`, replace `launch` with `thread`, and replace `delay` with `Thread.sleep`).
What would happen? (Most likely your code will produce some sort of out-of-memory error)
If you write the same program using threads (remove `runBlocking`, replace
`launch` with `thread`, and replace `delay` with `Thread.sleep`), it will
likely consume too much memory and throw an out-of-memory error.

<!--- MODULE kotlinx-coroutines-core -->
<!--- INDEX kotlinx.coroutines -->
Expand Down