1 4 package nl.justobjects.pushlet.core; 5 6 import nl.justobjects.pushlet.util.Log; 7 8 9 15 16 17 abstract public class EventPullSource implements EventSource, Runnable { 18 private volatile boolean alive = false; 19 private volatile boolean active = false; 20 private static int threadNum = 0; 21 private Thread thread; 22 23 public EventPullSource() { 24 } 25 26 abstract protected long getSleepTime(); 27 28 abstract protected Event pullEvent(); 29 30 public void start() { 31 thread = new Thread (this, "EventPullSource-" + (++threadNum)); 32 thread.setDaemon(true); 33 thread.start(); 34 } 35 36 public boolean isAlive() { 37 return alive; 38 } 39 40 41 public void stop() { 42 alive = false; 43 44 if (thread != null) { 45 thread.interrupt(); 46 thread = null; 47 } 48 49 } 50 51 52 synchronized public void activate() { 53 if (active) { 54 return; 55 } 56 active = true; 57 if (!alive) { 58 start(); 59 return; 60 } 61 Log.debug(getClass().getName() + ": notifying..."); 62 notifyAll(); 63 } 64 65 66 public void passivate() { 67 if (!active) { 68 return; 69 } 70 active = false; 71 } 72 73 74 public void run() { 75 Log.debug(getClass().getName() + ": starting..."); 76 alive = true; 77 while (alive) { 78 try { 79 80 Thread.sleep(getSleepTime()); 81 82 if (!alive) { 84 break; 85 } 86 87 synchronized (this) { 91 while (!active) { 92 Log.debug(getClass().getName() + ": waiting..."); 93 wait(); 94 } 95 } 96 97 } catch (InterruptedException e) { 98 break; 99 } 100 101 try { 102 Event event = pullEvent(); 104 105 Dispatcher.getInstance().multicast(event); 107 } catch (Throwable t) { 108 Log.warn("EventPullSource exception while multicasting ", t); 109 t.printStackTrace(); 110 } 111 } 112 Log.debug(getClass().getName() + ": stopped"); 113 } 114 } 115 116 174 | Popular Tags |