之前看redis的书,书上罗列源码的时候我总是在想,redis为什么不用Java实现!!
今天自己用Java写了一个简易的缓存,发现,redis不用Java实现可能是正确的:C语言可以自行回收内存,而Java不可以(我水平可能没达到,还没有自己回收过某个对象的内存),这样就导致了你的缓存中的对象有可能都过期了,你只是把这些过期对象的引用置空,但是什么时候回收这些内存,不是我们说了算的。
好,废话不多说了,上一段代码(代码如果写的不对、不合理的地方,还请大家一定指出)。
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class MyCache {
private Map<String, Value> map;
private int threshold; //达到百分之多少回收
private MemoryCalculateStrategy memoryCalculateStrategy;
public MyCache() {//todo: 改成单例模式
this(80, new SimpleMemoryCalculateStrategy());
}
public MyCache(int threshold) {
this(threshold, new SimpleMemoryCalculateStrategy());
}
public MyCache(int threshold, MemoryCalculateStrategy memoryCalculateStrategy) {
map = new Con