1 6 21 22 package de.schlichtherle.awt; 23 24 import java.lang.reflect.*; 25 import java.util.logging.*; 26 27 35 public class EventQueue extends java.awt.EventQueue { 36 37 private static final byte RESET = 0, CANCELLED = 1, STARTED = 2, DONE = 3; 38 39 44 public static final void invokeAndWaitUninterruptibly(Runnable task) 45 throws InvocationTargetException { 46 try { 47 invokeAndWait(task, false, 0); 48 } catch (EventDispatchTimeoutException cannotHappen) { 49 throw new AssertionError (cannotHappen); 50 } catch (InterruptedException cannotHappen) { 51 throw new AssertionError (cannotHappen); 52 } 53 } 54 55 82 public static final void invokeAndWaitUninterruptibly( 83 Runnable task, 84 long startTimeout) 85 throws EventDispatchTimeoutException, 86 InvocationTargetException { 87 try { 88 invokeAndWait(task, false, startTimeout); 89 } catch (InterruptedException cannotHappen) { 90 throw new AssertionError (cannotHappen); 91 } 92 } 93 94 104 105 113 114 public static void invokeAndWait( 115 final Runnable task, 116 final boolean interruptibly, 117 final long startTimeout) 118 throws EventDispatchTimeoutException, 119 InterruptedException , 120 InvocationTargetException { 121 if (startTimeout < 0) 122 throw new IllegalArgumentException ("Timeout must not be negative!"); 123 124 if (isDispatchThread()) { 125 try { 126 task.run(); 127 } catch (Throwable throwable) { 128 throw new InvocationTargetException(throwable); 129 } 130 } else { class MonitoredAction implements Runnable { 132 Thread edt; 133 Throwable throwable; 134 byte status = RESET; 135 136 public void run() { 137 assert isDispatchThread(); 138 if (start()) { 139 try { 140 task.run(); 141 finished(null); 142 } catch (Throwable throwable) { 143 finished(throwable); 144 } 145 } 146 } 147 148 private synchronized boolean start() { 149 if (status == CANCELLED) 150 return false; 151 152 edt = Thread.currentThread(); 153 status = STARTED; 154 notify(); 155 return true; 156 } 157 158 private synchronized void finished(final Throwable t) { 159 throwable = t; 160 status = DONE; 161 Thread.interrupted(); notify(); 163 } 164 } 165 166 final MonitoredAction action = new MonitoredAction(); 167 invokeLater(action); 168 synchronized (action) { 169 InterruptedException interrupted = null; 170 while (action.status < DONE) { 171 try { 172 action.wait(action.status < STARTED ? startTimeout : 0); 173 if (action.status < STARTED) { 174 action.status = CANCELLED; 175 throw new EventDispatchTimeoutException(startTimeout); 176 } 177 } catch (InterruptedException ex) { 178 interrupted = ex; 179 if (interruptibly) 180 break; 181 } 182 } 183 if (interrupted != null) { 184 if (interruptibly) { 185 if (action.status >= STARTED) 186 action.edt.interrupt(); 187 throw interrupted; 188 } else { 189 Thread.currentThread().interrupt(); 190 } 191 } 192 if (action.throwable != null) 193 throw new InvocationTargetException(action.throwable); 194 } 195 } 196 } 197 } 198 | Popular Tags |