1 23 24 package com.scalagent.kjoram.util; 25 26 import com.scalagent.kjoram.JoramTracing; 27 28 57 public abstract class Daemon implements Runnable { 58 59 63 public synchronized boolean isRunning() { 64 return ((thread != null) && thread.isAlive()); 65 } 66 67 73 protected volatile boolean running; 74 81 protected volatile boolean canStop; 82 83 protected Thread thread = null; 84 85 private String name; 86 87 private boolean daemon = false; 88 89 protected int priority = Thread.NORM_PRIORITY; 90 91 96 public final String getName() { 97 return name; 98 } 99 100 105 public String toString() { 106 StringBuffer strbuf = new StringBuffer (); 107 108 strbuf.append(getName()) 109 .append(" [").append(running).append("/") 110 .append(canStop).append("]"); 111 112 if (thread != null) strbuf.append(" -> ").append(thread.isAlive()); 113 114 return strbuf.toString(); 115 } 116 117 122 protected Daemon(String name) { 123 this.name = name; 124 running = false; 125 canStop = false; 126 thread = null; 127 } 128 129 public void setDaemon(boolean daemon) { 130 if (running || ((thread != null) && thread.isAlive())) { 131 throw new IllegalThreadStateException ("already started"); 132 } 133 this.daemon = daemon; 134 } 135 136 public void setPriority(int newPriority) { 137 if ((newPriority > Thread.MAX_PRIORITY) || 138 (newPriority < Thread.MIN_PRIORITY)) { 139 throw new IllegalArgumentException (); 140 } 141 if (running && (thread != null) && thread.isAlive()) 142 thread.setPriority(newPriority); 143 priority = newPriority; 144 } 145 146 153 public synchronized void start() { 154 if ((thread != null) && thread.isAlive()) { 155 if (JoramTracing.dbg) 156 JoramTracing.log(JoramTracing.WARN, 157 getName() + ", already started."); 158 throw new IllegalThreadStateException ("already started"); 159 } 160 161 thread = new Thread (this); 162 if (priority != Thread.NORM_PRIORITY) 164 thread.setPriority(priority); 165 running = true; 166 canStop = true; 167 thread.start(); 168 169 if (JoramTracing.dbg) 170 JoramTracing.log(JoramTracing.DEBUG, 171 getName() + ", started."); 172 } 173 174 178 protected abstract void close(); 179 180 187 protected abstract void shutdown(); 188 189 192 196 final protected void finish() { 197 running = false; 198 close(); 199 if (JoramTracing.dbg) 200 JoramTracing.log(JoramTracing.DEBUG, 201 getName() + ", ended"); 202 } 203 204 209 public synchronized void stop() { 210 if (JoramTracing.dbg) 211 JoramTracing.log(JoramTracing.DEBUG, 212 getName() + ", stops."); 213 running = false; 214 if (thread != null) { 215 while (thread.isAlive()) { 216 if (canStop) { 217 218 221 shutdown(); 222 } 223 } 229 finish(); 230 thread = null; 231 } 232 } 233 } 234 | Popular Tags |