当前位置: 移动技术网 > IT编程>开发语言>Java > 基于Java实现缓存Cache的深入分析

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

2019年07月22日  | 移动技术网IT编程  | 我要评论
原理是使用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();
 }
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网