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

util.LRUCache.kt Maven / Gradle / Ivy

package com.amplitude.experiment.util

import java.util.HashMap

internal class LRUCache(private val capacity: Int) {

    private class Node(
        var key: K? = null,
        var value: V? = null,
        var prev: Node? = null,
        var next: Node? = null,
    )

    private var count = 0
    private val map: MutableMap?> = HashMap()
    private val head: Node = Node()
    private val tail: Node = Node()
    private val lock = Any()

    init {
        head.next = tail
        tail.prev = head
    }

    operator fun get(key: K): V? = synchronized(lock) {
        val n = map[key] ?: return null
        update(n)
        return n.value
    }

    operator fun set(key: K, value: V) = synchronized(lock) {
        var n = map[key]
        if (n == null) {
            n = Node(key, value)
            map[key] = n
            add(n)
            ++count
        } else {
            n.value = value
            update(n)
        }
        if (count > capacity) {
            val toDel = tail.prev
            remove(toDel!!)
            map.remove(toDel.key)
            --count
        }
    }

    private fun update(node: Node) {
        remove(node)
        add(node)
    }

    private fun add(node: Node) {
        val after = head.next
        head.next = node
        node.prev = head
        node.next = after
        after!!.prev = node
    }

    private fun remove(node: Node) {
        val before = node.prev
        val after = node.next
        before!!.next = after
        after!!.prev = before
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy