30秒缓存
緩存類(lèi):
package test;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* 用來(lái)存儲(chǔ)短暫對(duì)象的緩存類(lèi),實(shí)現(xiàn)Map接口,內(nèi)部有一個(gè)定時(shí)器用來(lái)清除過(guò)期(30秒)的對(duì)象。
* 為避免創(chuàng)建過(guò)多線程,沒(méi)有特殊要求請(qǐng)使用getDefault()方法來(lái)獲取本類(lèi)的實(shí)例。
* 此代碼來(lái)源于互聯(lián)網(wǎng)
* @param <K>
* @param <V>
*/
public class CacheMap<K, V> extends AbstractMap<K, V> {
//過(guò)期時(shí)間為30秒
private static final long DEFAULT_TIMEOUT = 30000;
private static CacheMap<Object, Object> defaultInstance;
public static synchronized final CacheMap<Object, Object> getDefault() {
if (defaultInstance == null) {
defaultInstance = new CacheMap<Object, Object>(DEFAULT_TIMEOUT);
}
return defaultInstance;
}
private class CacheEntry implements Entry<K, V> {
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();
}
}
}
}
private long cacheTimeout;
private Map<K, CacheEntry> map = new HashMap<K, CacheEntry>();
public CacheMap(long timeout) {
this.cacheTimeout = timeout;
new ClearThread().start();
}
@Override
public Set<Entry<K, V>> entrySet() {
Set<Entry<K, V>> entrySet = new HashSet<Map.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);
synchronized (map) {
map.put(key, entry);
}
return value;
}
}
調(diào)用緩存類(lèi):
package test;
/**
* 調(diào)用步驟:
* 1:向緩存類(lèi)中存放一個(gè)key和Value
* 2:30秒之前使用get(key)取出的是value
* 3:30秒后使用get(key)取出的是null
* @author xuming
*
*/
public class run {
public static void main(String[] args) {
//實(shí)例化CacheMap方法
CacheMap c = CacheMap.getDefault();
c.put("k1","v1");
//存放時(shí)的時(shí)間戳
double currentTime =System.currentTimeMillis();
for(int i = 0;i<500000;i++){
//當(dāng)前的時(shí)間差---獲取get(key)
System.out.println((System.currentTimeMillis()-currentTime)/10000+"秒---"+c.get("k1"));
}
}
}
轉(zhuǎn)載于:https://www.cnblogs.com/Xmingzi/p/7886722.html
總結(jié)
- 上一篇: c# 拼接lambda表达式 (转载)
- 下一篇: ReactNative windows下