一個(gè)通用的LRU

/**
 * LRU緩存實(shí)現(xiàn)類。基于 LinkedHashMap 實(shí)現(xiàn)。
 *
 * @param <K> 鍵的類型
 * @param <V> 值的類型
 */
public class LRUCache<K, V> {
    // 緩存存儲(chǔ)結(jié)構(gòu),使用 LinkedHashMap 來(lái)保證訪問(wèn)順序性
    protected final LinkedHashMap<K, V> cache;
    // 緩存的入口集合,用于遍歷和移除操作
    protected final Set<Map.Entry<K, V>> cacheEntrySet;

    /**
     * 構(gòu)造函數(shù),初始化緩存。
     */
    public LRUCache() {
        cache = new LinkedHashMap<>(16, .75f, true); // 初始化 LinkedHashMap,容量為16,加載因子為0.75,訪問(wèn)順序
        cacheEntrySet = cache.entrySet(); // 獲取緩存的入口集合
    }

    /**
     * 觸發(fā)鍵的訪問(wèn),將對(duì)應(yīng)的緩存項(xiàng)移到鏈表尾部,表示最近訪問(wèn)。
     *
     * @param key 被訪問(wèn)的鍵
     * @return 如果緩存中存在該鍵,則返回 true;否則返回 false。
     */
    public synchronized boolean touch(K key) {
        return cache.get(key) != null;
    }

    /**
     * 將鍵值對(duì)放入緩存,如果鍵已存在,則更新值并觸發(fā)訪問(wèn)。
     *
     * @param key 鍵
     * @param value 值
     */
    public synchronized void put(K key, V value) {
        if (cache.put(key, value) != null) { // 如果鍵已存在,更新值并觸發(fā)訪問(wèn)
            touch(key);
        }
    }

    /**
     * 獲取緩存的值。
     *
     * @param key 鍵
     * @return 對(duì)應(yīng)的值,如果不存在,則返回 null。
     */
    public synchronized V get(K key) {
        return cache.get(key);
    }

    /**
     * 移除并返回緩存中最老的鍵值對(duì)。
     *
     * @return 最老的鍵值對(duì),如果緩存為空,則返回 null。
     */
    public synchronized Map.Entry<K, V> pop() {
        Iterator<Map.Entry<K, V>> it = cacheEntrySet.iterator();
        if (!it.hasNext()) { // 如果緩存為空,直接返回 null
            return null;
        }
        Map.Entry<K, V> entry = it.next();
        if (entry == null) { // 安全檢查
            return null;
        }
        it.remove(); // 移除最老的鍵值對(duì)
        return entry;
    }

    /**
     * 從緩存中移除指定鍵的鍵值對(duì)。
     *
     * @param key 要移除的鍵
     * @return 如果成功移除,則返回 true;否則返回 false。
     */
    public synchronized boolean remove(K key) {
        return cache.remove(key) != null;
    }

    /**
     * 獲取緩存中鍵值對(duì)的數(shù)量。
     *
     * @return 緩存大小
     */
    public synchronized int size() {
        return cache.size();
    }

    /**
     * 檢查緩存是否包含指定鍵。
     *
     * @param key 要檢查的鍵
     * @return 如果緩存包含該鍵,則返回 true;否則返回 false。
     */
    public synchronized boolean containsKey(K key) {
        return cache.containsKey(key);
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容