From f9917429de77cd6a55285bd711db62fc1f6a4f8b Mon Sep 17 00:00:00 2001 From: Scott Olsen Date: Thu, 31 Mar 2022 04:59:08 -0400 Subject: [PATCH] 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. --- docs/topics/coroutines-basics.md | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/docs/topics/coroutines-basics.md b/docs/topics/coroutines-basics.md index 885c29fc28..68ae97886f 100644 --- a/docs/topics/coroutines-basics.md +++ b/docs/topics/coroutines-basics.md @@ -245,14 +245,17 @@ Done -## 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 { @@ -261,8 +264,9 @@ fun main() = runBlocking { } } } -//sampleEnd ``` + > You can get the full code [here](../../kotlinx-coroutines-core/jvm/test/guide/example-basic-06.kt). > @@ -270,10 +274,9 @@ fun main() = runBlocking { -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.