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

me.xethh.libs.toolkits.cache.LRUCache Maven / Gradle / Ivy

The newest version!
package me.xethh.libs.toolkits.cache;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Function;

public abstract class LRUCache implements Cache {
    private LRUMap map;

    public static  LRUCache of(int maxCache, Function transform){
        return new LRUCache(maxCache) {
            @Override
            public Function getValueProvider() {
                return transform;
            }

        };
    }
    public static  LRUCache of(LRUCache cache){
        return cache;
    }
    public LRUCache(int maxCache) {
        map = new LRUMap(maxCache);
    }

    @Override
    public V getInternal(K key) {
        return map.get(key);
    }

    @Override
    public void cacheInternal(K key, V value) {
        map.put(key,value);
    }

    @Override
    public int size() {
        return map.size();
    }

    public LRUMap map() {
        return map;
    }

    public static class LRUMap extends LinkedHashMap {
        private final int maxEntries;
        public static final int DEFAULT_INITIAL_CAPACITY = 16;
        public static final float DEFAULT_LOAD_FACTOR = 0.75f;

        public LRUMap(int initialCapacity,
                        float loadFactor,
                        int maxEntries) {
            super(initialCapacity, loadFactor, true);
            this.maxEntries = maxEntries;
        }

        public LRUMap(int initialCapacity,
                        int maxEntries) {
            this(Math.min(initialCapacity,maxEntries), DEFAULT_LOAD_FACTOR, maxEntries);
        }

        public LRUMap(int maxEntries) {
            this(Math.min(DEFAULT_INITIAL_CAPACITY,maxEntries), maxEntries);
        }

        // not very useful constructor
        public LRUMap(Map m,
                        int maxEntries) {
            this(m.size(), maxEntries);
            putAll(m);
        }

        protected boolean removeEldestEntry(Map.Entry eldest) {
            return size() > maxEntries;
        }

        public int getMaxEntries() {
            return maxEntries;
        }
    }

    @Override
    public String toString() {
        return "LRUCache{" +
                "map=" + map +
                '}';
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy