sksamuel / aedile

Kotlin Wrapper for Caffeine
Apache License 2.0
170 stars 15 forks source link

Exceptions crash the caller thread #19

Closed trietsch closed 1 year ago

trietsch commented 1 year ago

After looking at #1, I thought that the exception handling was now done properly by using a SupervisorJob, however, the following leads to a crashed main thread:

import com.sksamuel.aedile.core.caffeineBuilder
import org.slf4j.LoggerFactory
import kotlin.random.Random

suspend fun main() {
    val log = LoggerFactory.getLogger("test")

    val cache = caffeineBuilder<String, String>().build()

    repeat(10) {
        log.info(cache.get(it.toString()) {
            if (Random.nextBoolean()) {
                throw Exception("test")
            }
            "value"
        })
    }
}

Which results in:

11:06:38.853 [main] INFO  test - value 
Exception in thread "main" java.lang.Exception: test
    at dev.trietsch.ApplicationKt$main$2$1.invokeSuspend(Application.kt:58)
    at dev.trietsch.ApplicationKt$main$2$1.invoke(Application.kt)
    at dev.trietsch.ApplicationKt$main$2$1.invoke(Application.kt)
    at com.sksamuel.aedile.core.Cache$get$2$1.invokeSuspend(Cache.kt:43)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:108)
    at kotlinx.coroutines.internal.LimitedDispatcher$Worker.run(LimitedDispatcher.kt:115)
    at kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:103)
    at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:584)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:793)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:697)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:684)
Aug 23, 2023 11:06:38 AM com.github.benmanes.caffeine.cache.LocalAsyncCache lambda$handleCompletion$7
WARNING: Exception thrown during asynchronous load
java.lang.Exception: test

Am I using the cache wrapper in the wrong way?

trietsch commented 1 year ago

Okay.... Seems I need to dive more into coroutines 🙃 SupervisorJob only takes care of not stopping the other coroutines in the same scope. You still are required to do exception handling, both in an async loader function and in a regular cache with a compute lambda. Closing! :)