ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/CancellableTask.java
Revision: 1.11
Committed: Fri Aug 8 20:05:07 2003 UTC (20 years, 9 months ago) by tim
Branch: MAIN
Changes since 1.10: +6 -12 lines
Log Message:
Scrunched catch, finally, else clauses.

File Contents

# User Rev Content
1 dl 1.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 dl 1.6 import java.util.concurrent.locks.*;
10 dl 1.1
11     /**
12     * Base class for cancellable actions running in the Executor
13     * framework. In addition to serving as a standalone class, this
14     * provides <tt>protected</tt> functionality that may be useful when
15     * creating customized task classes.
16 dl 1.5 * @since 1.5
17     * @author Doug Lea
18 dl 1.1 */
19    
20     public class CancellableTask implements Cancellable, Runnable {
21     /**
22     * Holds the run-state, taking on values:
23     * null = not yet started,
24     * [some thread ref] = running,
25     * DONE = completed normally,
26     * CANCELLED = cancelled (may or may not have ever run).
27     * Transitions use atomic updates.
28     */
29     private volatile Object runner;
30    
31 dl 1.5 /**
32 dl 1.1 * Special value for "runner" indicating task is completed
33     */
34     private static final Object DONE = new Object();
35    
36 dl 1.5 /**
37 dl 1.1 * Special value for "runner" indicating task is cancelled
38     */
39     private static final Object CANCELLED = new Object();
40    
41     private static AtomicReferenceFieldUpdater<CancellableTask, Object>
42 dl 1.9 runnerUpdater =
43     AtomicReferenceFieldUpdater.newUpdater
44     (CancellableTask.class, Object.class, "runner");
45 dl 1.1
46     /**
47     * The runnable underlying this task
48     */
49     private volatile Runnable runnable;
50    
51     /**
52 brian 1.4 * Creates a new CancellableTask which invokes the given
53     * <tt>Runnable</tt> when executed.
54 dl 1.5 * @param r the runnable action
55 dl 1.1 */
56     public CancellableTask(Runnable r) {
57     this.runnable = r;
58     }
59    
60     /**
61     * Creates a new CancellableTask without a runnable action, which
62     * must be set using <tt>setRunnable</tt> before use. This is
63     * intended for use in subclasses that must complete superclass
64     * construction beofre establishing the runnable action.
65     */
66     protected CancellableTask() {
67     }
68    
69    
70     public boolean cancel(boolean mayInterruptIfRunning) {
71     Object r = runner;
72     if (r == DONE || r == CANCELLED)
73     return false;
74    
75     if (mayInterruptIfRunning &&
76     r != null &&
77     r instanceof Thread &&
78 dl 1.3 runnerUpdater.compareAndSet(this, r, CANCELLED))
79 dl 1.1
80     ((Thread)r).interrupt();
81 dl 1.3 else
82 dl 1.1 runnerUpdater.set(this, CANCELLED);
83     return true;
84     }
85    
86     public boolean isCancelled() {
87     return runner == CANCELLED;
88     }
89    
90     public boolean isDone() {
91     Object r = runner;
92     return r == DONE || r == CANCELLED;
93     }
94    
95     /**
96     * Return the Runnable forming the basis of this task.
97 dl 1.5 * @return the runnable action
98 tim 1.10 * @see #setRunnable
99 dl 1.1 */
100     protected Runnable getRunnable() {
101     return runnable;
102     }
103    
104     /**
105     * Set the Runnable forming the basis of this task.
106 dl 1.5 * @param r the runnable action
107 tim 1.10 * @see #getRunnable
108 dl 1.1 */
109     protected void setRunnable(Runnable r) {
110     runnable = r;
111     }
112    
113     /**
114 tim 1.10 * Set the state of this task to Cancelled.
115 dl 1.1 */
116     protected void setCancelled() {
117     runnerUpdater.set(this, CANCELLED);
118     }
119    
120     /**
121     * Set the state of this task to Done, unless already
122     * in a Cancelled state, in which Cancelled status is preserved.
123     *
124     */
125     protected void setDone() {
126     for (;;) {
127     Object r = runner;
128     if (r == DONE || r == CANCELLED)
129     return;
130     if (runnerUpdater.compareAndSet(this, r, DONE))
131     return;
132     }
133     }
134    
135     /**
136     * Attempt to set the state of this task to Running, succeeding
137     * only if the state is currently NOT Done, Running, or Cancelled.
138 dl 1.2 * @return true if successful
139 dl 1.1 */
140     protected boolean setRunning() {
141     return runnerUpdater.compareAndSet(this, null, Thread.currentThread());
142     }
143    
144     public void run() {
145     if (setRunning()) {
146     try {
147     runnable.run();
148 tim 1.11 } finally {
149 dl 1.1 setDone();
150     }
151     }
152     }
153    
154     /**
155     * Implementation of Future methods under the control of a current
156     * CancellableTask. This is split into an inner class to permit
157     * Future support to be mixed-in with other flavors of tasks.
158     */
159     protected class InnerCancellableFuture<V> implements Future<V>, Runnable {
160     private final Callable<V> callable;
161     private final ReentrantLock lock = new ReentrantLock();
162     private final Condition accessible = lock.newCondition();
163     private V result;
164     private Throwable exception;
165 dl 1.5
166     /**
167     * Create an InnerCancellableFuture that will execute the
168     * given callable.
169     * @param callable the function to execute
170     */
171 dl 1.1 protected InnerCancellableFuture(Callable<V> callable) {
172     this.callable = callable;
173     }
174    
175     public boolean isDone() {
176     return CancellableTask.this.isDone();
177     }
178    
179     public void run() {
180     try {
181     set(callable.call());
182 tim 1.11 } catch(Throwable ex) {
183 dl 1.1 setException(ex);
184     }
185     }
186    
187     public V get() throws InterruptedException, ExecutionException {
188     lock.lock();
189     try {
190     while (!isDone())
191     accessible.await();
192     if (isCancelled())
193     throw new CancellationException();
194     else if (exception != null)
195     throw new ExecutionException(exception);
196     else
197     return result;
198 tim 1.11 } finally {
199 dl 1.1 lock.unlock();
200     }
201     }
202    
203     public V get(long timeout, TimeUnit unit)
204     throws InterruptedException, ExecutionException, TimeoutException {
205     lock.lock();
206     try {
207     if (!isDone()) {
208     long nanos = unit.toNanos(timeout);
209     do {
210     if (nanos <= 0)
211     throw new TimeoutException();
212     nanos = accessible.awaitNanos(nanos);
213     } while (!isDone());
214     }
215     if (isCancelled())
216     throw new CancellationException();
217     else if (exception != null)
218     throw new ExecutionException(exception);
219     else
220     return result;
221 tim 1.11 } finally {
222 dl 1.1 lock.unlock();
223     }
224     }
225    
226     protected void set(V v) {
227     lock.lock();
228     try {
229     result = v;
230     setDone();
231     accessible.signalAll();
232 tim 1.11 } finally {
233 dl 1.1 lock.unlock();
234     }
235     }
236    
237     protected void setException(Throwable t) {
238     lock.lock();
239     try {
240     exception = t;
241     setDone();
242     accessible.signalAll();
243 tim 1.11 } finally {
244 dl 1.1 lock.unlock();
245     }
246     }
247     }
248    
249     }