1 11 package org.eclipse.swt.widgets; 12 13 14 import org.eclipse.swt.*; 15 import org.eclipse.swt.internal.Compatibility; 16 17 34 public class Synchronizer { 35 Display display; 36 int messageCount; 37 RunnableLock [] messages; 38 Object messageLock = new Object (); 39 Thread syncThread; 40 41 46 public Synchronizer (Display display) { 47 this.display = display; 48 } 49 50 void addLast (RunnableLock lock) { 51 boolean wake = false; 52 synchronized (messageLock) { 53 if (messages == null) messages = new RunnableLock [4]; 54 if (messageCount == messages.length) { 55 RunnableLock[] newMessages = new RunnableLock [messageCount + 4]; 56 System.arraycopy (messages, 0, newMessages, 0, messageCount); 57 messages = newMessages; 58 } 59 messages [messageCount++] = lock; 60 wake = messageCount == 1; 61 } 62 if (wake) display.wakeThread (); 63 } 64 65 76 protected void asyncExec (Runnable runnable) { 77 if (runnable == null) { 78 display.wake (); 79 return; 80 } 81 addLast (new RunnableLock (runnable)); 82 } 83 84 int getMessageCount () { 85 synchronized (messageLock) { 86 return messageCount; 87 } 88 } 89 90 void releaseSynchronizer () { 91 display = null; 92 messages = null; 93 messageLock = null; 94 syncThread = null; 95 } 96 97 RunnableLock removeFirst () { 98 synchronized (messageLock) { 99 if (messageCount == 0) return null; 100 RunnableLock lock = messages [0]; 101 System.arraycopy (messages, 1, messages, 0, --messageCount); 102 messages [messageCount] = null; 103 if (messageCount == 0) { 104 if (messages.length > 64) messages = null; 105 } 106 return lock; 107 } 108 } 109 110 boolean runAsyncMessages () { 111 return runAsyncMessages (false); 112 } 113 114 boolean runAsyncMessages (boolean all) { 115 boolean run = false; 116 do { 117 RunnableLock lock = removeFirst (); 118 if (lock == null) return run; 119 run = true; 120 synchronized (lock) { 121 syncThread = lock.thread; 122 try { 123 lock.run (); 124 } catch (Throwable t) { 125 lock.throwable = t; 126 SWT.error (SWT.ERROR_FAILED_EXEC, t); 127 } finally { 128 syncThread = null; 129 lock.notifyAll (); 130 } 131 } 132 } while (all); 133 return run; 134 } 135 136 150 protected void syncExec (Runnable runnable) { 151 if (display.isValidThread ()) { 152 if (runnable != null) runnable.run (); 153 return; 154 } 155 if (runnable == null) { 156 display.wake (); 157 return; 158 } 159 RunnableLock lock = new RunnableLock (runnable); 160 163 lock.thread = Thread.currentThread(); 164 synchronized (lock) { 165 addLast (lock); 166 boolean interrupted = false; 167 while (!lock.done ()) { 168 try { 169 lock.wait (); 170 } catch (InterruptedException e) { 171 interrupted = true; 172 } 173 } 174 if (interrupted) { 175 Compatibility.interrupt(); 176 } 177 if (lock.throwable != null) { 178 SWT.error (SWT.ERROR_FAILED_EXEC, lock.throwable); 179 } 180 } 181 } 182 183 } 184 | Popular Tags |