1 30 31 32 package org.hsqldb.lib; 33 34 43 public class HsqlTaskQueue { 44 45 46 protected Thread taskRunnerThread; 47 48 49 protected static final Runnable SHUTDOWNTASK = new Runnable () { 50 public void run() {} 51 }; 52 53 58 protected volatile boolean isShutdown; 59 60 public synchronized Thread getTaskRunnerThread() { 61 return taskRunnerThread; 62 } 63 64 protected synchronized void clearThread() { 65 taskRunnerThread = null; 66 } 67 68 protected final HsqlDeque queue = new HsqlDeque(); 69 70 protected class TaskRunner implements Runnable { 71 72 public void run() { 73 74 Runnable task; 75 76 try { 77 while (!isShutdown) { 78 synchronized (queue) { 79 task = (Runnable ) queue.getFirst(); 80 } 81 82 if (task == SHUTDOWNTASK) { 83 isShutdown = true; 84 85 synchronized (queue) { 86 queue.clear(); 87 } 88 89 break; 90 } else if (task != null) { 91 task.run(); 92 93 task = null; 94 } else { 95 break; 96 } 97 } 98 } finally { 99 clearThread(); 100 } 101 } 102 } 103 104 protected final TaskRunner taskRunner = new TaskRunner(); 105 106 public HsqlTaskQueue() {} 107 108 public boolean isShutdown() { 109 return isShutdown; 110 } 111 112 public synchronized void restart() { 113 114 if (taskRunnerThread == null &&!isShutdown) { 115 taskRunnerThread = new Thread (taskRunner); 116 117 taskRunnerThread.start(); 118 } 119 } 120 121 public void execute(Runnable command) throws RuntimeException { 122 123 if (!isShutdown) { 124 synchronized (queue) { 125 queue.addLast(command); 126 } 127 128 restart(); 129 } 130 } 131 132 public synchronized void shutdownAfterQueued() { 133 134 if (!isShutdown) { 135 synchronized (queue) { 136 queue.addLast(SHUTDOWNTASK); 137 } 138 } 139 } 140 141 public synchronized void shutdownAfterCurrent() { 142 143 isShutdown = true; 144 145 synchronized (queue) { 146 queue.clear(); 147 queue.addLast(SHUTDOWNTASK); 148 } 149 } 150 151 public synchronized void shutdownImmediately() { 152 153 isShutdown = true; 154 155 if (taskRunnerThread != null) { 156 taskRunnerThread.interrupt(); 157 } 158 159 synchronized (queue) { 160 queue.clear(); 161 queue.addLast(SHUTDOWNTASK); 162 } 163 } 164 } 165 | Popular Tags |