使用監聽器:定時清除map緩存的key value .
配置web.xml:注意位置
<listener>
<listener-class>
com.my.common.listener.TimerListener
</listener-class>
</listener>
監聽類:
public class TimerListener implements ServletContextListener
{
public void contextDestroyed(ServletContextEvent event)
{
//服務停止時執行
}
public void contextInitialized(ServletContextEvent arg0)
{
//服務啟動、初始化時執行
int minutes = 10;
int second = 60;
int timeDistance = 1000;
//使用定時類,每隔一段時間執行
java.util.Timer timer = new java.util.Timer();
timer.schedule(new MyRandomMap(), new Date(), minutes * second* timeDistance);
}
private class MyRandomMap extends java.util.TimerTask //實現了TimerTask的類
{
public void run()
{
clearRandomMap();//每隔一段時間執行
}
}
public void clearRandomMap()
{
// 清除map過期的key
List<String> list = new ArrayList<String>();
Long now = System.currentTimeMillis();
Iterator iter = Tools.randomMap.keySet().iterator();
while (iter.hasNext())
{
String key = iter.next().toString();
Long val = Tools.randomMap.get(key);
//設計很巧妙:使用時間(毫秒)作為value,好處在於可以與當前時間(毫秒)比較大小,從達到過時
刪除
的目的
if(now-val>2 * 60 * 1000)
{
list.add(key);
}
}
for (int i = 0; i < list.size(); i++)
{
Tools.randomMap.remove(list.get(i));
}
}
}