All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.provenance.caching.Caching.kt Maven / Gradle / Ivy

The newest version!
package io.provenance.caching

import java.time.OffsetDateTime
import java.time.temporal.ChronoUnit
import java.util.concurrent.atomic.AtomicReference
import kotlin.time.Duration

fun  cached(ttl: Duration, block: () -> T): Cached {
    return object : BaseCachedAsync(ttl) {
        override fun fetch(): T = block()
    }
}

interface Cached {
    fun fetch(): T
    fun get(): T
}

abstract class BaseCachedAsync(private val ttl: Duration) : Cached {
    private val lastFetch = AtomicReference(OffsetDateTime.MIN)
    private val cachedValue = AtomicReference()

    override fun get(): T {
        if (OffsetDateTime.now().isAfter(lastFetch.get().plus(ttl.inWholeMilliseconds, ChronoUnit.MILLIS))) {
            cachedValue.set(fetch())
            lastFetch.set(OffsetDateTime.now())
        }
        return cachedValue.get()
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy