常见的策略有三种:先进先出策略 FIFO(First In,First Out)、最少使用策略 LFU(Least Frequently Used)、最近最少使用策略 LRU(Least Recently Used)。
- 使用链表实现LRU算法的方式很多,现在用数组也实现一下,话不多说上代码:
public class LRU {
private static String[] lruArray = new String[10];
private static String[] copyArray = new String[10];
private static HashMap<String, Integer> hashMap = new HashMap<>();
public static void main(String[] args) throws InterruptedException {
for(int i = 0; i < 100; i++) {
String str = "str" + Math.round(Math.random()*20);
TimeUnit.SECONDS.sleep(1);
LRUArithmetic(str);
}
}
public static void LRUArithmetic(String str) {
if(hashMap.containsKey(str)) {
if(hashMap.get(str) > 0) {
int pos = hashMap.get(str);
copyArray[0] = str;
for(int i = 1;i <= pos; i++) {
copyArray[i] = lruArray[i-1];
}
for(int i = pos + 1; i < 10; i++) {
copyArray[i] = lruArray[i];
}
for(int i = 0; i < copyArray.length; i++) {
lruArray[i] = copyArray[i];
hashMap.put(lruArray[i], i);
}
copyArray = new String[10];
}
} else {
copyArray[0] = str;
hashMap.put(str, 0);
if(!StringUtils.isEmpty(lruArray[9])) {
hashMap.remove(lruArray[9]);
}
for(int i = 1; i < copyArray.length; i++) {
copyArray[i] = lruArray[i-1];
}
for(int i = 0; i < copyArray.length; i++) {
lruArray[i] = copyArray[i];
hashMap.put(lruArray[i], i);
}
copyArray = new String[10];
}
for(int i = 0; i < lruArray.length; i++) {
System.out.print(lruArray[i] + ",");
}
System.out.println("--------------------分隔符---------------------");
}
}