1 17 18 package EDU.oswego.cs.dl.util.concurrent; 19 20 39 public class QueuedExecutor extends ThreadFactoryUser implements Executor { 40 41 42 43 44 protected Thread thread_; 45 46 47 protected static Runnable ENDTASK = new Runnable () { public void run() {} }; 48 49 50 protected volatile boolean shutdown_; 52 58 public synchronized Thread getThread() { 59 return thread_; 60 } 61 62 63 protected synchronized void clearThread() { 64 thread_ = null; 65 } 66 67 68 69 protected final Channel queue_; 70 71 72 79 protected class RunLoop implements Runnable { 80 public void run() { 81 try { 82 while (!shutdown_) { 83 Runnable task = (Runnable )(queue_.take()); 84 if (task == ENDTASK) { 85 shutdown_ = true; 86 break; 87 } 88 else if (task != null) { 89 task.run(); 90 task = null; 91 } 92 else 93 break; 94 } 95 } 96 catch (InterruptedException ex) {} finally { 98 clearThread(); 99 } 100 } 101 } 102 103 protected final RunLoop runLoop_; 104 105 106 116 117 public QueuedExecutor(Channel queue) { 118 queue_ = queue; 119 runLoop_ = new RunLoop(); 120 } 121 122 127 128 public QueuedExecutor() { 129 this(new BoundedLinkedQueue()); 130 } 131 132 138 139 public synchronized void restart() { 140 if (thread_ == null && !shutdown_) { 141 thread_ = threadFactory_.newThread(runLoop_); 142 thread_.start(); 143 } 144 } 145 146 147 156 public void execute(Runnable command) throws InterruptedException { 157 restart(); 158 queue_.put(command); 159 } 160 161 170 public synchronized void shutdownAfterProcessingCurrentlyQueuedTasks() { 171 if (!shutdown_) { 172 try { queue_.put(ENDTASK); } 173 catch (InterruptedException ex) { 174 Thread.currentThread().interrupt(); 175 } 176 } 177 } 178 179 180 185 public synchronized void shutdownAfterProcessingCurrentTask() { 186 shutdown_ = true; 187 try { 188 while (queue_.poll(0) != null) ; queue_.put(ENDTASK); 190 } 191 catch (InterruptedException ex) { 192 Thread.currentThread().interrupt(); 193 } 194 } 195 196 197 205 public synchronized void shutdownNow() { 206 shutdown_ = true; 207 Thread t = thread_; 208 if (t != null) 209 t.interrupt(); 210 shutdownAfterProcessingCurrentTask(); 211 } 212 } 213 | Popular Tags |