1 18 19 package org.apache.tools.ant.util; 20 21 import java.util.Enumeration ; 22 import java.util.Vector ; 23 24 32 public class Watchdog implements Runnable { 33 34 private Vector observers = new Vector (1); 35 private long timeout = -1; 36 40 private volatile boolean stopped = false; 41 45 public static final String ERROR_INVALID_TIMEOUT = "timeout less than 1."; 46 47 51 public Watchdog(long timeout) { 52 if (timeout < 1) { 53 throw new IllegalArgumentException (ERROR_INVALID_TIMEOUT); 54 } 55 this.timeout = timeout; 56 } 57 58 62 public void addTimeoutObserver(TimeoutObserver to) { 63 observers.addElement(to); 65 } 66 67 71 public void removeTimeoutObserver(TimeoutObserver to) { 72 observers.removeElement(to); 74 } 75 76 80 protected final void fireTimeoutOccured() { 81 Enumeration e = observers.elements(); 82 while (e.hasMoreElements()) { 83 ((TimeoutObserver) e.nextElement()).timeoutOccured(this); 84 } 85 } 86 87 90 public synchronized void start() { 91 stopped = false; 92 Thread t = new Thread (this, "WATCHDOG"); 93 t.setDaemon(true); 94 t.start(); 95 } 96 97 100 public synchronized void stop() { 101 stopped = true; 102 notifyAll(); 103 } 104 105 111 public synchronized void run() { 112 final long until = System.currentTimeMillis() + timeout; 113 long now; 114 while (!stopped && until > (now = System.currentTimeMillis())) { 115 try { 116 wait(until - now); 117 } catch (InterruptedException e) { 118 } 120 } 121 if (!stopped) { 122 fireTimeoutOccured(); 123 } 124 } 125 126 } 127 | Popular Tags |