aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/at/hannibal2/skyhanni/utils/TimeLimitedCache.kt
blob: 9f29b9ff161e64b414380d7b728fe723dd9425bd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package at.hannibal2.skyhanni.utils

import com.google.common.cache.CacheBuilder
import java.util.concurrent.TimeUnit
import kotlin.time.Duration

class TimeLimitedCache<K, V>(expireAfterWrite: Duration) {

    private val cache = CacheBuilder.newBuilder()
        .expireAfterWrite(expireAfterWrite.inWholeMilliseconds, TimeUnit.MILLISECONDS).build<K, V>()

    fun put(key: K, value: V) = cache.put(key, value)

    fun getOrNull(key: K): V? = cache.getIfPresent(key)

    fun clear() = cache.invalidateAll()

    fun values(): MutableCollection<V> = cache.asMap().values

    fun keys(): MutableSet<K> = cache.asMap().keys

    fun containsKey(key: K): Boolean = cache.getIfPresent(key) != null
}