package uk.ac.vamsas.client.simpleclient; import java.util.Iterator; import java.util.Vector; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Watches a bunch of VamsasFile states, calling * the associated event handler when anything changes. * @author JimP * */ public class VamsasFileWatcherThread extends Thread { private Log log = LogFactory.getLog(VamsasFileWatcherThread.class); /* (non-Javadoc) * @see java.lang.Thread#run() */ EventGeneratorThread client=null; private Vector elements=null; public VamsasFileWatcherThread(EventGeneratorThread client) { this.client = client; elements=new Vector(); } public void addElement(WatcherElement welement) { elements.addElement(welement); } public void removeElemenet(WatcherElement welement) { elements.removeElement(welement); } public void clearElements() { elements.clear(); } /** * true if the thread is running */ boolean running=false; /** * true if the watcher loop is in progress */ boolean watching=false; public void haltWatchers() { if (!watching) return; watching=false; // wait arount for WATCH_SLEEP milliseconds before returning // in the hope that the watcher loop has stopped try { long time = System.currentTimeMillis()+WATCH_SLEEP; interrupt(); while (running && time>System.currentTimeMillis()) { Thread.sleep(1); } } catch (Exception e) {}; if (running) log.warn("haltWatchers returning whilst thread is still running."); } /** * time between checks for changes of state on the file */ public int WATCH_SLEEP=30; /** * check each watcher in sequence, monitoring any events generated. * Then wait WATCH_SLEEP milliseconds before checking all again (if there were no events) */ public void run() { running=true; watching=true; log.debug("Starting WatcherThread poll loop"); while (watching) { boolean wait=true; Iterator watchers=elements.iterator(); while (watching && watchers.hasNext()) { WatcherElement watch = (WatcherElement) watchers.next(); if (watch.doWatch()) { wait=false; log.debug("Event generated for watcher on "+watch.getWatcher().getSubject()); } } if (watching && wait) { try { Thread.sleep(WATCH_SLEEP); } catch (InterruptedException e) {}; } } log.debug("Finishing WatcherThread poll loop"); running=false; } }