package com.anthony.util;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
/**
* 线程同步的LRUCache
* Created by luxuebing on 2019/4/30
*/
public class SynchronizedLRUCache<K, V> {
private final int CACHE_SIZE;
private final float DEFAULT_LOAD_FACTOR = 0.75f;
private final LinkedHashMap<K, V> map;
public SynchronizedLRUCache(int cacheSize) {
CACHE_SIZE = cacheSize;
int capacity = (int) Math.ceil(CACHE_SIZE / DEFAULT_LOAD_FACTOR) + 1;
map = new LinkedHashMap(capacity, DEFAULT_LOAD_FACTOR, true) {
@Override
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > CACHE_SIZE;
}
};
}
public synchronized void put(K key, V value) {
map.put(key, value);
}
public synchronized V get(K key) {
return map.get(key);
}
public synchronized void remove(K key) {
map.remove(key);
}
public synchronized int size() {
return map.size();
}
public synchronized void clear() {
map.clear();
}
public synchronized Set<Map.Entry<K, V>> entrySet() {
return map.entrySet();
}
public synchronized boolean containsKey(K key) {
return map.containsKey(key);
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer("[");
map.forEach((k, v) -> sb.append(k).append("=").append(v).append(","));
sb.delete(sb.length() - 1, sb.length()).append("]");
return sb.toString();
}
public static void main(String[] args) {
SynchronizedLRUCache<Object, Object> cache = new SynchronizedLRUCache<>(4);
System.out.println(cache);
}
}
Console:
[2=2,3=3,4=4,5=5]
Process finished with exit code 0