1 package org.sapia.ubik.net; 2 3 import java.util.ArrayList ; 4 import java.util.List ; 5 6 7 44 public abstract class ThreadPool extends Pool { 45 private String _name; 46 private boolean _daemon; 47 private boolean _shuttingDown; 48 private List _busy = new ArrayList (); 49 50 62 protected ThreadPool(String name, boolean daemon, int maxSize) { 63 super(maxSize); 64 _name = name; 65 _daemon = daemon; 66 } 67 68 78 protected ThreadPool(String name, boolean daemon) { 79 _name = name; 80 _daemon = daemon; 81 } 82 83 88 protected Object onAcquire(Object o) throws Exception , IllegalStateException { 89 if (_shuttingDown) { 90 throw new IllegalStateException ( 91 "Could not acquire thread; pool is shutting down"); 92 } 93 94 ((PooledThread) o).acquire(); 95 _busy.add(o); 96 97 return o; 98 } 99 100 103 protected synchronized void onRelease(Object o) { 104 ((PooledThread) o).release(); 105 _busy.remove(o); 106 notifyAll(); 107 } 108 109 114 public synchronized void shutdown() { 115 shutdown(0); 116 } 117 118 130 public synchronized void shutdown(long timeout) { 131 _shuttingDown = true; 132 133 for (int i = 0; i < _objects.size(); i++) { 134 ((PooledThread) _objects.get(i)).shutdown(); 135 } 136 137 if (_busy.size() > 0) { 138 for (int i = 0; i < _busy.size(); i++) { 139 ((PooledThread) _busy.get(i)).shutdown(); 140 } 141 142 Timer timer = new Timer(timeout); 143 144 while (_busy.size() != 0) { 145 try { 146 wait(timeout); 147 148 if (timer.isOver()) { 149 break; 150 } 151 } catch (InterruptedException e) { 152 return; 153 } 154 } 155 } 156 } 157 158 161 protected final Object doNewObject() throws Exception { 162 PooledThread th = (PooledThread) newThread(); 163 th.setOwner(this); 164 th.setName("[" + _name + " - " + super.getCreatedCount() + "]"); 165 th.setDaemon(_daemon); 166 th.start(); 167 168 return th; 169 } 170 171 178 protected abstract PooledThread newThread() throws Exception ; 179 } 180 | Popular Tags |