LoginSignup
3
1

More than 3 years have passed since last update.

Kotlin 1.3のCoroutineの使い方⑦(コルーチンは軽量!)

Last updated at Posted at 2019-01-28

検証環境

この記事の内容は、以下の環境で検証しました。

  • Intellij IDEA ULTIMATE 2018.2
  • Kotlin 1.3.0
  • Gradle Projectで作成
  • GradleファイルはKotlinで記述(KotlinでDSL)

準備

詳細は下記の準備を参照してください。
https://qiita.com/naoi/items/8abf2cddfc2cb3802daa

Coroutines ARE light-weight

前回に引き続き、公式サイトを読み解いていきます。

今回のタイトルはわかりやすいです!
軽量アピールです。

早速読み進めます。

Run the following code:

いきなり、サンプルコードを実行せよと言われたので、実行してみたいと思います。
まず、サンプルコードは以下のとおりです。

import kotlinx.coroutines.*

fun main() = runBlocking {
    repeat(100_000) { // launch a lot of coroutines
        launch {
            delay(1000L)
            print(".")
        }
    }
}

実行したら大変な事になりました。
「.」ドットが大量に表示されました。

説明を読んでみましょう。

It launches 100K coroutines and, after a second, each coroutine prints a dot. Now, try that with threads. What would happen? (Most likely your code will produce some sort of out-of-memory error)

意訳込みですが

10万のコルーチンを起動しました、1秒後にそれぞれのコルーチンがドットを出力します。
早速ためしてみてください。何が起こりました?(多くの場合、ある種、OOMのような感じになりまるよね。)

要は、軽いよって言いたいんですね。確かにスレッドを10万も生成したらOOMになりますね。

まとめ

このブロックは、ひたすら軽量アピールでした。

3
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1