Cache问题,淘宝用户数据比较多,每次用户来讲问,需要仅数据库取得用户信息,为了提高速度,在内存中缓存用户数据,设计算法,Cache满的时候需要删除很久没有使用的数据。
import java.util.ArrayList;
import java.util.HashMap;
public class Resolve {
HashMap cache = new HashMap();
ArrayList<Integer> list = new ArrayList<Integer>();
int index = 0;
int rear = 0;
int cacheSize = 3;
/**
*
* @param id
* @param data
* return void
*eg. 1, 2, 3, 4, 5, 1, 2, 5, 1, 2
* | |
* index rear
*/
private void addToCache(int id, String data) {
rear++;
/**
* 如果在hashmap中不存在该数据,若当前小于Cache容量还足够
* 则往里直接添加数据,否则通过index获得最近没有使用的ID(index总是
* 指向最后一个没有使用的ID)然后通过id把hashmap中该数据删除
*
*
*/
if (!cache.containsKey(id)) {
if (rear > cacheSize) {
int oldID = list.get(index);
cache.remove(oldID);
}
cache.put(id, data);
}
list.add(id);
/** 如果在hashmap中存在该数据,则最后的rear指针要加一,而index指针要
* 找一个与当前id不一样的ID(因为可能会有连续的相同的ID)假设Cache为3,如下:
* 1, 2, 3, 4, 5, 1, 2, 2, 2, 5, 1, 2
* | |
* index rear
* 则需要找到5才停下
*/
if (rear > cacheSize)
while(list.get(++index) == id);
for (int i = index; i < rear; i++) {
System.out.print(list.get(i) + " ");
}
System.out.println();
System.out.println(cache);
System.out.println();
}
public static void main(String argv[]) {
int[] lru = new int[]{1, 2, 3, 4, 5, 1, 2, 5, 1, 2, 3, 4, 5};
String data = "data";
Resolve r = new Resolve();
r.addToCache(1, data);
r.addToCache(2, data);
r.addToCache(3, data);
r.addToCache(4, data);
r.addToCache(5, data);
r.addToCache(1, data);
r.addToCache(2, data);
r.addToCache(5, data);
r.addToCache(1, data);
r.addToCache(2, data);
r.addToCache(3, data);
r.addToCache(4, data);
r.addToCache(5, data);
// cache.put(, value)
}
}