Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: a6cddd29d970d3d3ee2c361e7d106558c4aa617f (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
/*****************************************************************************
 * Copyright (c) 2014 Christian W. Damus 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:
 *   Christian W. Damus - Initial API and implementation
 *   
 *****************************************************************************/

package org.eclipse.papyrus.junit.utils;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.RunnableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;

import com.google.common.collect.ImmutableList;

/**
 * A convenient {@link ExecutorService} implementation for test cases where we want to control
 * when asynchronous tasks run.
 */
public class SynchronousExecutorService extends AbstractExecutorService {

	/**
	 * A runnable to post to me to cause me to run all pending tasks. This lets the caller
	 * synchronize with me, to run and/or wait for all tasks up to that point.
	 * 
	 * @see #flush()
	 */
	public static final Runnable FLUSH = new Runnable() {
		public void run() {
			// Pass
		}
	};

	private final AtomicBoolean isShutdown = new AtomicBoolean();
	private final ConcurrentLinkedQueue<Runnable> queue = new ConcurrentLinkedQueue<Runnable>();

	private final Lock lock = new ReentrantLock();
	private final Condition done = lock.newCondition();

	/**
	 * Constructor.
	 */
	public SynchronousExecutorService() {
		super();
	}

	public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
		lock.lockInterruptibly();
		try {
			long now = System.currentTimeMillis();
			long deadline = now + unit.toMillis(timeout);
			while (!isTerminated()) {
				if (done.await(deadline - now, TimeUnit.MILLISECONDS)) {
					break;
				}
				now = System.currentTimeMillis();
				if (now >= deadline) {
					break;
				}
			}
		} finally {
			lock.unlock();
		}

		return isTerminated();
	}

	public boolean isShutdown() {
		return isShutdown.get();
	}

	public boolean isTerminated() {
		return isShutdown() && queue.isEmpty();
	}

	public void shutdown() {
		if (isShutdown.compareAndSet(false, true)) {
			queue.clear();
		}
	}

	public List<Runnable> shutdownNow() {
		List<Runnable> result;

		lock.lock();
		try {
			if (isShutdown.compareAndSet(false, true)) {
				result = ImmutableList.copyOf(queue);
				queue.clear();
				done.signalAll();
			} else {
				result = Collections.emptyList();
			}
		} finally {
			lock.unlock();
		}

		return result;
	}

	public void execute(Runnable command) {
		final boolean flush = isFlush(command);

		lock.lock();
		try {
			if (isShutdown()) {
				throw new RejectedExecutionException("executor is shut down");
			}

			// Even if it's FLUSH, enqueue it because somebody may be synchronizing on a Future wrapping it
			queue.add(command);
		} finally {
			lock.unlock();
		}

		if (flush) {
			flush();
		}
	}

	public void flush() {
		lock.lock();
		try {
			for (Runnable next = queue.poll(); next != null; next = queue.poll()) {
				lock.unlock();

				try {
					next.run();
				} catch (Exception e) {
					final String bsn = "org.eclipse.papyrus.junit.utils";
					IStatus status = new Status(IStatus.ERROR, bsn, "Uncaught exception in async runnable.", e);
					Platform.getLog(Platform.getBundle(bsn)).log(status);
				} finally {
					lock.lock();
				}
			}

			if (isShutdown()) {
				done.signalAll();
			}
		} finally {
			lock.unlock();
		}
	}

	@Override
	protected <T> RunnableFuture<T> newTaskFor(Runnable task, T value) {
		return new MyFutureTask<T>(task, value);
	}

	boolean isFlush(Runnable task) {
		return (task == FLUSH) || ((task instanceof MyFutureTask<?>) && ((MyFutureTask<?>) task).task == FLUSH);
	}

	//
	// Nested types
	//

	private static class MyFutureTask<V> extends FutureTask<V> {
		final Runnable task;

		MyFutureTask(Runnable task, V value) {
			super(task, value);

			this.task = task;
		}
	}
}

Back to the top