Skip to content

Noticeable upfront cost of Dispatchers.Default #4051

Closed
@semoro

Description

Describe the problem

Creation of the CoroutineScheduler requires initialization of kotlin.random.Random, which, in the case of kotlin-stdlib-jdk8 is used, requires dynamic class-loading of android.os.BUNDLE (see: https://youtrack.jetbrains.com/issue/KT-44089)

However, Dispatchers.Default is often used early in the application runtime when startup logic uses coroutines, and additional class-loading delays are unfortunate.
See github: "main" /Dispatchers.Default/ for examples.

Profiler result Screenshot 2024-02-23 at 23 26 13

Provide a Reproducer

// FILE: main.kt
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking


fun main() {
    val dispatcher = Dispatchers.Default
    runBlocking {
        delay(1000)
    }

    subCall(dispatcher)
}

suspend fun mainImpl() {
    println("done")
}
// FILE: other.kt
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.runBlocking

fun subCall(dispatcher: CoroutineDispatcher) {
    // This runBlocking is causing a long kotlin.Random.<clinit>
    runBlocking(dispatcher) {
        mainImpl()
    }
}
build.gradle.kts
// FILE: build.gradle.kts

plugins {
  kotlin("jvm") version "1.9.21"
}

group = "org.example"
version = "1.0-SNAPSHOT"

repositories {
  mavenCentral()
}

dependencies {
  implementation(kotlin("stdlib-jdk8"))
  testImplementation("org.jetbrains.kotlin:kotlin-test")

  // dependency on Kotlinx-coroutines
  implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.8.0")
}
kotlin {
  jvmToolchain(21)
}

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions