首页

分析基于HashMap的定义HashMapCache缓存实现类可以在指定缓存失效时间FIFO进行失效代码示例

标签:HashMapCache,hash缓存,fifo,自定义缓存机制     发布时间:2018-11-29   

一、前言

基于java.util.HashMap并实现定义Cache缓存接口的HashMapCache实现类,在缓存内对象按照FIFO的失效机制进行释放缓存空间,详情参见代码示例。

二、代码示例

1. Cache接口

public abstract interface Cache@b@{@b@  public abstract void put(Object paramObject1, Object paramObject2);@b@@b@  public abstract Object get(Object paramObject);@b@@b@  public abstract void remove(Object paramObject);@b@@b@  public abstract void clear();@b@@b@  public abstract int size();@b@}

2. HashMapCache实现类

import java.util.HashMap;@b@import java.util.Iterator;@b@import java.util.Map;@b@import java.util.Map.Entry;@b@import java.util.Set;@b@@b@public class HashMapCache implements Cache {@b@	@b@	private final Map cache = new HashMap();@b@	private long clearInterval = 86400000L;@b@	private long clearTimePoint = System.currentTimeMillis()@b@			+ this.clearInterval;@b@	private int maxSize = 1000;@b@@b@	public HashMapCache() {@b@	}@b@@b@	public HashMapCache(long clearInterval, int maxSize) {@b@		this.clearInterval = clearInterval;@b@		this.maxSize = maxSize;@b@	}@b@@b@	public void clear() {@b@		this.cache.clear();@b@	}@b@@b@	public Object get(Object key) {@b@		checkClear();@b@		Value value = (Value) this.cache.get(key);@b@		if (value != null) {@b@			Value.access$002(value, System.currentTimeMillis());@b@			return Value.access$100(value);@b@		}@b@		return null;@b@	}@b@@b@	public void put(Object key, Object value) {@b@		checkClear();@b@		checkMaxSize();@b@		this.cache.put(key, new Value(value));@b@	}@b@@b@	public int size() {@b@		return this.cache.size();@b@	}@b@@b@	private void checkClear() {@b@		if (System.currentTimeMillis() > this.clearTimePoint) {@b@			this.cache.clear();@b@			this.clearTimePoint = (System.currentTimeMillis() + this.clearInterval);@b@		}@b@	}@b@@b@	private void checkMaxSize() {@b@		long timePoint;@b@		Iterator it;@b@		if (this.cache.size() > this.maxSize) {@b@			timePoint = System.currentTimeMillis() - this.clearInterval / 2L;@b@			for (it = this.cache.entrySet().iterator(); it.hasNext();) {@b@				Map.Entry e = (Map.Entry) it.next();@b@				Value value = (Value) e.getValue();@b@				if (Value.access$000(value) < timePoint)@b@					it.remove();@b@			}@b@		}@b@	}@b@@b@	public void remove(Object key) {@b@		this.cache.remove(key);@b@	}@b@@b@	private static class Value {@b@		private Object value;@b@		private long time = System.currentTimeMillis();@b@@b@		public Value(Object value) {@b@			this.value = value;@b@		}@b@@b@		static long access$002(Value x0, long x1) {@b@			return (x0.time = x1);@b@		}@b@@b@		static Object access$100(Value x0) {@b@			return x0.value;@b@		}@b@@b@		static long access$000(Value x0) {@b@			return x0.time;@b@		}@b@	}@b@}
  • ◆ 相关内容