根据某种条件定时删除Map中的key

根据某种条件定时删除Map中的key,主要用于一些定时删除key的操作
应该是在模仿httpsession的环境中应用比较多
package pack;
import java.util.HashMap;
import java.util.Map;
/**
 *
 * @author Administrator
 *
 */
public abstract class ExecuteTimeTask extends Thread {
 
 private long time=60*100;//定时时间
 private Map map=null;
 /**
  * condition is true, execute the clean operation
  * @param key
  * @param value
  * @return
  */
 public abstract boolean condition(Object key,Object value);
 
 
 
 
 /* (non-Javadoc)
  * @see java.lang.Thread#run()
  */
 public void run() {
  for(;;){
   //
   try {
    synchronized (this) {
     this.wait(time);
    }    
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   
   if(map==null||map.size()<1){
    continue;
   }
   
   for(java.util.Iterator it=map.entrySet().iterator();it.hasNext();){
     Map.Entry entry=(Map.Entry)it.next();
     if(condition(entry.getKey(),entry.getValue())){
      it.remove();
     };
    
    
   }
  
   
  }
 }

 /**
  * @param args
  */
 public static void main(String[] args) {
  ExecuteTimeTask t=new ExecuteTimeTask(){
   public boolean condition(Object key, Object value) {
    return key.toString().equals(value.toString())?true:false;
    //return true;
   }
   
  };
  Map m=new HashMap();
  m.put("a", "2");
  //m.put("2", "2");
  t.setMap(m);
  t.setTime(1000);
  
  
  t.start();
  long l=0;
   for(;;){
   
    try {
     synchronized (Thread.currentThread()) {
      Thread.currentThread().wait(2000);
     }   
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
     System.err.println("before--"+m+"---"+java.lang.Runtime.getRuntime().totalMemory());
  m.put(l+"", l+"");
  l++;
  System.err.println("after"+m+"---nanotime--"+System.nanoTime()+"-----"+System.currentTimeMillis());
   }
  
 }

 /**
  * @return the map
  */
 public Map getMap() {
  return map;
 }

 /**
  * @param map the map to set
  */
 public void setMap(Map map) {
  this.map = map;
 }

 /**
  * @return the time
  */
 public long getTime() {
  return time;
 }

 /**
  * @param time the time to set
  */
 public void setTime(long time) {
  this.time = time;
 }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值