Thursday, March 23, 2017

LRU Cache

A simple Least Recently Used Cache implementation in Java, with thanks to Chris Wu for the idea.

package demo;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Thanks to http://chriswu.me/blog/a-lru-cache-in-10-lines-of-java/
 *
 * @author Marcel Dullaart
 */
class LRUCache extends LinkedHashMap {

    private Integer sizeLimit;

    LRUCache(Integer size) {
        super(16, 0.75f, true);
        this.sizeLimit = size;
    }

    /**
     * Removes the eldest entry if the {@link #size()} exceeds the {@link #sizeLimit}
     *
     * @param entry the eldest entry
     * @return always false
     */
    @Override
    protected boolean removeEldestEntry(Map.Entry entry) {
        if (size() > sizeLimit) {
            remove(entry.getKey());
        }
        return false;
    }
}

No comments: