java添加超时检测

需求,在不一样的ssm模块间,若是一个模块给给一个模块发任务,任务又好多,期间有某个任务死循环、崩了,怎么办?
因此在这里要作一个超时机制,监听每一个任务,原理很简单,用一个线程不断去判断任务是否超时。web

  • controller拿到任务,将拿到的元素和拿到时刻的时间记录下,存储在hashMap中缓存

  • Timer线程不停的去遍历hashMap,将超时时间大于某个阀值的任务设置为超时链接,调用处理方法svg

这里要考虑的问题只有一个:要保证Timer复用this

Timer:线程

public class Timer extends Thread {
	
	private static Logger logger = LoggerFactory.getLogger(Timer.class);
	
	//缓存机制
	private static Map<String, String> map;
	
	//超时阀值
	private static int timestamp = 3000;
    
	public Timer(Map<CmdNotice, String> map, CenterService centerService){
    	this.map = map;
    }
	
	public void run(){
		try{
        	logger.info("--------------------center:启动超时线程--------------------");
            Iterator<Entry<String, String>> it = map.entrySet().iterator();
	    	while(it.hasNext()){
		    	Entry<String, String> entry = it.next();
		    	Long now = System.currentTimeMillis();
		    	int nowtime = now.intValue();
		    	int last = Integer.parseInt(entry.getValue());
		    	//超时,从队列里面踢出
		    	if(nowtime - last > timestamp) {
		    		logger.info("--------------------center:超时了--------------------");
		    		//记录异常,通知异常处理
		    		...
		    	}
           }
        }catch(Exception e){
        	e.printStackTrace();
        }
	}
	
}

应用场景:code

...
    //将任务加入队列
	QUEUE_NODE.offer(“xxxx”);
	Long now = System.currentTimeMillis();
    int nowtime = now.intValue();
    map.put("xxxx", nowtime +"");
	//启动监听超时线程
	new Timer(map).start();
	Thread.currentThread();
...