0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Kotlin Coroutine] Dispatcherの使い分け

Posted at

はじめに

Kotlin Coroutines には、用途ごとにいくつかの Dispatcher が用意されています。
Coroutines を効果的に活用するには、処理の性質に応じて適切な Dispatcher を選択することが重要です。

本記事では、以下の記事の続編として、各 Dispatcher の特徴と、どのような場面で利用すべきかを整理します。

Dispatchers 比較表

Dispatcher 主な用途 スレッド数 Blocking 処理 利用シーン 注意点
Dispatchers.Default CPU バウンド処理 CPU コア数基準 ❌ 不向き 計算処理、データ変換 I/O 待ちで使うと性能低下
Dispatchers.IO Blocking I/O 多め(上限あり) ⭕ 想定用途 JDBC、ファイル I/O Non-Blocking API では非推奨
Dispatchers.Main UI 更新 1(UI スレッド) ❌ 不可 Android / Desktop UI サーバーでは使わない
Dispatchers.Unconfined 特殊用途 状況依存 ⚠️ 注意 テスト・検証 実務では基本非推奨

Dispatchers.Default

Dispatchers.DefaultCPU バウンドな処理向け の Dispatcher です。

  • CPU コア数を基準にしたスレッドプール
  • 計算量の多い処理に適している
withContext(Dispatchers.Default) {
    heavyCalculation()
}

向いている処理

  • 暗号化・ハッシュ計算
  • JSON のパース・マッピング
  • 大量データの加工

注意点

I/O 待ちが発生する処理を実行すると、CPU 用スレッドが無駄に塞がれ、全体の性能低下につながります。

Dispatchers.IO

Dispatchers.IOBlocking API を安全に隔離するための Dispatcher です。

withContext(Dispatchers.IO) {
    jdbcRepository.findAll()
}

向いている処理

  • JDBC を利用した DB アクセス
  • ファイルの読み書き
  • Blocking な外部 API 呼び出し

重要な注意(R2DBC との関係)

R2DBC や WebClient などの Non-Blocking API を利用する場合、
Dispatchers.IO への切り替えは基本的に不要で、むしろ非推奨です。

// ❌ 不要な Dispatcher 切り替え
withContext(Dispatchers.IO) {
    r2dbcRepository.findAll()
}

Non-Blocking API は I/O 待ち中にスレッドを占有しないため、切り替えることでメリットを失ってしまいます。

Dispatchers.Main

Dispatchers.MainUI スレッド専用の Dispatcher です。

withContext(Dispatchers.Main) {
    updateUI()
}

利用環境

  • Android
  • Desktop Compose
  • JavaFX

サーバーサイドでは?

Spring Boot や WebFlux などのサーバーサイドでは
UI スレッドが存在しないため、通常は使用しません。

Dispatchers.Unconfined

Dispatchers.Unconfined実行スレッドを保証しない Dispatcher です。

launch(Dispatchers.Unconfined) {
    // 実行スレッドは予測しづらい
}

特徴

  • Coroutine 開始時は呼び出し元スレッドで実行される
  • suspend 以降の再開スレッドは保証されない

Dispatchers.Unconfined は、Coroutine を開始時は呼び出し元スレッドで実行しますが、
suspend 以降の再開スレッドは保証されません。
親 Coroutine の Dispatcher を維持するわけではないため、利用時は注意がに注意が必要です。

終わりに

Dispatcher は Coroutine の実行モデルを左右する重要な要素です。
処理が CPU バウンドか、I/O バウンドか、
また Blocking か Non-Blocking かを意識して選択することで、Coroutine のメリットを正しく活かすことができます。

本記事で Dispatcher に対する理解が深まれば幸いです。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?