本文共 1934 字,大约阅读时间需要 6 分钟。
public class CacheMap extends AbstractMap { //默认保存时间 private static final long DEFAULT_TIMEOUT = 1000*60*10; private static CacheMap defaultInstance; //缓存时间 private long cacheTimeout; private Map map = new HashMap (); public CacheMap(long timeout) { this.cacheTimeout = timeout; new ClearThread().start(); } public static synchronized final CacheMap getDefault() { if (defaultInstance == null) { defaultInstance = new CacheMap (DEFAULT_TIMEOUT); } return defaultInstance; } //缓存实体 private class CacheEntry implements Entry { long time; V value; 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; } } //清理缓存线程 private class ClearThread extends Thread { ClearThread() { setName("clear cache thread"); } 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 >= cacheTimeout) { synchronized (map) { map.remove(key); } } } Thread.sleep(cacheTimeout); } catch (Exception e) { e.printStackTrace(); } } } } @Override public Set > entrySet() { Set > entrySet = new HashSet >(); Set > wrapEntrySet = map.entrySet(); for (Entry 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); synchronized (map) { map.put(key, entry); } return value; }}
转载于:https://my.oschina.net/zhengweishan/blog/3043774