Kotlin - 迁移到 Kotlin 1.3 后,协程会导致 DefaultDispatcher 使用大量 CPU

标签 kotlin coroutine java.util.concurrent kotlin-coroutines

长期在高并发下使用 Kotlin 协程的实验版,性能一直很优秀。主要逻辑可以简化为以下代码:

// works fine in kotlin 1.2 with 3000+ QPS for a 40-core host
launch {
  // running in ForkJoinPool.commonPool() by default
  // non-blocking IO function
  val result = supendFunction()
  doSomething(result)
}

不过我把kotlin更新到1.3之后,迁移到正式版​​的coroutines之后,是这样的
// kotlin 1.3 version
GlobalScope.launch {
  // running in DefaultDispatcher
  // non-blocking IO function
  val result = supendFunction()
  doSomething(result)
}

CPU 使用率从 2% 上升到 50%,没有抛出任何异常或错误。我注意到的唯一区别是协程不再在 ForkJoinPool.commonPool() 中执行。就像之前一样。相反,它们运行在 DefaultDispatcher线程,例如 DefaultDispatcher-worker-30 .

我的问题是:
  • 为什么用 DefaultDispatcher 花费这么多 CPU 使用率?
  • 为什么 kotlin 1.3 使用 DefaultDispatcher代替 ForkJoinPool.commonPool()默认情况下?
  • 如何保持协程的行为就像 1.3 之前一样?
  • 最佳答案

    1. Why does it cost so much CPU usage with DefaultDispatcher?


    这是一个完全不同的实现,它针对多个性能目标进行了优化,例如通过 channel 进行通信。它受制于 future 的改进。

    1. Why does kotlin 1.3 use DefaultDispatcher in place of ForkJoinPool.commonPool() by default?


    其实它一直在使用Default调度员一直在,但Default的分辨率改变了。在实验阶段,它等于CommonPool但现在它更喜欢自定义实现。

    1. How to keep the behavior of coroutines just like before 1.3?


    设置 kotlinx.coroutines.scheduler系统属性到 off .

    关于Kotlin - 迁移到 Kotlin 1.3 后,协程会导致 DefaultDispatcher 使用大量 CPU,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53279409/

    相关文章:

    JDBC 结果上的 Java 并发

    kotlin - Uncaught TypeError : this. resultContinuation_0 在 Kotlin JS 浏览器 onclick 中尝试运行挂起函数时未定义

    android - 代码覆盖内联函数

    c++ - `co_yield` 能否在协程恢复时从调用方返回一个值?

    android - 为什么以及何时在使用 Kotlin 的 Android 中使用协程而不是线程,因为没有并行性?

    java - @GuardedBy , @ThreadSafe ,@NotThreadSafe

    java - Java 中的启动/暂停/恢复方法

    Android - Fragment 中的 GlSurfaceView 同时运行两次

    Kotlin JS - 访问 HTML DOM 属性

    android - Android协程相当于Executor服务是什么