1 45 package org.exolab.jms.common.threads; 46 47 import org.exolab.jms.common.util.FifoQueue; 48 49 50 73 public class ThreadPool { 74 75 78 private final String _name; 79 80 83 private ThreadGroup _group; 84 85 88 private FifoQueue _idleWorkers; 89 90 93 private ThreadPoolWorker[] _workers; 94 95 98 private QueueWorker _queue; 99 100 103 private static volatile int _poolSeed = 0; 104 105 106 115 public ThreadPool(int threads) { 116 this(threads, false); 117 } 118 119 129 public ThreadPool(int threads, boolean daemon) { 130 this("ThreadPool-" + ++_poolSeed, threads, daemon); 131 } 132 133 142 public ThreadPool(String name, int threads) { 143 this(name, threads, false); 144 } 145 146 156 public ThreadPool(String name, int threads, boolean daemon) { 157 this(new ThreadGroup (name), threads, daemon); 158 } 159 160 169 public ThreadPool(ThreadGroup group, int threads, boolean daemon) { 170 _name = group.getName(); 171 _group = new ThreadGroup (_name); 172 if (daemon) { 173 _group.setDaemon(true); 174 } 175 if (threads < 1) { 176 throw new IllegalArgumentException ( 177 "Argument 'threads' must be > 0"); 178 } 179 180 _idleWorkers = new FifoQueue(threads); 181 _workers = new ThreadPoolWorker[threads]; 182 183 for (int i = 0; i < _workers.length; ++i) { 184 String id = _name + "-Worker-" + i; 185 _workers[i] = new ThreadPoolWorker(_group, id, _idleWorkers); 186 } 187 } 188 189 198 public void execute(Runnable target) throws InterruptedException { 199 ThreadPoolWorker worker = (ThreadPoolWorker) _idleWorkers.get(); 201 worker.process(target); 202 } 203 204 211 public void queue(Runnable target) { 212 queue(target, null); 213 } 214 215 225 public synchronized void queue(Runnable target, 226 CompletionListener listener) { 227 if (_queue == null) { 228 _queue = new QueueWorker(this, _group, _name + "-QueueWorker"); 229 } 230 _queue.add(target, listener); 231 } 232 233 239 public void stopRequestIdleWorkers() { 240 try { 241 Object [] idle = _idleWorkers.getAll(); 242 for (int i = 0; i < idle.length; i++) { 243 ((ThreadPoolWorker) idle[i]).stopRequest(); 244 } 245 } catch (InterruptedException exception) { 246 Thread.currentThread().interrupt(); 248 } 249 } 250 251 256 public void stopRequestAllWorkers() { 257 final long delay = 250; 258 stopRequestIdleWorkers(); 259 260 try { 262 Thread.sleep(delay); 263 } catch (InterruptedException ignore) { 264 } 265 266 for (int i = 0; i < _workers.length; i++) { 267 if (_workers[i].isAlive()) { 268 _workers[i].stopRequest(); 269 } 270 } 271 272 if (_queue != null && _queue.isAlive()) { 273 _queue.stop(); 274 } 275 } 276 277 283 boolean hasIdleThread() { 284 return (_idleWorkers.isEmpty() ? false : true); 285 } 286 287 } 288 | Popular Tags |