1 7 8 package org.jboss.mx.util; 9 10 import java.util.Stack ; 11 12 22 public class ThreadPool 23 { 24 26 private static int counter = 0; 28 29 32 private Stack pool = new Stack (); 33 34 37 private int maxSize = 10; 38 39 42 private boolean active = false; 43 44 47 private boolean daemon = true; 48 49 51 53 56 public ThreadPool() 57 { 58 } 59 60 65 public ThreadPool(boolean active) 66 { 67 this.active = active; 68 } 69 70 72 77 public void setMaximumSize(int size) 78 { 79 maxSize = size; 80 } 81 82 87 public int getMaximumSize() 88 { 89 return maxSize; 90 } 91 92 98 public void setActive(boolean status) 99 { 100 active = status; 101 if (active == false) 102 while (pool.size() > 0) 103 ((Worker)pool.pop()).die(); 104 } 105 106 111 public boolean isActive() 112 { 113 return active; 114 } 115 116 121 public void setDaemonThreads(boolean value) 122 { 123 daemon = value; 124 } 125 126 131 public boolean getDaemonThreads() 132 { 133 return daemon; 134 } 135 136 143 public synchronized void run(Runnable work) 144 { 145 if (pool.size() == 0) 146 new Worker(work); 147 else 148 { 149 Worker worker = (Worker) pool.pop(); 150 worker.run(work); 151 } 152 } 153 154 156 163 private synchronized void returnWorker(Worker worker) 164 { 165 if (pool.size() < maxSize) 166 pool.push(worker); 167 else 168 worker.die(); 169 } 170 171 173 176 class Worker extends Thread 177 { 178 181 boolean running = true; 182 183 186 Runnable work; 187 188 193 Worker(Runnable work) 194 { 195 super("ThreadPoolWorker["+(++counter)+"]"); 197 this.work = work; 198 setDaemon(daemon); 199 start(); 200 } 201 202 205 public synchronized void die() 206 { 207 running = false; 208 this.notify(); 209 } 210 211 218 public synchronized void run(Runnable work) 219 { 220 if (this.work != null) 221 throw new IllegalStateException ("Worker already has work to do."); 222 this.work = work; 223 this.notify(); 224 } 225 226 229 public void run() 230 { 231 while (active && running) 232 { 233 if (work != null) 235 { 236 try 237 { 238 work.run(); 239 } 240 catch (Exception ignored) {} 241 242 work = null; 244 } 245 246 returnWorker(this); 248 249 synchronized (this) 251 { 252 while (running && work == null) 253 { 254 try 255 { 256 this.wait(); 257 } 258 catch (InterruptedException ignored) {} 259 } 260 } 261 } 262 } 263 } 264 } 265 | Popular Tags |