需求,在不一樣的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(); ...