Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 54194532e3731a7aec3df2eac527675770ab0a34 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
/*******************************************************************************
 * Copyright (c) 2007, 2009 Wind River Systems and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     Wind River Systems - initial API and implementation
 *******************************************************************************/

package org.eclipse.cdt.dsf.ui.concurrent;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import org.eclipse.cdt.dsf.concurrent.DefaultDsfExecutor;
import org.eclipse.cdt.dsf.concurrent.DsfExecutable;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;

/**
 * DSF executor which uses the display thread to run the submitted runnables 
 * and callables.  The implementation is based on the default DSF executor 
 * which still creates its own thread.  However this thread blocks when running
 * each executable in the display thread.   
 * 
 * @since 1.0
 */
public class DisplayDsfExecutor extends DefaultDsfExecutor 
{
    /**
     * Internal mapping of display objects to executors.
     */
    private static Map<Display, DisplayDsfExecutor> fExecutors = Collections.synchronizedMap( new HashMap<Display, DisplayDsfExecutor>() );
    
    /**
     * Factory method for display executors.
     * @param display Display to create an executor for.
     * @return The new (or re-used) executor.
     */
    public static DisplayDsfExecutor getDisplayDsfExecutor(Display display) {
        synchronized (fExecutors) {
            DisplayDsfExecutor executor = fExecutors.get(display);
            if (executor == null) {
                executor = new DisplayDsfExecutor(display);
                fExecutors.put(display, executor);
            }
            return executor;
        }
    }
    
    /**
     * The display class used by this executor to execute the submitted runnables. 
     */
    private final Display fDisplay;
    
	private DisplayDsfExecutor(Display display) {
		super("Display DSF Executor"); //$NON-NLS-1$
		fDisplay = display;
		fDisplay.addListener(SWT.Dispose, new Listener() {
		    public void handleEvent(Event event) {
		        if (event.type == SWT.Dispose) {
                    DisplayDsfExecutor.super.shutdownNow();
		        }
		    }
		});
	}
	
	/**
	 * Override to check if we're in the display thread rather than the helper
	 * thread of the super-class.
	 */
	@Override
	public boolean isInExecutorThread() {
	    return Thread.currentThread().equals(fDisplay.getThread());
	}
	
	/**
	 * Creates a callable wrapper, which delegates to the display to perform the 
	 * operation.  The callable blocks the executor thread while each call
	 * is executed in the display thred.
	 * @param <V> Type used in the callable.
	 * @param callable Callable to wrap.
	 * @return Wrapper callable.
	 */
	private <V> Callable<V> createSWTDispatchCallable(final Callable<V> callable) {
        // Check if executable wasn't executed already.
        if (DEBUG_EXECUTOR && callable instanceof DsfExecutable) {
            assert !((DsfExecutable)callable).getSubmitted() : "Executable was previously executed."; //$NON-NLS-1$
            ((DsfExecutable)callable).setSubmitted();
        }

	    return new Callable<V>() {
			@SuppressWarnings("unchecked")
            public V call() throws Exception {
				final Object[] v = new Object[1];
				final Throwable[] e = new Throwable[1];
				
                try {
    				fDisplay.syncExec(new Runnable() {
    					public void run() {
    						try {
    							v[0] = callable.call();
    						} catch(Throwable exception) {
    							e[0] = exception;
    						}
    					}
    				});
                } catch (SWTException swtException) {
                    if (swtException.code == SWT.ERROR_DEVICE_DISPOSED) {
                        DisplayDsfExecutor.super.shutdown();
                    }
                }

				if(e[0] instanceof RuntimeException) {
					throw (RuntimeException) e[0];
                } else if (e[0] instanceof Error) {
                    throw (Error) e[0];
				} else if(e[0] instanceof Exception) {
					throw (Exception) e[0];
                }
				
				return (V) v[0];
			}
		};
	}
	
