Skip to content

Commit

Permalink
Make dispatcherToBlockOn dispatcher based on daemon threads. (#814)
Browse files Browse the repository at this point in the history
After #798, we changed Dispatcher.IO to custom dispatcher.

Dispatcher.IO is based on daemon threads (thread that receives InterruptException on application exit).

Our new dispatcher isn't. The proof:
```
import java.util.concurrent.Executors
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.runBlocking

fun main() {
    runBlocking(Dispatchers.IO) {
        println(Thread.currentThread().isDaemon) // prints true
    }
    runBlocking(Executors.newCachedThreadPool().asCoroutineDispatcher()) {
        println(Thread.currentThread().isDaemon) // prints false
    }
    val defaultFactory = Executors.defaultThreadFactory()
    runBlocking(Executors.newCachedThreadPool {
        defaultFactory.newThread(it).apply {
            isDaemon = true
        }
    }.asCoroutineDispatcher()) {
        println(Thread.currentThread().isDaemon) // prints true
    }
}
```

This PR makes threads daemon.

Reported in [Kotlin Slack](https://kotlinlang.slack.com/archives/C01D6HTPATV/p1697400320739369) - applications exits too long.
  • Loading branch information
igordmn authored Oct 20, 2023
1 parent 91c3db8 commit 1cbde7b
Showing 1 changed file with 6 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,16 @@ package org.jetbrains.skiko.redrawer
import kotlinx.coroutines.asCoroutineDispatcher
import java.util.concurrent.Executors

private val defaultFactory = Executors.defaultThreadFactory()

/**
* Dispatcher intended for use in coroutines that blocks (not suspends) for indefinite amount of time.
* Now we use it e.g. for waiting for VSYNC.
* We can't use `Dispatchers.IO` here because it's limited by 64 threads and under heavy IO workload all of them might be occupied
* which leads to skipped frames
*/
internal val dispatcherToBlockOn = Executors.newCachedThreadPool().asCoroutineDispatcher()
internal val dispatcherToBlockOn = Executors.newCachedThreadPool {
defaultFactory.newThread(it).apply {
isDaemon = true
}
}.asCoroutineDispatcher()

0 comments on commit 1cbde7b

Please sign in to comment.