1 7 8 package org.jboss.web; 9 10 import java.util.Stack ; 11 12 18 public class ThreadPool 19 { 20 22 24 27 private final Stack pool = new Stack (); 28 29 32 private int maxSize = 10; 33 34 35 private boolean enabled = false; 36 37 39 41 44 public ThreadPool() 45 { 46 } 47 48 public synchronized void enable() 50 { 51 enabled = true; 52 } 53 54 public synchronized void disable() 55 { 56 enabled = false; 57 while (!pool.isEmpty()) 58 { 59 Worker w = (Worker)pool.pop(); 60 w.die(); 61 } } 63 64 65 66 69 public void setMaximumSize(int size) 70 { 71 maxSize = size; 72 } 73 74 79 public synchronized void run(Runnable work) 80 { 81 if (pool.size() == 0) { 82 new Worker(work); 83 } else { 84 Worker w = (Worker)pool.pop(); 85 w.run(work); 86 } 87 } 88 89 91 95 private synchronized void returnWorker(Worker w) 96 { 97 if (enabled && pool.size() < maxSize) 98 { 99 pool.push(w); 100 } 101 else 102 { 103 w.die(); 104 } } 106 107 109 class Worker extends Thread 110 { 111 114 boolean running = true; 115 116 119 Runnable work; 120 121 124 Worker(Runnable work) 125 { 126 this.work = work; 127 setDaemon(true); 128 start(); 129 } 130 131 134 public synchronized void die() 135 { 136 running = false; 137 this.notify(); 138 } 139 140 146 public synchronized void run(Runnable work) 147 { 148 if (this.work != null) 149 throw new IllegalStateException ("Worker already has work to do."); 150 this.work = work; 151 this.notify(); 152 } 153 154 157 public void run() 158 { 159 while (running) { 160 if (work != null) { 162 try { 163 work.run(); 164 } catch (Exception e) { 165 } 167 work = null; 169 } 170 171 returnWorker(this); 173 174 synchronized (this) { 176 while (running && work == null) { 177 try { 178 this.wait(); 179 } catch (InterruptedException e) { 180 } 182 } 183 } 184 } 185 } 186 187 } 188 } 189 190 | Popular Tags |