1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
14 * @author Toni Kalajainen
16 package org.simantics.utils.threads;
18 import java.awt.EventQueue;
19 import java.awt.Toolkit;
20 import java.lang.reflect.Field;
21 import java.lang.reflect.InvocationTargetException;
22 import java.util.List;
23 import java.util.concurrent.AbstractExecutorService;
24 import java.util.concurrent.Executor;
25 import java.util.concurrent.TimeUnit;
27 import javax.swing.SwingUtilities;
30 public class AWTThread extends AbstractExecutorService implements IThreadWorkQueue, Executor {
32 public static AWTThread INSTANCE = new AWTThread();
34 public static IThreadWorkQueue getThreadAccess()
42 dispatchThread = getDispatchThreadField();
45 private Field getDispatchThreadField()
48 Field f = EventQueue.class.getDeclaredField("dispatchThread");
49 f.setAccessible(true);
51 } catch (SecurityException e) {
52 throw new RuntimeException(e);
53 } catch (NoSuchFieldException e) {
54 throw new RuntimeException(e);
59 public Thread asyncExec(Runnable runnable) {
60 EventQueue eq = Toolkit.getDefaultToolkit().getSystemEventQueue();
61 EventQueue.invokeLater(runnable);
63 return (Thread) dispatchThread.get(eq);
64 } catch (IllegalArgumentException e1) {
65 throw new RuntimeException(e1);
66 } catch (IllegalAccessException e1) {
67 throw new RuntimeException(e1);
72 public boolean syncExec(Runnable runnable) {
73 if (EventQueue.isDispatchThread())
80 SwingUtilities.invokeAndWait(runnable);
82 } catch (InterruptedException e) {
83 throw new RuntimeException(e);
84 } catch (InvocationTargetException e) {
85 throw new RuntimeException(e.getCause());
90 public boolean currentThreadAccess() {
91 return EventQueue.isDispatchThread();
95 public Thread getThread() {
96 EventQueue eq = Toolkit.getDefaultToolkit().getSystemEventQueue();
98 return (Thread) dispatchThread.get(eq);
99 } catch (IllegalArgumentException e1) {
100 throw new RuntimeException(e1);
101 } catch (IllegalAccessException e1) {
102 throw new RuntimeException(e1);
106 public String toString() {
111 public void execute(Runnable command) {
112 EventQueue.invokeLater(command);
116 public void shutdown() {
120 public List<Runnable> shutdownNow() {
125 public boolean isShutdown() {
130 public boolean isTerminated() {
135 public boolean awaitTermination(long timeout, TimeUnit unit)
136 throws InterruptedException {