Skip to content

Instantly share code, notes, and snippets.

@longforus
Last active October 8, 2021 05:46
Show Gist options
  • Save longforus/ed0a2202f79bff891adef67dedb8eaa0 to your computer and use it in GitHub Desktop.
Save longforus/ed0a2202f79bff891adef67dedb8eaa0 to your computer and use it in GitHub Desktop.
[Simple LruCache] Simple LruCache #lru #kotlin
import java.util.*
import kotlin.concurrent.thread
/**
* @describe 最近最少使用队列, 只能使用這里override的api哦
* @author XQ Yang
* @date 4/3/2019 3:09 PM
*/
class LRURequestTimeQueue<T>(val maxSize: Int, private val realQueue: LinkedList<T> = LinkedList()):Deque<T> by realQueue {
val map = linkedMapOf<T,Long>()
/**
* 移除队尾元素
*/
override fun removeLast(): T {
val last = realQueue.removeLast()
if (last != null) {
map.remove(last)
}
return last
}
/**
* 如果存在则放到队头,更新访问时间,否则插入,如果队满,则删除队尾元素
*/
override fun addFirst(e: T) {
if (contains(e)) {
map[e] = System.currentTimeMillis()
return
}
if (map.size + 1 > maxSize) {
removeLast()
}
realQueue.addFirst(e)
map[e] = System.currentTimeMillis()
}
/**
* 如果包含则放到队头
*/
override fun contains(element: T): Boolean {
val contains = realQueue.contains(element)
if (contains) {
realQueue.remove(element)
realQueue.addFirst(element)
}
return contains
}
/**
* 获取e对应的时间值,如果e不存在则会插入.如果存在则放到队头,更新访问时间
*/
fun getAndUpdate(e: T): Long {
if (contains(e)) {
val old = map[e] ?: 0L
map[e] = System.currentTimeMillis()
return old
} else {
addFirst(e)
}
return 0L
}
/**
* 查看效果
*/
fun print(){
forEach {
println("key=${it.toString()} value = ${map[it]}")
}
}
}
fun main() {
val queue = LRURequestTimeQueue<String>(20)
val list = mutableListOf<String>()
for (i in 0..50) {
list.add("test ${i}")
}
thread {
for (i in 0..30) {
Thread.sleep(kotlin.random.Random.nextLong(10))
queue.getAndUpdate(list[kotlin.random.Random.nextInt(49)])
}
queue.print()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment