LoginSignup
2
1

More than 3 years have passed since last update.

Kotlin 1.3のCoroutineのコンテキストとディスパッチャ⑥(デバッグのためのコルーチンの命名)

Posted at

検証環境

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

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

準備

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

Naming coroutines for debugging

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

今回のタイトルはわかりやすいです。
これまで、デバッグではスレッド名とIDが表示されることについて学習してきました。
多分、その部分の名前を変えられるのでしょう。

早速読み進めてみます。

Automatically assigned ids are good when coroutines log often and you just need to correlate log records coming from the same coroutine. However, when coroutine is tied to the processing of a specific request or doing some specific background task, it is better to name it explicitly for debugging purposes. CoroutineName context element serves the same function as a thread name. It'll get displayed in the thread name that is executing this coroutine when debugging mode is turned on.

訳します。

頻繁にログをとり、調査する際、自動で付加されるIDはとても便利です。しかし、コルーチンが特定のバックグラウンド処理や特定のプロセスに紐付いている場合は、名前を明示的に指定することをお勧めします。
CoroutineNameクラスのコンテキスト要素はスレッド名と同じ役割をもちます。CoroutineNameを指定するとデバッグモードでスレッド名を変更することができます。

なるほど、確かにこれまではmainとか寂しい感じですが、それが変更できるということですね。
サンプルコードがあるので見てみましょう。

import kotlinx.coroutines.*

fun log(msg: String) = println("[${Thread.currentThread().name}] $msg")

fun main() = runBlocking(CoroutineName("main")) {
    log("Started main coroutine")
    // run two background value computations
    val v1 = async(CoroutineName("v1coroutine")) {
        delay(500)
        log("Computing v1")
        252
    }
    val v2 = async(CoroutineName("v2coroutine")) {
        delay(1000)
        log("Computing v2")
        6
    }
    log("The answer for v1 / v2 = ${v1.await() / v2.await()}")
}

CoroutineNameクラスのコンストラクタにスレッド名を指定していますね。
では、実際に実行結果がどうなるかも確認しておきます。

[main @main#1] Started main coroutine
[main @v1coroutine#2] Computing v1
[main @v2coroutine#3] Computing v2
[main @main#1] The answer for v1 / v2 = 42

確かに、コンストラクタで指定した名前が表示されています。

まとめ

このブロックで理解できたことは以下のことだと思います。

  • CoroutineNameのコンストラクタにスレッド名を指定し、async関数の引数に渡すとスレッド名を変更できる
2
1
0

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
2
1