Skip to content

Instantly share code, notes, and snippets.

@yhirano
Created January 4, 2021 23:43
Show Gist options
  • Select an option

  • Save yhirano/4e6628e77ea782f9a9401875f89debad to your computer and use it in GitHub Desktop.

Select an option

Save yhirano/4e6628e77ea782f9a9401875f89debad to your computer and use it in GitHub Desktop.
import android.os.SystemClock
import androidx.collection.LruCache
import java.util.*
/**
* @param expireTime Cache expire time(ms).
*/
class ExpiringLruCache<K: Any, V: Any>(maxSize: Int, private val expireTime: Long) {
private val cache: LruCache<K, V> = CustomLruCache(maxSize)
private val expirationTimes: MutableMap<K, Long> = HashMap<K, Long>(maxSize)
operator fun get(key: K): V? {
synchronized(this) {
val value = cache[key]
if (value != null && elapsedRealtime() >= getExpiryTime(key)) {
remove(key)
return null
} else {
return value
}
}
}
operator fun set(key: K, value: V): V? {
synchronized(this) {
val previousValue = cache.put(key, value)
expirationTimes[key] = elapsedRealtime() + expireTime
return previousValue
}
}
fun elapsedRealtime(): Long {
return SystemClock.elapsedRealtime()
}
fun getExpiryTime(key: K): Long {
return expirationTimes[key] ?: 0
}
fun removeExpiryTime(key: K) {
synchronized(this) {
expirationTimes.remove(key)
}
}
fun remove(key: K): V? {
synchronized(this) {
expirationTimes.remove(key)
return cache.remove(key)
}
}
fun snapshot(): Map<K, V> {
return cache.snapshot()
}
fun trimToSize(maxSize: Int) {
cache.trimToSize(maxSize)
}
fun createCount(): Int {
return cache.createCount()
}
fun evictAll() {
cache.evictAll()
}
fun evictionCount(): Int {
return cache.evictionCount()
}
fun hitCount(): Int {
return cache.hitCount()
}
fun maxSize(): Int {
return cache.maxSize()
}
fun missCount(): Int {
return cache.missCount()
}
fun putCount(): Int {
return cache.putCount()
}
fun size(): Int {
return cache.size()
}
private inner class CustomLruCache(maxSize: Int) : LruCache<K, V>(maxSize) {
override fun entryRemoved(evicted: Boolean, key: K, oldValue: V, newValue: V?) {
super.entryRemoved(evicted, key, oldValue, newValue)
removeExpiryTime(key)
}
override fun sizeOf(key: K, value: V): Int {
return 1
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment