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.util.concurrent.Executor;
20 import org.eclipse.swt.widgets.Display;
21 import org.eclipse.swt.widgets.Widget;
23 public class SWTThread implements IThreadWorkQueue, Executor {
25 private final Display display;
26 private final boolean executeAsync;
28 public static IThreadWorkQueue getThreadAccess(Display display, boolean executeAsync)
30 return new SWTThread(display, executeAsync);
33 public static IThreadWorkQueue getThreadAccess(Display display)
35 return getThreadAccess(display, false);
38 public static IThreadWorkQueue getThreadAccess(Widget widget)
40 return new SWTThread(widget.getDisplay(), false);
43 public static IThreadWorkQueue getThreadAccess() {
44 return new SWTThread(Display.getDefault(), false);
47 SWTThread(Display display, boolean executeAsync)
49 this.display = display;
50 this.executeAsync = executeAsync;
54 public Thread asyncExec(Runnable runnable) {
55 // Don't accept work if the SWT thread is disposed.
56 if (display.isDisposed())
58 display.asyncExec(runnable);
59 return display.getThread();
63 public boolean syncExec(Runnable runnable) {
64 // Don't accept work if the SWT thread is disposed.
65 if (display.isDisposed())
67 if (display.getThread() == Thread.currentThread ())
70 display.syncExec(runnable);
75 public boolean currentThreadAccess() {
76 // A disposed SWT thread can never be the current thread access
77 if (display.isDisposed())
79 return display.getThread() == Thread.currentThread ();
83 public Thread getThread() {
84 // Use null to indicate disposed SWT thread.
85 if (display.isDisposed())
87 return display.getThread();
91 public String toString() {
96 public void execute(Runnable command) {
97 if (executeAsync) asyncExec(command);
98 else syncExec(command);