LRUCache (least recently used)

发布时间 2023-08-25 16:39:09作者: zno2

 

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * Caching with the LRU (Least Recently Used) algorithm.
 * 
 */
public class LRUCache {

    private Map<Object, Object> cache = new HashMap<Object, Object>();

    private LinkedList<Object> keyList = new LinkedList<Object>();

    private int maxSize;

    public LRUCache(int maxSize) {
        if (maxSize < 1) {
            throw new IllegalArgumentException("LRUCache max size must be greater than 0");
        }
        this.maxSize = maxSize;
    }

    public synchronized void put(Object key, Object value) {
        if (key == null) {
            return;
        }
        keyList.remove(key);
        keyList.addFirst(key);
        cache.put(key, value);

        if (cache.size() > maxSize) {
            Object lastKey = keyList.getLast();
            this.remove(lastKey);
        }
    }

    public synchronized Object get(Object key) {
        if (key == null) {
            return null;
        }
        Object value = cache.get(key);
        if (value == null) {
            return null;
        }

        keyList.remove(key);
        keyList.addFirst(key);
        return value;
    }

    public synchronized Object remove(Object key) {
        if (key == null) {
            return null;
        }
        Object value = cache.remove(key);
        if (value == null) {
            return null;
        }
        keyList.remove(key);
        return value;
    }

    public synchronized void clear() {
        cache.clear();
        keyList.clear();
    }
}

 

备注

https://stackoverflow.com/questions/322715/when-to-use-linkedlist-over-arraylist

什么时候用LinkedList 

什么时候用ArrayList

什么时候用HashMap

什么时候用LinkedHashMap