1 19 package freecs.core; 20 21 import java.util.HashMap ; 22 import java.util.Iterator ; 23 24 import freecs.Server; 25 26 27 33 public class RequestMonitor extends Thread { 34 public static RequestMonitor instance = new RequestMonitor(); 35 private HashMap monitors = new HashMap (); 36 37 private RequestMonitor () { 38 } 39 40 public synchronized void addMonitor (Thread t, long timeout) { 41 if (!this.isAlive()) 42 this.start(); 43 if (t == null) 44 return; 45 monitors.put(t, new Long (timeout)); 46 } 47 48 public synchronized void removeMonitor (Thread t) { 49 monitors.remove(t); 50 } 51 52 private void interruptMonitored(Thread t) { 53 t.interrupt(); 54 57 Server.log ("RequestMonitor", "interrupted thread " + t.toString(), Server.MSG_STATE, Server.LVL_MAJOR); 58 } 59 60 public void run () { 61 long lastMessage = 0; 62 while (Server.srv.isRunning()) { 63 if (Server.DEBUG || lastMessage + 5000 > System.currentTimeMillis()) { 64 Server.log (this, "loopstart", Server.MSG_STATE, Server.LVL_VERY_VERBOSE); 65 lastMessage = System.currentTimeMillis(); 66 } 67 long sleepTime = 1000; 68 long now = System.currentTimeMillis(); 69 synchronized (this) { 70 for (Iterator i = monitors.keySet().iterator(); i.hasNext(); ) { 71 Thread t = (Thread ) i.next(); 72 long timeout = ((Long ) monitors.get(t)).longValue(); 73 if (timeout <= now) { 74 interruptMonitored(t); 75 i.remove(); 76 continue; 77 } else { 78 long thisTimeout = now - timeout; 79 if (thisTimeout < sleepTime) 80 sleepTime = thisTimeout; 81 } 82 } 83 } 84 if (sleepTime < 33) 85 sleepTime = 33; 86 try { 87 Thread.sleep(sleepTime); 88 } catch (InterruptedException ie) { 89 } 91 } 92 } 93 94 public String toString () { 95 return "[RequestMonitor]"; 96 } 97 } | Popular Tags |