Skip to content

Commit

Permalink
Eagerly load CoroutineExceptionHandler and load corresponding service
Browse files Browse the repository at this point in the history
Partially addresses #2552
  • Loading branch information
qwwdfsad committed Sep 27, 2021
1 parent e4bee74 commit 906eae1
Show file tree
Hide file tree
Showing 5 changed files with 26 additions and 2 deletions.
@@ -1,13 +1,19 @@
/*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/

package kotlinx.coroutines

import kotlin.coroutines.*
import kotlin.jvm.*

internal expect fun handleCoroutineExceptionImpl(context: CoroutineContext, exception: Throwable)

/**
* JVM kludge: trigger loading of all the classes and service loading
* **before** any exception occur because it may be OOM, SOE or VerifyError
*/
internal expect fun initializeDefaultExceptionHandlers()

/**
* Helper function for coroutine builder implementations to handle uncaught and unexpected exceptions in coroutines,
* that could not be otherwise handled in a normal way through structured concurrency, saving them to a future, and
Expand Down
6 changes: 5 additions & 1 deletion kotlinx-coroutines-core/common/src/Job.kt
Expand Up @@ -113,7 +113,11 @@ public interface Job : CoroutineContext.Element {
/**
* Key for [Job] instance in the coroutine context.
*/
public companion object Key : CoroutineContext.Key<Job>
public companion object Key : CoroutineContext.Key<Job> {
init {
initializeDefaultExceptionHandlers()
}
}

// ------------ state query ------------

Expand Down
Expand Up @@ -6,6 +6,10 @@ package kotlinx.coroutines

import kotlin.coroutines.*

internal actual fun initializeDefaultExceptionHandlers() {
// Do nothing
}

internal actual fun handleCoroutineExceptionImpl(context: CoroutineContext, exception: Throwable) {
// log exception
console.error(exception)
Expand Down
Expand Up @@ -22,6 +22,12 @@ private val handlers: List<CoroutineExceptionHandler> = ServiceLoader.load(
CoroutineExceptionHandler::class.java.classLoader
).iterator().asSequence().toList()

internal actual fun initializeDefaultExceptionHandlers() {
// Load CEH and handlers
CoroutineExceptionHandler
}


internal actual fun handleCoroutineExceptionImpl(context: CoroutineContext, exception: Throwable) {
// use additional extension handlers
for (handler in handlers) {
Expand Down
Expand Up @@ -6,6 +6,10 @@ package kotlinx.coroutines

import kotlin.coroutines.*

internal actual fun initializeDefaultExceptionHandlers() {
// Do nothing
}

internal actual fun handleCoroutineExceptionImpl(context: CoroutineContext, exception: Throwable) {
// log exception
exception.printStackTrace()
Expand Down

0 comments on commit 906eae1

Please sign in to comment.