1 |
/* |
2 |
* Written by Doug Lea with assistance from members of JCP JSR-166 |
3 |
* Expert Group and released to the public domain, as explained at |
4 |
* http://creativecommons.org/publicdomain/zero/1.0/ |
5 |
*/ |
6 |
|
7 |
package java.util.concurrent; |
8 |
import java.util.concurrent.locks.LockSupport; |
9 |
|
10 |
/** |
11 |
* A cancellable asynchronous computation. This class provides a base |
12 |
* implementation of {@link Future}, with methods to start and cancel |
13 |
* a computation, query to see if the computation is complete, and |
14 |
* retrieve the result of the computation. The result can only be |
15 |
* retrieved when the computation has completed; the {@code get} |
16 |
* methods will block if the computation has not yet completed. Once |
17 |
* the computation has completed, the computation cannot be restarted |
18 |
* or cancelled (unless the computation is invoked using |
19 |
* {@link #runAndReset}). |
20 |
* |
21 |
* <p>A {@code FutureTask} can be used to wrap a {@link Callable} or |
22 |
* {@link Runnable} object. Because {@code FutureTask} implements |
23 |
* {@code Runnable}, a {@code FutureTask} can be submitted to an |
24 |
* {@link Executor} for execution. |
25 |
* |
26 |
* <p>In addition to serving as a standalone class, this class provides |
27 |
* {@code protected} functionality that may be useful when creating |
28 |
* customized task classes. |
29 |
* |
30 |
* @since 1.5 |
31 |
* @author Doug Lea |
32 |
* @param <V> The result type returned by this FutureTask's {@code get} methods |
33 |
*/ |
34 |
public class FutureTask<V> implements RunnableFuture<V> { |
35 |
/* |
36 |
* Revision notes: This differs from previous versions of this |
37 |
* class that relied on AbstractQueuedSynchronizer, mainly to |
38 |
* avoid surprising users about retaining interrupt status during |
39 |
* cancellation races. Sync control in the current design relies |
40 |
* on a "state" field updated via CAS to track completion, along |
41 |
* with a simple Treiber stack to hold waiting threads. |
42 |
* |
43 |
* Style note: As usual, we bypass overhead of using |
44 |
* AtomicXFieldUpdaters and instead directly use Unsafe intrinsics. |
45 |
*/ |
46 |
|
47 |
/** |
48 |
* The run state of this task, initially NEW. The run state |
49 |
* transitions to a terminal state only in methods set, |
50 |
* setException, and cancel. During completion, state may take on |
51 |
* transient values of COMPLETING (while outcome is being set) or |
52 |
* INTERRUPTING (only while interrupting the runner to satisfy a |
53 |
* cancel(true)). Transitions from these intermediate to final |
54 |
* states use cheaper ordered/lazy writes because values are unique |
55 |
* and cannot be further modified. |
56 |
* |
57 |
* Possible state transitions: |
58 |
* NEW -> COMPLETING -> NORMAL |
59 |
* NEW -> COMPLETING -> EXCEPTIONAL |
60 |
* NEW -> CANCELLED |
61 |
* NEW -> INTERRUPTING -> INTERRUPTED |
62 |
*/ |
63 |
private volatile int state; |
64 |
private static final int NEW = 0; |
65 |
private static final int COMPLETING = 1; |
66 |
private static final int NORMAL = 2; |
67 |
private static final int EXCEPTIONAL = 3; |
68 |
private static final int CANCELLED = 4; |
69 |
private static final int INTERRUPTING = 5; |
70 |
private static final int INTERRUPTED = 6; |
71 |
|
72 |
/** The underlying callable; nulled out after running */ |
73 |
private Callable<V> callable; |
74 |
/** The result to return or exception to throw from get() */ |
75 |
private Object outcome; // non-volatile, protected by state reads/writes |
76 |
/** The thread running the callable; CASed during run() */ |
77 |
private volatile Thread runner; |
78 |
/** Treiber stack of waiting threads */ |
79 |
private volatile WaitNode waiters; |
80 |
|
81 |
/** |
82 |
* Returns result or throws exception for completed task. |
83 |
* |
84 |
* @param s completed state value |
85 |
*/ |
86 |
private V report(int s) throws ExecutionException { |
87 |
Object x = outcome; |
88 |
if (s == NORMAL) |
89 |
return (V)x; |
90 |
if (s >= CANCELLED) |
91 |
throw new CancellationException(); |
92 |
throw new ExecutionException((Throwable)x); |
93 |
} |
94 |
|
95 |
/** |
96 |
* Creates a {@code FutureTask} that will, upon running, execute the |
97 |
* given {@code Callable}. |
98 |
* |
99 |
* @param callable the callable task |
100 |
* @throws NullPointerException if callable is null |
101 |
*/ |
102 |
public FutureTask(Callable<V> callable) { |
103 |
if (callable == null) |
104 |
throw new NullPointerException(); |
105 |
this.callable = callable; |
106 |
this.state = NEW; |
107 |
} |
108 |
|
109 |
/** |
110 |
* Creates a {@code FutureTask} that will, upon running, execute the |
111 |
* given {@code Runnable}, and arrange that {@code get} will return the |
112 |
* given result on successful completion. |
113 |
* |
114 |
* @param runnable the runnable task |
115 |
* @param result the result to return on successful completion. If |
116 |
* you don't need a particular result, consider using |
117 |
* constructions of the form: |
118 |
* {@code Future<?> f = new FutureTask<Void>(runnable, null)} |
119 |
* @throws NullPointerException if runnable is null |
120 |
*/ |
121 |
public FutureTask(Runnable runnable, V result) { |
122 |
this.callable = Executors.callable(runnable, result); |
123 |
this.state = NEW; |
124 |
} |
125 |
|
126 |
public boolean isCancelled() { |
127 |
return state >= CANCELLED; |
128 |
} |
129 |
|
130 |
public boolean isDone() { |
131 |
return state != NEW; |
132 |
} |
133 |
|
134 |
public boolean cancel(boolean mayInterruptIfRunning) { |
135 |
if (state != NEW) |
136 |
return false; |
137 |
if (mayInterruptIfRunning) { |
138 |
if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, INTERRUPTING)) |
139 |
return false; |
140 |
Thread t = runner; |
141 |
if (t != null) |
142 |
t.interrupt(); |
143 |
UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED); // final state |
144 |
} |
145 |
else if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, CANCELLED)) |
146 |
return false; |
147 |
finishCompletion(); |
148 |
return true; |
149 |
} |
150 |
|
151 |
/** |
152 |
* @throws CancellationException {@inheritDoc} |
153 |
*/ |
154 |
public V get() throws InterruptedException, ExecutionException { |
155 |
int s = state; |
156 |
return report(s <= COMPLETING ? awaitDone(false, 0L) : s); |
157 |
} |
158 |
|
159 |
/** |
160 |
* @throws CancellationException {@inheritDoc} |
161 |
*/ |
162 |
public V get(long timeout, TimeUnit unit) |
163 |
throws InterruptedException, ExecutionException, TimeoutException { |
164 |
long nanos = unit.toNanos(timeout); |
165 |
int s = state; |
166 |
if (s <= COMPLETING && |
167 |
(s = awaitDone(true, nanos)) <= COMPLETING) |
168 |
throw new TimeoutException(); |
169 |
return report(s); |
170 |
} |
171 |
|
172 |
/** |
173 |
* Protected method invoked when this task transitions to state |
174 |
* {@code isDone} (whether normally or via cancellation). The |
175 |
* default implementation does nothing. Subclasses may override |
176 |
* this method to invoke completion callbacks or perform |
177 |
* bookkeeping. Note that you can query status inside the |
178 |
* implementation of this method to determine whether this task |
179 |
* has been cancelled. |
180 |
*/ |
181 |
protected void done() { } |
182 |
|
183 |
/** |
184 |
* Sets the result of this future to the given value unless |
185 |
* this future has already been set or has been cancelled. |
186 |
* |
187 |
* <p>This method is invoked internally by the {@link #run} method |
188 |
* upon successful completion of the computation. |
189 |
* |
190 |
* @param v the value |
191 |
*/ |
192 |
protected void set(V v) { |
193 |
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) { |
194 |
outcome = v; |
195 |
UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state |
196 |
finishCompletion(); |
197 |
} |
198 |
} |
199 |
|
200 |
/** |
201 |
* Causes this future to report an {@link ExecutionException} |
202 |
* with the given throwable as its cause, unless this future has |
203 |
* already been set or has been cancelled. |
204 |
* |
205 |
* <p>This method is invoked internally by the {@link #run} method |
206 |
* upon failure of the computation. |
207 |
* |
208 |
* @param t the cause of failure |
209 |
*/ |
210 |
protected void setException(Throwable t) { |
211 |
if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) { |
212 |
outcome = t; |
213 |
UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state |
214 |
finishCompletion(); |
215 |
} |
216 |
} |
217 |
|
218 |
public void run() { |
219 |
if (state == NEW && |
220 |
UNSAFE.compareAndSwapObject(this, runnerOffset, |
221 |
null, Thread.currentThread())) { |
222 |
Callable<V> c = callable; |
223 |
if (c != null && state == NEW) { |
224 |
V result = null; |
225 |
boolean ran = false; |
226 |
try { |
227 |
result = c.call(); |
228 |
ran = true; |
229 |
} catch (Throwable ex) { |
230 |
setException(ex); |
231 |
} |
232 |
if (ran) |
233 |
set(result); |
234 |
callable = null; // null out upon use to reduce footprint |
235 |
} |
236 |
runner = null; |
237 |
if (state >= INTERRUPTING) { |
238 |
while (state == INTERRUPTING) |
239 |
Thread.yield(); // wait out pending interrupt |
240 |
Thread.interrupted(); // clear interrupt from cancel(true) |
241 |
} |
242 |
} |
243 |
} |
244 |
|
245 |
/** |
246 |
* Executes the computation without setting its result, and then |
247 |
* resets this future to initial state, failing to do so if the |
248 |
* computation encounters an exception or is cancelled. This is |
249 |
* designed for use with tasks that intrinsically execute more |
250 |
* than once. |
251 |
* |
252 |
* @return true if successfully run and reset |
253 |
*/ |
254 |
protected boolean runAndReset() { |
255 |
boolean rerun = false; // true if this task can be re-run |
256 |
if (state == NEW && |
257 |
UNSAFE.compareAndSwapObject(this, runnerOffset, |
258 |
null, Thread.currentThread())) { |
259 |
Callable<V> c = callable; |
260 |
if (c != null && state == NEW) { |
261 |
try { |
262 |
c.call(); // don't set result |
263 |
rerun = true; |
264 |
} catch (Throwable ex) { |
265 |
setException(ex); |
266 |
} |
267 |
} |
268 |
runner = null; |
269 |
int s = state; |
270 |
if (s != NEW) { |
271 |
rerun = false; |
272 |
if (s >= INTERRUPTING) { |
273 |
while (state == INTERRUPTING) |
274 |
Thread.yield(); // wait out pending interrupt |
275 |
Thread.interrupted(); // clear interrupt from cancel(true) |
276 |
} |
277 |
} |
278 |
if (!rerun) |
279 |
callable = null; |
280 |
} |
281 |
return rerun; |
282 |
} |
283 |
|
284 |
/** |
285 |
* Simple linked list nodes to record waiting threads in a Treiber |
286 |
* stack. See other classes such as Phaser and SynchronousQueue |
287 |
* for more detailed explanation. |
288 |
*/ |
289 |
static final class WaitNode { |
290 |
volatile Thread thread; |
291 |
volatile WaitNode next; |
292 |
WaitNode() { thread = Thread.currentThread(); } |
293 |
} |
294 |
|
295 |
/** |
296 |
* Removes and signals all waiting threads, and |
297 |
* invokes done(); |
298 |
*/ |
299 |
private void finishCompletion() { |
300 |
WaitNode q; |
301 |
while ((q = waiters) != null) { |
302 |
if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) { |
303 |
for (;;) { |
304 |
Thread t = q.thread; |
305 |
if (t != null) { |
306 |
q.thread = null; |
307 |
LockSupport.unpark(t); |
308 |
} |
309 |
WaitNode next = q.next; |
310 |
if (next == null) |
311 |
break; |
312 |
q.next = null; // unlink to help gc |
313 |
q = next; |
314 |
} |
315 |
break; |
316 |
} |
317 |
} |
318 |
done(); |
319 |
} |
320 |
|
321 |
/** |
322 |
* Awaits completion or aborts on interrupt or timeout. |
323 |
* |
324 |
* @param timed true if use timed waits |
325 |
* @param nanos time to wait, if timed |
326 |
* @return state upon completion |
327 |
*/ |
328 |
private int awaitDone(boolean timed, long nanos) |
329 |
throws InterruptedException { |
330 |
long last = timed ? System.nanoTime() : 0L; |
331 |
WaitNode q = null; |
332 |
boolean queued = false; |
333 |
for (;;) { |
334 |
if (Thread.interrupted()) { |
335 |
removeWaiter(q); |
336 |
throw new InterruptedException(); |
337 |
} |
338 |
|
339 |
int s = state; |
340 |
if (s > COMPLETING) { |
341 |
if (q != null) |
342 |
q.thread = null; |
343 |
return s; |
344 |
} |
345 |
else if (q == null) |
346 |
q = new WaitNode(); |
347 |
else if (!queued) |
348 |
queued = UNSAFE.compareAndSwapObject(this, waitersOffset, |
349 |
q.next = waiters, q); |
350 |
else if (timed) { |
351 |
long now = System.nanoTime(); |
352 |
if ((nanos -= (now - last)) <= 0L) { |
353 |
removeWaiter(q); |
354 |
return state; |
355 |
} |
356 |
last = now; |
357 |
LockSupport.parkNanos(this, nanos); |
358 |
} |
359 |
else |
360 |
LockSupport.park(this); |
361 |
} |
362 |
} |
363 |
|
364 |
/** |
365 |
* Tries to unlink a timed-out or interrupted wait node to avoid |
366 |
* accumulating garbage. Internal nodes are simply unspliced |
367 |
* without CAS since it is harmless if they are traversed anyway |
368 |
* by releasers. To avoid effects of unsplicing from already |
369 |
* removed nodes, the list is retraversed until no cancelled nodes |
370 |
* are found. This is slow when there are a lot of nodes, but we |
371 |
* don't expect lists to be long enough to outweigh |
372 |
* higher-overhead schemes. |
373 |
*/ |
374 |
private void removeWaiter(WaitNode node) { |
375 |
if (node != null) { |
376 |
node.thread = null; |
377 |
for (WaitNode pred = null, q = waiters; q != null;) { |
378 |
WaitNode next = q.next; |
379 |
if (q.thread != null) { |
380 |
pred = q; |
381 |
q = next; |
382 |
} |
383 |
else { |
384 |
if (pred != null) |
385 |
pred.next = next; |
386 |
else |
387 |
UNSAFE.compareAndSwapObject(this, waitersOffset, |
388 |
q, next); |
389 |
pred = null; // restart until clean sweep |
390 |
q = waiters; |
391 |
} |
392 |
} |
393 |
} |
394 |
} |
395 |
|
396 |
// Unsafe mechanics |
397 |
private static final sun.misc.Unsafe UNSAFE; |
398 |
private static final long stateOffset; |
399 |
private static final long runnerOffset; |
400 |
private static final long waitersOffset; |
401 |
static { |
402 |
try { |
403 |
UNSAFE = sun.misc.Unsafe.getUnsafe(); |
404 |
Class<?> k = FutureTask.class; |
405 |
stateOffset = UNSAFE.objectFieldOffset |
406 |
(k.getDeclaredField("state")); |
407 |
runnerOffset = UNSAFE.objectFieldOffset |
408 |
(k.getDeclaredField("runner")); |
409 |
waitersOffset = UNSAFE.objectFieldOffset |
410 |
(k.getDeclaredField("waiters")); |
411 |
} catch (Exception e) { |
412 |
throw new Error(e); |
413 |
} |
414 |
} |
415 |
|
416 |
} |