1 /* 2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 3 * 4 * This code is free software; you can redistribute it and/or modify it 5 * under the terms of the GNU General Public License version 2 only, as 6 * published by the Free Software Foundation. Oracle designates this 7 * particular file as subject to the "Classpath" exception as provided 8 * by Oracle in the LICENSE file that accompanied this code. 9 * 10 * This code is distributed in the hope that it will be useful, but WITHOUT 11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 13 * version 2 for more details (a copy is included in the LICENSE file that 14 * accompanied this code). 15 * 16 * You should have received a copy of the GNU General Public License version 17 * 2 along with this work; if not, write to the Free Software Foundation, 18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 19 * 20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 21 * or visit www.oracle.com if you need additional information or have any 22 * questions. 23 */ 24 25 /* 26 * This file is available under and governed by the GNU General Public 27 * License version 2 only, as published by the Free Software Foundation. 28 * However, the following notice accompanied the original version of this 29 * file: 30 * 31 * Written by Doug Lea with assistance from members of JCP JSR-166 32 * Expert Group and released to the public domain, as explained at 33 * http://creativecommons.org/publicdomain/zero/1.0/ 34 */ 35 36 package java.util.concurrent; 37 38 import java.lang.invoke.MethodHandles; 39 import java.lang.invoke.VarHandle; 40 import java.util.concurrent.locks.LockSupport; 41 42 /** 43 * A cancellable asynchronous computation. This class provides a base 44 * implementation of {@link Future}, with methods to start and cancel 45 * a computation, query to see if the computation is complete, and 46 * retrieve the result of the computation. The result can only be 47 * retrieved when the computation has completed; the {@code get} 48 * methods will block if the computation has not yet completed. Once 49 * the computation has completed, the computation cannot be restarted 50 * or cancelled (unless the computation is invoked using 51 * {@link #runAndReset}). 52 * 53 * <p>A {@code FutureTask} can be used to wrap a {@link Callable} or 54 * {@link Runnable} object. Because {@code FutureTask} implements 55 * {@code Runnable}, a {@code FutureTask} can be submitted to an 56 * {@link Executor} for execution. 57 * 58 * <p>In addition to serving as a standalone class, this class provides 59 * {@code protected} functionality that may be useful when creating 60 * customized task classes. 61 * 62 * @since 1.5 63 * @author Doug Lea 64 * @param <V> The result type returned by this FutureTask's {@code get} methods 65 */ 66 public class FutureTask<V> implements RunnableFuture<V> { 67 /* 68 * Revision notes: This differs from previous versions of this 69 * class that relied on AbstractQueuedSynchronizer, mainly to 70 * avoid surprising users about retaining interrupt status during 71 * cancellation races. Sync control in the current design relies 72 * on a "state" field updated via CAS to track completion, along 73 * with a simple Treiber stack to hold waiting threads. 74 */ 75 76 /** 77 * The run state of this task, initially NEW. The run state 78 * transitions to a terminal state only in methods set, 79 * setException, and cancel. During completion, state may take on 80 * transient values of COMPLETING (while outcome is being set) or 81 * INTERRUPTING (only while interrupting the runner to satisfy a 82 * cancel(true)). Transitions from these intermediate to final 83 * states use cheaper ordered/lazy writes because values are unique 84 * and cannot be further modified. 85 * 86 * Possible state transitions: 87 * NEW -> COMPLETING -> NORMAL 88 * NEW -> COMPLETING -> EXCEPTIONAL 89 * NEW -> CANCELLED 90 * NEW -> INTERRUPTING -> INTERRUPTED 91 */ 92 private volatile int state; 93 private static final int NEW = 0; 94 private static final int COMPLETING = 1; 95 private static final int NORMAL = 2; 96 private static final int EXCEPTIONAL = 3; 97 private static final int CANCELLED = 4; 98 private static final int INTERRUPTING = 5; 99 private static final int INTERRUPTED = 6; 100 101 /** The underlying callable; nulled out after running */ 102 private Callable<V> callable; 103 /** The result to return or exception to throw from get() */ 104 private Object outcome; // non-volatile, protected by state reads/writes 105 /** The thread running the callable; CASed during run() */ 106 private volatile Thread runner; 107 /** Treiber stack of waiting threads */ 108 private volatile WaitNode waiters; 109 110 /** 111 * Returns result or throws exception for completed task. 112 * 113 * @param s completed state value 114 */ 115 @SuppressWarnings("unchecked") report(int s)116 private V report(int s) throws ExecutionException { 117 Object x = outcome; 118 if (s == NORMAL) 119 return (V)x; 120 if (s >= CANCELLED) 121 throw new CancellationException(); 122 throw new ExecutionException((Throwable)x); 123 } 124 125 /** 126 * Creates a {@code FutureTask} that will, upon running, execute the 127 * given {@code Callable}. 128 * 129 * @param callable the callable task 130 * @throws NullPointerException if the callable is null 131 */ FutureTask(Callable<V> callable)132 public FutureTask(Callable<V> callable) { 133 if (callable == null) 134 throw new NullPointerException(); 135 this.callable = callable; 136 this.state = NEW; // ensure visibility of callable 137 } 138 139 /** 140 * Creates a {@code FutureTask} that will, upon running, execute the 141 * given {@code Runnable}, and arrange that {@code get} will return the 142 * given result on successful completion. 143 * 144 * @param runnable the runnable task 145 * @param result the result to return on successful completion. If 146 * you don't need a particular result, consider using 147 * constructions of the form: 148 * {@code Future<?> f = new FutureTask<Void>(runnable, null)} 149 * @throws NullPointerException if the runnable is null 150 */ FutureTask(Runnable runnable, V result)151 public FutureTask(Runnable runnable, V result) { 152 this.callable = Executors.callable(runnable, result); 153 this.state = NEW; // ensure visibility of callable 154 } 155 isCancelled()156 public boolean isCancelled() { 157 return state >= CANCELLED; 158 } 159 isDone()160 public boolean isDone() { 161 return state != NEW; 162 } 163 cancel(boolean mayInterruptIfRunning)164 public boolean cancel(boolean mayInterruptIfRunning) { 165 if (!(state == NEW && STATE.compareAndSet 166 (this, NEW, mayInterruptIfRunning ? INTERRUPTING : CANCELLED))) 167 return false; 168 try { // in case call to interrupt throws exception 169 if (mayInterruptIfRunning) { 170 try { 171 Thread t = runner; 172 if (t != null) 173 t.interrupt(); 174 } finally { // final state 175 STATE.setRelease(this, INTERRUPTED); 176 } 177 } 178 } finally { 179 finishCompletion(); 180 } 181 return true; 182 } 183 184 /** 185 * @throws CancellationException {@inheritDoc} 186 */ get()187 public V get() throws InterruptedException, ExecutionException { 188 int s = state; 189 if (s <= COMPLETING) 190 s = awaitDone(false, 0L); 191 return report(s); 192 } 193 194 /** 195 * @throws CancellationException {@inheritDoc} 196 */ get(long timeout, TimeUnit unit)197 public V get(long timeout, TimeUnit unit) 198 throws InterruptedException, ExecutionException, TimeoutException { 199 if (unit == null) 200 throw new NullPointerException(); 201 int s = state; 202 if (s <= COMPLETING && 203 (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING) 204 throw new TimeoutException(); 205 return report(s); 206 } 207 208 @Override resultNow()209 public V resultNow() { 210 switch (state()) { // Future.State 211 case SUCCESS: 212 @SuppressWarnings("unchecked") 213 V result = (V) outcome; 214 return result; 215 case FAILED: 216 throw new IllegalStateException("Task completed with exception"); 217 case CANCELLED: 218 throw new IllegalStateException("Task was cancelled"); 219 default: 220 throw new IllegalStateException("Task has not completed"); 221 } 222 } 223 224 @Override exceptionNow()225 public Throwable exceptionNow() { 226 switch (state()) { // Future.State 227 case SUCCESS: 228 throw new IllegalStateException("Task completed with a result"); 229 case FAILED: 230 Object x = outcome; 231 return (Throwable) x; 232 case CANCELLED: 233 throw new IllegalStateException("Task was cancelled"); 234 default: 235 throw new IllegalStateException("Task has not completed"); 236 } 237 } 238 239 @Override state()240 public State state() { 241 int s = state; 242 while (s == COMPLETING) { 243 // waiting for transition to NORMAL or EXCEPTIONAL 244 Thread.yield(); 245 s = state; 246 } 247 switch (s) { 248 case NORMAL: 249 return State.SUCCESS; 250 case EXCEPTIONAL: 251 return State.FAILED; 252 case CANCELLED: 253 case INTERRUPTING: 254 case INTERRUPTED: 255 return State.CANCELLED; 256 default: 257 return State.RUNNING; 258 } 259 } 260 261 /** 262 * Protected method invoked when this task transitions to state 263 * {@code isDone} (whether normally or via cancellation). The 264 * default implementation does nothing. Subclasses may override 265 * this method to invoke completion callbacks or perform 266 * bookkeeping. Note that you can query status inside the 267 * implementation of this method to determine whether this task 268 * has been cancelled. 269 */ done()270 protected void done() { } 271 272 /** 273 * Sets the result of this future to the given value unless 274 * this future has already been set or has been cancelled. 275 * 276 * <p>This method is invoked internally by the {@link #run} method 277 * upon successful completion of the computation. 278 * 279 * @param v the value 280 */ set(V v)281 protected void set(V v) { 282 if (STATE.compareAndSet(this, NEW, COMPLETING)) { 283 outcome = v; 284 STATE.setRelease(this, NORMAL); // final state 285 finishCompletion(); 286 } 287 } 288 289 /** 290 * Causes this future to report an {@link ExecutionException} 291 * with the given throwable as its cause, unless this future has 292 * already been set or has been cancelled. 293 * 294 * <p>This method is invoked internally by the {@link #run} method 295 * upon failure of the computation. 296 * 297 * @param t the cause of failure 298 */ setException(Throwable t)299 protected void setException(Throwable t) { 300 if (STATE.compareAndSet(this, NEW, COMPLETING)) { 301 outcome = t; 302 STATE.setRelease(this, EXCEPTIONAL); // final state 303 finishCompletion(); 304 } 305 } 306 run()307 public void run() { 308 if (state != NEW || 309 !RUNNER.compareAndSet(this, null, Thread.currentThread())) 310 return; 311 try { 312 Callable<V> c = callable; 313 if (c != null && state == NEW) { 314 V result; 315 boolean ran; 316 try { 317 result = c.call(); 318 ran = true; 319 } catch (Throwable ex) { 320 result = null; 321 ran = false; 322 setException(ex); 323 } 324 if (ran) 325 set(result); 326 } 327 } finally { 328 // runner must be non-null until state is settled to 329 // prevent concurrent calls to run() 330 runner = null; 331 // state must be re-read after nulling runner to prevent 332 // leaked interrupts 333 int s = state; 334 if (s >= INTERRUPTING) 335 handlePossibleCancellationInterrupt(s); 336 } 337 } 338 339 /** 340 * Executes the computation without setting its result, and then 341 * resets this future to initial state, failing to do so if the 342 * computation encounters an exception or is cancelled. This is 343 * designed for use with tasks that intrinsically execute more 344 * than once. 345 * 346 * @return {@code true} if successfully run and reset 347 */ runAndReset()348 protected boolean runAndReset() { 349 if (state != NEW || 350 !RUNNER.compareAndSet(this, null, Thread.currentThread())) 351 return false; 352 boolean ran = false; 353 int s = state; 354 try { 355 Callable<V> c = callable; 356 if (c != null && s == NEW) { 357 try { 358 c.call(); // don't set result 359 ran = true; 360 } catch (Throwable ex) { 361 setException(ex); 362 } 363 } 364 } finally { 365 // runner must be non-null until state is settled to 366 // prevent concurrent calls to run() 367 runner = null; 368 // state must be re-read after nulling runner to prevent 369 // leaked interrupts 370 s = state; 371 if (s >= INTERRUPTING) 372 handlePossibleCancellationInterrupt(s); 373 } 374 return ran && s == NEW; 375 } 376 377 /** 378 * Ensures that any interrupt from a possible cancel(true) is only 379 * delivered to a task while in run or runAndReset. 380 */ handlePossibleCancellationInterrupt(int s)381 private void handlePossibleCancellationInterrupt(int s) { 382 // It is possible for our interrupter to stall before getting a 383 // chance to interrupt us. Let's spin-wait patiently. 384 if (s == INTERRUPTING) 385 while (state == INTERRUPTING) 386 Thread.yield(); // wait out pending interrupt 387 388 // assert state == INTERRUPTED; 389 390 // We want to clear any interrupt we may have received from 391 // cancel(true). However, it is permissible to use interrupts 392 // as an independent mechanism for a task to communicate with 393 // its caller, and there is no way to clear only the 394 // cancellation interrupt. 395 // 396 // Thread.interrupted(); 397 } 398 399 /** 400 * Simple linked list nodes to record waiting threads in a Treiber 401 * stack. See other classes such as Phaser and SynchronousQueue 402 * for more detailed explanation. 403 */ 404 static final class WaitNode { 405 volatile Thread thread; 406 volatile WaitNode next; WaitNode()407 WaitNode() { thread = Thread.currentThread(); } 408 } 409 410 /** 411 * Removes and signals all waiting threads, invokes done(), and 412 * nulls out callable. 413 */ finishCompletion()414 private void finishCompletion() { 415 // assert state > COMPLETING; 416 for (WaitNode q; (q = waiters) != null;) { 417 if (WAITERS.weakCompareAndSet(this, q, null)) { 418 for (;;) { 419 Thread t = q.thread; 420 if (t != null) { 421 q.thread = null; 422 LockSupport.unpark(t); 423 } 424 WaitNode next = q.next; 425 if (next == null) 426 break; 427 q.next = null; // unlink to help gc 428 q = next; 429 } 430 break; 431 } 432 } 433 434 done(); 435 436 callable = null; // to reduce footprint 437 } 438 439 /** 440 * Awaits completion or aborts on interrupt or timeout. 441 * 442 * @param timed true if use timed waits 443 * @param nanos time to wait, if timed 444 * @return state upon completion or at timeout 445 */ awaitDone(boolean timed, long nanos)446 private int awaitDone(boolean timed, long nanos) 447 throws InterruptedException { 448 // The code below is very delicate, to achieve these goals: 449 // - call nanoTime exactly once for each call to park 450 // - if nanos <= 0L, return promptly without allocation or nanoTime 451 // - if nanos == Long.MIN_VALUE, don't underflow 452 // - if nanos == Long.MAX_VALUE, and nanoTime is non-monotonic 453 // and we suffer a spurious wakeup, we will do no worse than 454 // to park-spin for a while 455 long startTime = 0L; // Special value 0L means not yet parked 456 WaitNode q = null; 457 boolean queued = false; 458 for (;;) { 459 int s = state; 460 if (s > COMPLETING) { 461 if (q != null) 462 q.thread = null; 463 return s; 464 } 465 else if (s == COMPLETING) 466 // We may have already promised (via isDone) that we are done 467 // so never return empty-handed or throw InterruptedException 468 Thread.yield(); 469 else if (Thread.interrupted()) { 470 removeWaiter(q); 471 throw new InterruptedException(); 472 } 473 else if (q == null) { 474 if (timed && nanos <= 0L) 475 return s; 476 q = new WaitNode(); 477 } 478 else if (!queued) 479 queued = WAITERS.weakCompareAndSet(this, q.next = waiters, q); 480 else if (timed) { 481 final long parkNanos; 482 if (startTime == 0L) { // first time 483 startTime = System.nanoTime(); 484 if (startTime == 0L) 485 startTime = 1L; 486 parkNanos = nanos; 487 } else { 488 long elapsed = System.nanoTime() - startTime; 489 if (elapsed >= nanos) { 490 removeWaiter(q); 491 return state; 492 } 493 parkNanos = nanos - elapsed; 494 } 495 // nanoTime may be slow; recheck before parking 496 if (state < COMPLETING) 497 LockSupport.parkNanos(this, parkNanos); 498 } 499 else 500 LockSupport.park(this); 501 } 502 } 503 504 /** 505 * Tries to unlink a timed-out or interrupted wait node to avoid 506 * accumulating garbage. Internal nodes are simply unspliced 507 * without CAS since it is harmless if they are traversed anyway 508 * by releasers. To avoid effects of unsplicing from already 509 * removed nodes, the list is retraversed in case of an apparent 510 * race. This is slow when there are a lot of nodes, but we don't 511 * expect lists to be long enough to outweigh higher-overhead 512 * schemes. 513 */ removeWaiter(WaitNode node)514 private void removeWaiter(WaitNode node) { 515 if (node != null) { 516 node.thread = null; 517 retry: 518 for (;;) { // restart on removeWaiter race 519 for (WaitNode pred = null, q = waiters, s; q != null; q = s) { 520 s = q.next; 521 if (q.thread != null) 522 pred = q; 523 else if (pred != null) { 524 pred.next = s; 525 if (pred.thread == null) // check for race 526 continue retry; 527 } 528 else if (!WAITERS.compareAndSet(this, q, s)) 529 continue retry; 530 } 531 break; 532 } 533 } 534 } 535 536 /** 537 * Returns a string representation of this FutureTask. 538 * 539 * @implSpec 540 * The default implementation returns a string identifying this 541 * FutureTask, as well as its completion state. The state, in 542 * brackets, contains one of the strings {@code "Completed Normally"}, 543 * {@code "Completed Exceptionally"}, {@code "Cancelled"}, or {@code 544 * "Not completed"}. 545 * 546 * @return a string representation of this FutureTask 547 */ toString()548 public String toString() { 549 final String status; 550 switch (state) { 551 case NORMAL: 552 status = "[Completed normally]"; 553 break; 554 case EXCEPTIONAL: 555 status = "[Completed exceptionally: " + outcome + "]"; 556 break; 557 case CANCELLED: 558 case INTERRUPTING: 559 case INTERRUPTED: 560 status = "[Cancelled]"; 561 break; 562 default: 563 // BEGIN Android-changed: recursion risk building string (b/241297967) 564 /* 565 final Callable<?> callable = this.callable; 566 status = (callable == null) 567 ? "[Not completed]" 568 : "[Not completed, task = " + callable + "]"; 569 */ 570 status = "[Not completed]"; 571 // END Android-changed: recursion risk building string (b/241297967) 572 } 573 return super.toString() + status; 574 } 575 576 // VarHandle mechanics 577 private static final VarHandle STATE; 578 private static final VarHandle RUNNER; 579 private static final VarHandle WAITERS; 580 static { 581 try { 582 MethodHandles.Lookup l = MethodHandles.lookup(); 583 STATE = l.findVarHandle(FutureTask.class, "state", int.class); 584 RUNNER = l.findVarHandle(FutureTask.class, "runner", Thread.class); 585 WAITERS = l.findVarHandle(FutureTask.class, "waiters", WaitNode.class); 586 } catch (ReflectiveOperationException e) { 587 throw new ExceptionInInitializerError(e); 588 } 589 590 // Reduce the risk of rare disastrous classloading in first call to 591 // LockSupport.park: https://bugs.openjdk.org/browse/JDK-8074773 592 Class<?> ensureLoaded = LockSupport.class; 593 } 594 595 } 596