Skip to content

Commit

Permalink
Do not load a CoroutineExceptionHandler SL eagerly on Android as it c…
Browse files Browse the repository at this point in the history
…auses verification of the whole JAR/dex (-> file I/O) and ANR

Fixes #3180
  • Loading branch information
qwwdfsad committed Feb 15, 2022
1 parent 70d0ec7 commit f2a41d4
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions kotlinx-coroutines-core/jvm/src/CoroutineExceptionHandlerImpl.kt
Expand Up @@ -4,6 +4,7 @@

package kotlinx.coroutines

import kotlinx.coroutines.internal.*
import java.util.*
import kotlin.coroutines.*

Expand All @@ -17,14 +18,29 @@ import kotlin.coroutines.*
* We are explicitly using the `ServiceLoader.load(MyClass::class.java, MyClass::class.java.classLoader).iterator()`
* form of the ServiceLoader call to enable R8 optimization when compiled on Android.
*/
private val handlers: List<CoroutineExceptionHandler> = ServiceLoader.load(
private val handlers: List<CoroutineExceptionHandler> by lazy {
ServiceLoader.load(
CoroutineExceptionHandler::class.java,
CoroutineExceptionHandler::class.java.classLoader
).iterator().asSequence().toList()
).iterator().asSequence().toList()
}

internal actual fun initializeDefaultExceptionHandlers() {
/**
* For Android, we do not want to allow arbitrary disks read (service loader JAR scanning)
* as it causes ANR, so we are postponing service loading until the actual exception (crash in case of Android).
* For other applications it's not the issue to read the JAR, but it is the issue
* to read from disk/call service loader when e.g. OOM was thrown, as exception reporting will also throw,
* so we are initializing it eagerly.
*
* Alternatively, we can use our own FastServiceLoader (as for Dispatchers.Main) here as it gives x20 speedup, see
* https://github.com/Kotlin/kotlinx.coroutines/issues/878#issuecomment-445815632
* but it doesn't seem worth the trouble.
*/
if (ANDROID_DETECTED) return
// Load CEH and handlers
CoroutineExceptionHandler
handlers
}

/**
Expand Down

0 comments on commit f2a41d4

Please sign in to comment.