Skip to content

Instantly share code, notes, and snippets.

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

  • Save yhirano/3cad99716ef7212f3f13ef6c313993ec to your computer and use it in GitHub Desktop.

Select an option

Save yhirano/3cad99716ef7212f3f13ef6c313993ec to your computer and use it in GitHub Desktop.
import android.os.SystemClock
/**
* @param expireTime Cache expire time(ms).
*/
class ExpiringCache<V: Any>(private val expireTime: Long) {
private var cache: V? = null
private var expirationTime: Long = 0
fun get(): V? {
synchronized(this) {
val value = cache
if (value != null && elapsedRealtime() >= expirationTime) {
remove()
return null
} else {
return value
}
}
}
fun set(value: V): V? {
synchronized(this) {
val previousValue = cache
cache = value
expirationTime = elapsedRealtime() + expireTime
return previousValue
}
}
fun elapsedRealtime(): Long {
return SystemClock.elapsedRealtime()
}
fun getExpiryTime(): Long {
return expirationTime
}
fun removeExpiryTime() {
expirationTime = 0
}
fun remove(): V? {
synchronized(this) {
val previousValue = cache
cache = null
expirationTime = 0
return previousValue
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment