import java.util.AbstractMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
-
用来存储短暂对象的缓存类,实现Map接口,内部有一个定时器用来清除过期(timeOut)的对象。
-
注意:为避免创建过多线程,没有特殊要求请使用getDefault()方法来获取本类的实例。
*/
public class CacheMap<K, V> extends AbstractMap<K, V> {// 设置超时时间
private static long timeOut = 10 * 60 * 1000;
// 设置缓存
private static CacheMap<Object, Object> defaultInstance;
// 线程休眠时间(默认3秒)
private static long threadSleepTime = 3000L;
// CacheEntry缓存map值存入的时间
private Map<K, CacheEntry> map = new HashMap<K, CacheEntry>();/**
- 获取缓存
- @return
*/
public static synchronized final CacheMap<Object, Object> getDefault() {
if (defaultInstance == null) {
defaultInstance = new CacheMap<Object, Object>(timeOut);
}
return defaultInstance;
}
public CacheMap(long timeOut) {
CacheMap.timeOut = timeOut;
new ClearThread().start();
}@Override
public Set<Entry<K, V>> entrySet() {
Set<Entry<K, V>> entrySet = new HashSet<Entry<K, V>>();
Set<Entry<K, CacheEntry>> wrapEntrySet = map.entrySet();
for (Entry<K, CacheEntry> entry : wrapEntrySet) {
entrySet.add(entry.getValue());
}
return entrySet;
}@Override
public V get(Object key) {
CacheEntry entry = map.get(key);
return entry == null ? null : entry.value;
}@Override
public V put(K key, V value) {
CacheEntry entry = new CacheEntry(key, value);
// 锁map太浪费资源,不建议使用,后期了解下高并发ConcurrentHashMap会对此做修改
synchronized (key) {
map.put(key, entry);
}
return value;
}/**
- 清除map缓存线程
*/
private class ClearThread extends Thread {
ClearThread() {
setName(“clear cache thread”);
}
@Override
public void run() {
while (true) {
try {
long now = System.currentTimeMillis();
Object[] keys = map.keySet().toArray();
for (Object key : keys) {
CacheEntry entry = map.get(key);
if (now - entry.time >= timeOut) {
synchronized (key) {
map.remove(key);
}
}
}
Thread.sleep(threadSleepTime);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
-
缓存map值对象(包换map值存入map缓存的时间)
*/
private class CacheEntry implements Entry<K, V> {
private long time;
private V value;
private K key;CacheEntry(K key, V value) {
super();
this.value = value;
this.key = key;
this.time = System.currentTimeMillis();
}@Override
public K getKey() {
return key;
}@Override
public V getValue() {
return value;
}@Override
public V setValue(V value) {
return this.value = value;
}
}
public static void main(String[] args) {
//CacheMap.getDefault().put(“123”,123);
System.out.println(“finish”);
System.out.println(CacheMap.getDefault().get(“123”));
}