基于Java实现缓存Cache的深入分析

原理是使用LinkedHashMap来实现,当缓存超过大小时,将会删除最老的一个元组
实现代码如下所示

import java.util.LinkedHashMap;
import java.util.Map;
public class LRUCache {
 public static class CachedData {
  private Object data = null;
  private long time = 0;
  private boolean refreshing = false;
  public CachedData(Object data) {
   this.data = data;
   this.time = System.currentTimeMillis();
  }
  public Object getData() {
   return data;
  }
  public long getTime() {
   return time;
  }

  public void setTime(long time) {
   this.time = time;
  }

  public boolean getRefreshing() {
      return refreshing;
  }

  public void setRefreshing(boolean b) {
      this.refreshing = b;
  }
 }
 protected static class CacheMap extends LinkedHashMap {
  protected int maxsize = 0;
  public CacheMap(int maxsize) {
   super(maxsize * 4 / 3 + 1,0.75f,true);
   this.maxsize = maxsize;
  }
  protected boolean removeEldestEntry(Map.Entry eldest) {
   return size() > this.maxsize;
  }
 }
 protected CacheMap map = null;
 public LRUCache(int size) {
  this.map = new CacheMap(size);
 }
 public synchronized void set(Object key,Object value) {
  map.remove(key);
  map.put(key,new CachedData(value));
 }
 public synchronized void remove(Object key) {
  map.remove(key);
 }
 public synchronized CachedData get(Object key) {
  CachedData value = (CachedData) map.get(key);
  if (value == null) {
   return null;
  }
  map.remove(key);
  map.put(key,value);

  return value;
 }

 public int usage() {
  return map.size();
 }

 public int capacity() {
  return map.maxsize;
 }

 public void clear() {
  map.clear();
 }
}

相关文章

HashMap是Java中最常用的集合类框架,也是Java语言中非常典型...
在EffectiveJava中的第 36条中建议 用 EnumSet 替代位字段,...
介绍 注解是JDK1.5版本开始引入的一个特性,用于对代码进行说...
介绍 LinkedList同时实现了List接口和Deque接口,也就是说它...
介绍 TreeSet和TreeMap在Java里有着相同的实现,前者仅仅是对...
HashMap为什么线程不安全 put的不安全 由于多线程对HashMap进...