    /**
     * Creates a runnable wrapper, which delegates to the display to perform the 
     * operation.  The runnable blocks the executor thread while each call
     * is executed in the display thred.
     * @param runnable Runnable to wrap.
     * @return Wrapper runnable.
     */
	private Runnable createSWTDispatchRunnable(final Runnable runnable) {

	    // Check if executable wasn't executed already.
        if (DEBUG_EXECUTOR && runnable instanceof DsfExecutable) {
            assert !((DsfExecutable)runnable).getSubmitted() : "Executable was previously executed."; //$NON-NLS-1$
            ((DsfExecutable)runnable).setSubmitted();
        }

	    return new Runnable() {
			public void run() {
				try {
    				fDisplay.syncExec(new Runnable() {
    					public void run() {
    					    runnable.run();
    					}
    				});
				} catch (SWTException swtException) {
				    if (swtException.code == SWT.ERROR_DEVICE_DISPOSED) {
				        DisplayDsfExecutor.super.shutdownNow();
				    }
				}
			}
		};
	}
	
	@Override
	public <V> ScheduledFuture<V> schedule(final Callable<V> callable, long delay, TimeUnit unit) {
	    if (fDisplay.isDisposed()) {
            if (!super.isShutdown()) super.shutdown();
	        throw new RejectedExecutionException("Display " + fDisplay + " is disposed."); //$NON-NLS-1$ //$NON-NLS-2$
	    }
		return super.schedule(createSWTDispatchCallable(callable), delay, unit);
	}

	@Override
	public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
        if (fDisplay.isDisposed()) {
            if (!super.isShutdown()) super.shutdown();
            throw new RejectedExecutionException("Display " + fDisplay + " is disposed."); //$NON-NLS-1$ //$NON-NLS-2$
        }
		return super.schedule(createSWTDispatchRunnable(command), delay, unit);
	}

	@Override
	public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
        if (fDisplay.isDisposed()) {
            if (!super.isShutdown()) super.shutdown();
            throw new RejectedExecutionException("Display " + fDisplay + " is disposed."); //$NON-NLS-1$ //$NON-NLS-2$
        }
		return super.scheduleAtFixedRate(createSWTDispatchRunnable(command), initialDelay, period, unit);
	}

	@Override
	public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
        if (fDisplay.isDisposed()) {
            if (!super.isShutdown()) super.shutdown();
            throw new RejectedExecutionException("Display " + fDisplay + " is disposed."); //$NON-NLS-1$ //$NON-NLS-2$
        }
		return super.scheduleWithFixedDelay(createSWTDispatchRunnable(command), initialDelay, delay, unit);
	}

	@Override
	public void execute(Runnable command) {
        if (fDisplay.isDisposed()) {
            if (!super.isShutdown()) super.shutdown();
            throw new RejectedExecutionException("Display " + fDisplay + " is disposed."); //$NON-NLS-1$ //$NON-NLS-2$
        }
		super.execute(createSWTDispatchRunnable(command));
	}

	@Override
	public <T> Future<T> submit(Callable<T> callable) {
        if (fDisplay.isDisposed()) {
            if (!super.isShutdown()) super.shutdown();
            throw new RejectedExecutionException("Display " + fDisplay + " is disposed."); //$NON-NLS-1$ //$NON-NLS-2$
        }
		return super.submit(createSWTDispatchCallable(callable));
	}

	@Override
	public <T> Future<T> submit(Runnable command, T result) {
        if (fDisplay.isDisposed()) {
            if (!super.isShutdown()) super.shutdown();
            throw new RejectedExecutionException("Display " + fDisplay + " is disposed."); //$NON-NLS-1$ //$NON-NLS-2$
        }
		return super.submit(createSWTDispatchRunnable(command), result);
	}

	@Override
	public Future<?> submit(Runnable command) {
        if (fDisplay.isDisposed()) {
            if (!super.isShutdown()) super.shutdown();
            throw new RejectedExecutionException("Display " + fDisplay + " is disposed."); //$NON-NLS-1$ //$NON-NLS-2$
        }
		return super.submit(createSWTDispatchRunnable(command));
	}
	
    /**
     * Override to prevent clients from shutting down.  The executor will be
     * shut down when the underlying display is discovered to be shut down. 
     */
	@Override
	public void shutdown() {
	}
	
    /**
     * Override to prevent clients from shutting down.  The executor will be
     * shut down when the underlying display is discovered to be shut down. 
     */
	@SuppressWarnings({ "cast", "unchecked" })
    @Override
	public List<Runnable> shutdownNow() {
	    return (List<Runnable>)Collections.EMPTY_LIST;
	}
}

Back to the top