package niewei.test4;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Collection;
import java.util.Map;
import java.util.Random;
import java.util.ArrayList;
/*假设有一个list容量只有10,而你的数据库的数据有100个,访问是随机的,
请基于访问次数,做一个LRU算法的小型缓存。注意线程安全!*/
public class LRUCache<K, V> {
private static final float hashTableLoadFactor = 0.75f;
private LinkedHashMap<K, V> map;
private int cacheSize;
public LRUCache(int cacheSize) {
this.cacheSize = cacheSize;
int hashTableCapacity = (int) Math.ceil(cacheSize / hashTableLoadFactor) + 1;
map = new LinkedHashMap<K, V>(hashTableCapacity, hashTableLoadFactor, true) {
private static final long serialVersionUID = 1;
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > LRUCache.this.cacheSize;
}
};
}
public synchronized V get(K key) {
return map.get(key);
}
public synchronized void put(K key, V value) {
map.put(key, value);
}
public synchronized void clear() {
map.clear();
}
public synchronized int usedEntries() {
return map.size();
}
public synchronized Collection<Map.Entry<K, V>> getAll() {
return new ArrayList<Map.Entry<K, V>>(map.entrySet());
}
public static void main(String[] args) {
List<String> list1 = new ArrayList<>();
Random r = new Random();
// 给list1设置100个
for (int i = 0; i < 100; i++) {
list1.add("" + i + "");
}
LRUCache<String, String> list2 = new LRUCache<String, String>(10);
for (int i = 0; i < 10; i++) {
list2.put("" + i + "", list1.get(r.nextInt(100)));
}
System.out.println("添加10个,结果0-9");
for (Map.Entry<String, String> e : list2.getAll())
System.out.print(e.getKey() + ":" + e.getValue() + " ,");
list2.put("10", list1.get(r.nextInt(100)));
System.out.println("\n添加11个,结果为1-10");
for (Map.Entry<String, String> e : list2.getAll())
System.out.print(e.getKey() + ":" + e.getValue() + " ,");
}
}
LRU算法的小型缓存
最新推荐文章于 2024-09-13 19:19:27 发布