1 9 package org.jboss.portal.common.concurrent; 10 11 18 public class Valve 19 { 20 21 23 26 public static final int OPEN = 0; 27 28 31 public static final int CLOSING = 1; 32 33 36 public static final int CLOSED = 2; 37 38 41 private static final String [] STATE_NAMES = {"OPEN","CLOSING","CLOSED"}; 42 43 45 48 protected Object stateLock = new Object (); 49 50 53 protected int state; 54 55 58 protected int invocations = 0; 59 60 62 64 67 public Valve() 68 { 69 this(CLOSED); 70 } 71 72 77 protected Valve(int state) 78 { 79 this.state = state; 80 } 81 82 84 89 public boolean isClosed() 90 { 91 synchronized (stateLock) 92 { 93 return state != OPEN; 94 } 95 } 96 97 102 public boolean beforeInvocation() 103 { 104 synchronized (stateLock) 105 { 106 if (state != OPEN) 107 { 108 return false; 109 } 110 ++invocations; 111 } 112 return true; 113 } 114 115 118 public void afterInvocation() 119 { 120 synchronized (stateLock) 121 { 122 --invocations; 123 stateLock.notifyAll(); 124 } 125 } 126 127 130 public int getState() 131 { 132 return state; 133 } 134 135 138 public int getInvocations() 139 { 140 return invocations; 141 } 142 143 148 public void open() throws IllegalStateException 149 { 150 synchronized (stateLock) 151 { 152 if (state != CLOSED) 153 { 154 throw new IllegalStateException ("Cannot invoke open() valve in state " + STATE_NAMES[state]); 155 } 156 state = OPEN; 157 } 158 } 159 160 165 public void closing() throws IllegalStateException 166 { 167 closing(0); 168 } 169 170 175 public boolean closing(long millis) throws IllegalStateException 176 { 177 boolean interrupted = false; 178 boolean empty = false; 179 synchronized (stateLock) 180 { 181 if (state == CLOSED) 182 { 183 throw new IllegalStateException ("Cannot invoke closing() valve in state " + STATE_NAMES[state]); 184 } 185 186 state = CLOSING; 188 189 long finished = -1; 191 if (millis > 0) 192 { 193 finished = System.currentTimeMillis() + millis; 194 } 195 196 while (invocations > 0) 197 { 198 try 199 { 200 if (finished == -1) 201 { 202 stateLock.wait(); 203 } 204 else 205 { 206 long time = finished - System.currentTimeMillis(); 207 if (time > 0) 208 { 209 stateLock.wait(time); 210 } 211 else 212 { 213 break; 214 } 215 } 216 } 217 catch (InterruptedException e) 218 { 219 interrupted = true; 220 } 221 } 222 223 empty = invocations == 0; 224 } 225 226 if (interrupted) 227 { 228 Thread.currentThread().interrupt(); 229 } 230 231 return empty; 232 } 233 234 239 public void closed() throws IllegalStateException 240 { 241 synchronized (stateLock) 242 { 243 if (state != CLOSING) 244 { 245 throw new IllegalStateException ("Cannot invoke close() valve in state " + STATE_NAMES[state]); 246 } 247 state = CLOSED; 248 } 249 } 250 251 253 255 257 259 } 260 | Popular Tags |