1 16 package org.mortbay.util; 17 18 import java.io.InterruptedIOException ; 19 20 import org.apache.commons.logging.Log; 21 import org.mortbay.log.LogFactory; 22 23 24 29 public abstract class LifeCycleThread implements LifeCycle, Runnable 30 { 31 private static Log log = LogFactory.getLog(LifeCycleThread.class); 32 33 private boolean _running; 34 private boolean _daemon ; 35 private Thread _thread; 36 37 38 public boolean isDaemon() 39 { 40 return _daemon; 41 } 42 43 44 public void setDaemon(boolean d) 45 { 46 _daemon = d; 47 } 48 49 50 public Thread getThread() 51 { 52 return _thread; 53 } 54 55 56 public boolean isStarted() 57 { 58 return _running; 59 } 60 61 62 public synchronized void start() 63 throws Exception 64 { 65 if (_running) 66 { 67 log.debug("Already started"); 68 return; 69 } 70 _running=true; 71 if (_thread==null) 72 { 73 _thread=new Thread (this); 74 _thread.setDaemon(_daemon); 75 } 76 _thread.start(); 77 } 78 79 80 82 public synchronized void stop() 83 throws InterruptedException 84 { 85 _running=false; 86 if (_thread!=null) 87 { 88 _thread.interrupt(); 89 _thread.join(); 90 } 91 } 92 93 94 95 97 public final void run() 98 { 99 try 100 { 101 while(_running) 102 { 103 try 104 { 105 loop(); 106 } 107 catch(InterruptedException e) 108 { 109 LogSupport.ignore(log,e); 110 } 111 catch(InterruptedIOException e) 112 { 113 LogSupport.ignore(log,e); 114 } 115 catch(Exception e) 116 { 117 if (exception(e)) 118 break; 119 } 120 catch(Error e) 121 { 122 if (error(e)) 123 break; 124 } 125 } 126 } 127 finally 128 { 129 _running=false; 130 } 131 } 132 133 134 138 public boolean exception(Exception e) 139 { 140 log.warn(LogSupport.EXCEPTION,e); 141 return true; 142 } 143 144 145 149 public boolean error(Error e) 150 { 151 log.warn(LogSupport.EXCEPTION,e); 152 return true; 153 } 154 155 156 160 public abstract void loop() 161 throws InterruptedException , 162 InterruptedIOException , 163 Exception ; 164 165 } 166 | Popular Tags |