zoukankan      html  css  js  c++  java
  • 使用监听器:定时清除map缓存的key value .


    使用监听器:定时清除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));

      }

     }
    }

  • 相关阅读:
    第五周总结
    第四周总结
    第三周总结
    第二周总结
    第一周总结
    暑假学习进度八
    使用nmtui文本框方式修改IP
    Linux 忘记密码配置
    关于公网IP和内网IP
    常见API编写方式(三种)
  • 原文地址:https://www.cnblogs.com/qqzy168/p/3136970.html
Copyright © 2011-2022 走看看