java添加超时检测

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/change_on/article/details/84335834

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

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

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

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

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();
        }
	}
	
}

应用场景:

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

猜你喜欢

转载自blog.csdn.net/change_on/article/details/84335834
今日推荐