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();
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值