Skip to content

Commit

Permalink
Fixed a bug related to the coroutine job (#13)
Browse files Browse the repository at this point in the history
  • Loading branch information
be-hase authored Jul 19, 2024
1 parent 51a4300 commit c4fb7c9
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ package dev.hsbrysk.caffeine.internal
import com.github.benmanes.caffeine.cache.AsyncCache
import com.github.benmanes.caffeine.cache.Cache
import dev.hsbrysk.caffeine.CoroutineCache
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.future.await
import kotlinx.coroutines.future.future
import java.util.concurrent.CompletableFuture
Expand All @@ -15,17 +14,15 @@ internal class CoroutineCacheImpl<K : Any, V : Any>(private val cache: AsyncCach
override suspend fun get(
key: K,
mappingFunction: suspend (K) -> V?,
): V? {
val ctx = currentCoroutineContext()
return cache.get(key) { k, _ -> CoroutineScope(ctx).future { mappingFunction(k) } }.await()
): V? = coroutineScope {
cache.get(key) { k, _ -> future { mappingFunction(k) } }.await()
}

override suspend fun getAll(
keys: Iterable<K>,
mappingFunction: suspend (Iterable<K>) -> Map<K, V>,
): Map<K, V> {
val ctx = currentCoroutineContext()
return cache.getAll(keys) { k, _ -> CoroutineScope(ctx).future { mappingFunction(k) } }.await()
): Map<K, V> = coroutineScope {
cache.getAll(keys) { k, _ -> future { mappingFunction(k) } }.await()
}

override fun put(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -242,5 +242,37 @@ class CoroutineCacheImplTest {
assertThat(result1.await()).isEqualTo("value-1")
}
}

@Test
fun `get - check exception and cancel behavior`() {
val scope = CoroutineScope(EmptyCoroutineContext)
val job = scope.async {
try {
target.get("1", exceptionFunction)
} catch (expected: IllegalArgumentException) {
println(expected)
}
"Result"
}
val result = runBlocking { job.await() }
assertThat(result).isEqualTo("Result")
}

@Test
fun `getAll - check exception and cancel behavior`() {
val scope = CoroutineScope(EmptyCoroutineContext)
val job = scope.async {
try {
target.getAll(listOf("1", "2")) {
throw IllegalArgumentException()
}
} catch (expected: IllegalArgumentException) {
println(expected)
}
"Result"
}
val result = runBlocking { job.await() }
assertThat(result).isEqualTo("Result")
}
}
}

0 comments on commit c4fb7c9

Please sign in to comment.