Skip to content

A simple extension that adds Kotlin Coroutines support to caffeine

License

Notifications You must be signed in to change notification settings

be-hase/caffeine-coroutines

Folders and files

NameName
Last commit message
Last commit date
Feb 17, 2025
Feb 26, 2025
Feb 12, 2025
May 18, 2024
Mar 20, 2025
Jun 26, 2024
May 18, 2024
Jan 29, 2025
May 17, 2024
Jun 10, 2024
Dec 23, 2024
May 18, 2024
Feb 25, 2025
Jul 11, 2024
May 18, 2024
May 18, 2024

Repository files navigation

caffeine-coroutines

Maven Central Version

Motivation

There is a caching library called Caffeine, which is used as a de facto standard in Java.

I will make this library usable with Kotlin Coroutines.

Install

Gradle

implementation("dev.hsbrysk:caffeine-coroutines:{{version}}")

Maven

<dependency>
    <groupId>dev.hsbrysk</groupId>
    <artifactId>caffeine-coroutines</artifactId>
    <version>{{version}}</version>
</dependency>

How to use

There is almost no difference from Caffeine. The only thing you need to know is that by using buildCoroutine, you can obtain a coroutine-compatible Cache instance.

suspend fun main() {
    val cache: CoroutineCache<String, String> = Caffeine.newBuilder()
        .maximumSize(10_000)
        .expireAfterWrite(Duration.ofMinutes(5))
        .buildCoroutine() // Use buildCoroutine

    val value = cache.get("key") {
        delay(1000) // You can use suspend functions.
        "value"
    }
    println(value)
}

Of course, it also supports the Loading Cache style.

suspend fun main() {
    val cache: CoroutineLoadingCache<String, String> = Caffeine.newBuilder()
        .maximumSize(10_000)
        .expireAfterWrite(Duration.ofMinutes(5))
        .buildCoroutine { // Use buildCoroutine
            delay(1000) // You can use suspend functions.
            "value"
        }

    val value = cache.get("key")
    println(value)
}

Philosophy

We will primarily focus on coroutine support

We respect the widely used Caffeine API.

Introducing our own API would confuse users. It would also make adoption more difficult and would be troublesome when discontinuing it after adoption.

Contributing

If there are any issues, please feel free to send a pull request.