ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CancellableTask.java
Revision: 1.16
Committed: Fri Sep 12 15:40:10 2003 UTC (20 years, 9 months ago) by dl
Branch: MAIN
Changes since 1.15: +15 -3 lines
Log Message:
Adapt AbstractQueue changes; Conditionalize CancellableTask.reset; new TimeUnit methods

File Contents

# Content
1 /*
2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 * Expert Group and released to the public domain. Use, modify, and
4 * redistribute this code in any way without acknowledgement.
5 */
6
7 package java.util.concurrent;
8 import java.util.concurrent.atomic.*;
9 import java.util.concurrent.locks.*;
10
11 /**
12 * Base class for {@link Cancellable} {@link java.lang.Runnable}
13 * actions within the {@link Executor} framework. In addition to
14 * serving as a standalone class, this provides <tt>protected</tt>
15 * functionality that may be useful when creating customized task
16 * classes.
17 * @since 1.5
18 * @author Doug Lea
19 */
20
21 public class CancellableTask implements Cancellable, Runnable {
22 /**
23 * Holds the run-state, taking on values:
24 * null = not yet started,
25 * [some thread ref] = running,
26 * DONE = completed normally,
27 * CANCELLED = cancelled (may or may not have ever run).
28 * Transitions use atomic updates.
29 */
30 private volatile Object runner;
31
32 /**
33 * Special value for "runner" indicating task is completed
34 */
35 private static final Object DONE = new Object();
36
37 /**
38 * Special value for "runner" indicating task is cancelled
39 */
40 private static final Object CANCELLED = new Object();
41
42 private static AtomicReferenceFieldUpdater<CancellableTask, Object>
43 runnerUpdater =
44 AtomicReferenceFieldUpdater.newUpdater
45 (CancellableTask.class, Object.class, "runner");
46
47 /**
48 * The runnable underlying this task
49 */
50 private volatile Runnable runnable;
51
52 /**
53 * Creates a new CancellableTask which invokes the given
54 * <tt>Runnable</tt> when executed.
55 * @param r the runnable action
56 * @throws NullPointerException if runnable is null
57 */
58 public CancellableTask(Runnable r) {
59 if (r == null)
60 throw new NullPointerException();
61 this.runnable = r;
62 }
63
64 /**
65 * Creates a new CancellableTask without a runnable action, which
66 * must be set using <tt>setRunnable</tt> before use. This is
67 * intended for use in subclasses that must complete superclass
68 * construction before establishing the runnable action.
69 */
70 protected CancellableTask() {
71 }
72
73
74 public boolean cancel(boolean mayInterruptIfRunning) {
75 Object r = runner;
76 if (r == DONE || r == CANCELLED)
77 return false;
78
79 if (mayInterruptIfRunning &&
80 r != null &&
81 r instanceof Thread &&
82 runnerUpdater.compareAndSet(this, r, CANCELLED))
83
84 ((Thread)r).interrupt();
85 else
86 runnerUpdater.set(this, CANCELLED);
87 return true;
88 }
89
90 public boolean isCancelled() {
91 return runner == CANCELLED;
92 }
93
94 public boolean isDone() {
95 Object r = runner;
96 return r == DONE || r == CANCELLED;
97 }
98
99 /**
100 * Return the Runnable forming the basis of this task.
101 * @return the runnable action
102 * @see #setRunnable
103 */
104 protected Runnable getRunnable() {
105 return runnable;
106 }
107
108 /**
109 * Set the Runnable forming the basis of this task.
110 * @param r the runnable action
111 * @see #getRunnable
112 */
113 protected void setRunnable(Runnable r) {
114 runnable = r;
115 }
116
117 /**
118 * Set the state of this task to Cancelled.
119 */
120 protected void setCancelled() {
121 runnerUpdater.set(this, CANCELLED);
122 }
123
124 /**
125 * Set the state of this task to Done, unless already
126 * in a Cancelled state, in which Cancelled status is preserved.
127 *
128 */
129 protected void setDone() {
130 for (;;) {
131 Object r = runner;
132 if (r == DONE || r == CANCELLED)
133 return;
134 if (runnerUpdater.compareAndSet(this, r, DONE))
135 return;
136 }
137 }
138
139 /**
140 * Attempt to set the state of this task to Running, succeeding
141 * only if the state is currently NOT Done, Running, or Cancelled.
142 * @return true if successful
143 */
144 protected boolean setRunning() {
145 return runnerUpdater.compareAndSet(this, null, Thread.currentThread());
146 }
147
148 public void run() {
149 if (setRunning()) {
150 try {
151 runnable.run();
152 } finally {
153 setDone();
154 }
155 }
156 }
157
158 /**
159 * Reset the run state of this task to its initial state unless
160 * it has been cancelled. (Note that a cancelled task cannot be
161 * reset.)
162 * @return true if successful
163 */
164 protected boolean reset() {
165 for (;;) {
166 Object r = runner;
167 if (r == CANCELLED)
168 return false;
169 if (runnerUpdater.compareAndSet(this, r, null))
170 return true;
171 }
172 }
173
174 /**
175 * Implementation of Future methods under the control of a current
176 * <tt>CancellableTask</tt>, which it relies on for methods
177 * <tt>isDone</tt>, <tt>isCancelled</tt> and <tt>cancel</tt>. This
178 * class is split into an inner class to permit Future support to
179 * be mixed-in with other flavors of tasks. Normally, such a
180 * class will delegate <tt>Future</tt> <tt>get</tt> methods to the
181 * <tt>InnerCancellableFuture</tt>, and internally arrange that
182 * <tt>set</tt> methods be invoked when computations are ready.
183 *
184 * <p><b>Sample Usage</b>. Here are fragments of an example subclass.
185 * <pre>
186 * class MyFutureTask&lt;V&gt; extends CancellableTask implements Future&lt;
187 V&gt; {
188 *
189 * MyFutureTask(Callable&lt;V&gt; callable) {
190 * setRunnable(new InnerCancellableFuture&lt;V&gt;(callable));
191 * }
192 *
193 * public V get() throws InterruptedException, ExecutionException {
194 * return ((InnerCancellableFuture&lt;V&gt;)getRunnable()).get();
195 * }
196 * // (And similarly for timeout version.)
197 *
198 * void action() { // whatever action causes execution
199 * try {
200 * ((InnerCancellableFuture&lt;V&gt;)getRunnable()).set(compute());
201 * } catch (Exception ex) {
202 * ((InnerCancellableFuture&lt;V&gt;)getRunnable()).setException(ex);
203 * }
204 * }
205 * }
206 *</pre>
207 */
208 protected class InnerCancellableFuture<V> implements Future<V>, Runnable {
209 private final Callable<V> callable;
210 private final ReentrantLock lock = new ReentrantLock();
211 private final Condition accessible = lock.newCondition();
212 private V result;
213 private Throwable exception;
214
215 /**
216 * Create an InnerCancellableFuture that will execute the
217 * given callable.
218 * @param callable the function to execute
219 */
220 protected InnerCancellableFuture(Callable<V> callable) {
221 this.callable = callable;
222 }
223
224 public boolean cancel(boolean mayInterruptIfRunning) {
225 return CancellableTask.this.cancel(mayInterruptIfRunning);
226 }
227
228 public boolean isCancelled() {
229 return CancellableTask.this.isCancelled();
230 }
231
232
233 public boolean isDone() {
234 return CancellableTask.this.isDone();
235 }
236
237
238 /**
239 * Sets this Future to the results of <tt>callable.call</tt>
240 */
241 public void run() {
242 try {
243 set(callable.call());
244 } catch(Throwable ex) {
245 setException(ex);
246 }
247 }
248
249 /**
250 * Waits if necessary for the call to <tt>callable.call</tt> to
251 * complete, and then retrieves its result.
252 *
253 * @return computed result
254 * @throws CancellationException here???
255 * @throws ExecutionException if underlying computation threw an
256 * exception
257 * @throws InterruptedException if current thread was interrupted
258 * while waiting
259 */
260 public V get() throws InterruptedException, ExecutionException {
261 lock.lock();
262 try {
263 while (!isDone())
264 accessible.await();
265 if (isCancelled())
266 throw new CancellationException();
267 else if (exception != null)
268 throw new ExecutionException(exception);
269 else
270 return result;
271 } finally {
272 lock.unlock();
273 }
274 }
275
276 /**
277 * Waits if necessary for at most the given time for the call to
278 * <tt>callable.call</tt> to complete, and then retrieves its
279 * result.
280 *
281 * @param timeout the maximum time to wait
282 * @param unit the time unit of the timeout argument
283 * @return computed result
284 * @throws ExecutionException if underlying computation threw an
285 * exception
286 * @throws InterruptedException if current thread was interrupted
287 * while waiting
288 * @throws TimeoutException if the wait timed out
289 */
290 public V get(long timeout, TimeUnit unit)
291 throws InterruptedException, ExecutionException, TimeoutException {
292 lock.lock();
293 try {
294 if (!isDone()) {
295 long nanos = unit.toNanos(timeout);
296 do {
297 if (nanos <= 0)
298 throw new TimeoutException();
299 nanos = accessible.awaitNanos(nanos);
300 } while (!isDone());
301 }
302 if (isCancelled())
303 throw new CancellationException();
304 else if (exception != null)
305 throw new ExecutionException(exception);
306 else
307 return result;
308 } finally {
309 lock.unlock();
310 }
311 }
312
313 /**
314 * Sets the result of this Future to the given value.
315 * @param v the value
316 */
317 protected void set(V v) {
318 lock.lock();
319 try {
320 result = v;
321 setDone();
322 accessible.signalAll();
323 } finally {
324 lock.unlock();
325 }
326 }
327
328 /**
329 * Causes this futue to report an <tt>ExecutionException</tt>
330 * with the given throwable as its cause.
331 * @param t the cause of failure.
332 */
333 protected void setException(Throwable t) {
334 lock.lock();
335 try {
336 exception = t;
337 setDone();
338 accessible.signalAll();
339 } finally {
340 lock.unlock();
341 }
342 }
343 }
344
345 }