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.io.Serializable; 39 import java.lang.ref.ReferenceQueue; 40 import java.lang.ref.WeakReference; 41 import java.lang.reflect.Constructor; 42 import java.util.Collection; 43 import java.util.List; 44 import java.util.RandomAccess; 45 import java.util.concurrent.locks.ReentrantLock; 46 47 // BEGIN android-note 48 // removed java 9 code 49 // END android-note 50 51 /** 52 * Abstract base class for tasks that run within a {@link ForkJoinPool}. 53 * A {@code ForkJoinTask} is a thread-like entity that is much 54 * lighter weight than a normal thread. Huge numbers of tasks and 55 * subtasks may be hosted by a small number of actual threads in a 56 * ForkJoinPool, at the price of some usage limitations. 57 * 58 * <p>A "main" {@code ForkJoinTask} begins execution when it is 59 * explicitly submitted to a {@link ForkJoinPool}, or, if not already 60 * engaged in a ForkJoin computation, commenced in the {@link 61 * ForkJoinPool#commonPool()} via {@link #fork}, {@link #invoke}, or 62 * related methods. Once started, it will usually in turn start other 63 * subtasks. As indicated by the name of this class, many programs 64 * using {@code ForkJoinTask} employ only methods {@link #fork} and 65 * {@link #join}, or derivatives such as {@link 66 * #invokeAll(ForkJoinTask...) invokeAll}. However, this class also 67 * provides a number of other methods that can come into play in 68 * advanced usages, as well as extension mechanics that allow support 69 * of new forms of fork/join processing. 70 * 71 * <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}. 72 * The efficiency of {@code ForkJoinTask}s stems from a set of 73 * restrictions (that are only partially statically enforceable) 74 * reflecting their main use as computational tasks calculating pure 75 * functions or operating on purely isolated objects. The primary 76 * coordination mechanisms are {@link #fork}, that arranges 77 * asynchronous execution, and {@link #join}, that doesn't proceed 78 * until the task's result has been computed. Computations should 79 * ideally avoid {@code synchronized} methods or blocks, and should 80 * minimize other blocking synchronization apart from joining other 81 * tasks or using synchronizers such as Phasers that are advertised to 82 * cooperate with fork/join scheduling. Subdividable tasks should also 83 * not perform blocking I/O, and should ideally access variables that 84 * are completely independent of those accessed by other running 85 * tasks. These guidelines are loosely enforced by not permitting 86 * checked exceptions such as {@code IOExceptions} to be 87 * thrown. However, computations may still encounter unchecked 88 * exceptions, that are rethrown to callers attempting to join 89 * them. These exceptions may additionally include {@link 90 * RejectedExecutionException} stemming from internal resource 91 * exhaustion, such as failure to allocate internal task 92 * queues. Rethrown exceptions behave in the same way as regular 93 * exceptions, but, when possible, contain stack traces (as displayed 94 * for example using {@code ex.printStackTrace()}) of both the thread 95 * that initiated the computation as well as the thread actually 96 * encountering the exception; minimally only the latter. 97 * 98 * <p>It is possible to define and use ForkJoinTasks that may block, 99 * but doing do requires three further considerations: (1) Completion 100 * of few if any <em>other</em> tasks should be dependent on a task 101 * that blocks on external synchronization or I/O. Event-style async 102 * tasks that are never joined (for example, those subclassing {@link 103 * CountedCompleter}) often fall into this category. (2) To minimize 104 * resource impact, tasks should be small; ideally performing only the 105 * (possibly) blocking action. (3) Unless the {@link 106 * ForkJoinPool.ManagedBlocker} API is used, or the number of possibly 107 * blocked tasks is known to be less than the pool's {@link 108 * ForkJoinPool#getParallelism} level, the pool cannot guarantee that 109 * enough threads will be available to ensure progress or good 110 * performance. 111 * 112 * <p>The primary method for awaiting completion and extracting 113 * results of a task is {@link #join}, but there are several variants: 114 * The {@link Future#get} methods support interruptible and/or timed 115 * waits for completion and report results using {@code Future} 116 * conventions. Method {@link #invoke} is semantically 117 * equivalent to {@code fork(); join()} but always attempts to begin 118 * execution in the current thread. The "<em>quiet</em>" forms of 119 * these methods do not extract results or report exceptions. These 120 * may be useful when a set of tasks are being executed, and you need 121 * to delay processing of results or exceptions until all complete. 122 * Method {@code invokeAll} (available in multiple versions) 123 * performs the most common form of parallel invocation: forking a set 124 * of tasks and joining them all. 125 * 126 * <p>In the most typical usages, a fork-join pair act like a call 127 * (fork) and return (join) from a parallel recursive function. As is 128 * the case with other forms of recursive calls, returns (joins) 129 * should be performed innermost-first. For example, {@code a.fork(); 130 * b.fork(); b.join(); a.join();} is likely to be substantially more 131 * efficient than joining {@code a} before {@code b}. 132 * 133 * <p>The execution status of tasks may be queried at several levels 134 * of detail: {@link #isDone} is true if a task completed in any way 135 * (including the case where a task was cancelled without executing); 136 * {@link #isCompletedNormally} is true if a task completed without 137 * cancellation or encountering an exception; {@link #isCancelled} is 138 * true if the task was cancelled (in which case {@link #getException} 139 * returns a {@link java.util.concurrent.CancellationException}); and 140 * {@link #isCompletedAbnormally} is true if a task was either 141 * cancelled or encountered an exception, in which case {@link 142 * #getException} will return either the encountered exception or 143 * {@link java.util.concurrent.CancellationException}. 144 * 145 * <p>The ForkJoinTask class is not usually directly subclassed. 146 * Instead, you subclass one of the abstract classes that support a 147 * particular style of fork/join processing, typically {@link 148 * RecursiveAction} for most computations that do not return results, 149 * {@link RecursiveTask} for those that do, and {@link 150 * CountedCompleter} for those in which completed actions trigger 151 * other actions. Normally, a concrete ForkJoinTask subclass declares 152 * fields comprising its parameters, established in a constructor, and 153 * then defines a {@code compute} method that somehow uses the control 154 * methods supplied by this base class. 155 * 156 * <p>Method {@link #join} and its variants are appropriate for use 157 * only when completion dependencies are acyclic; that is, the 158 * parallel computation can be described as a directed acyclic graph 159 * (DAG). Otherwise, executions may encounter a form of deadlock as 160 * tasks cyclically wait for each other. However, this framework 161 * supports other methods and techniques (for example the use of 162 * {@link Phaser}, {@link #helpQuiesce}, and {@link #complete}) that 163 * may be of use in constructing custom subclasses for problems that 164 * are not statically structured as DAGs. To support such usages, a 165 * ForkJoinTask may be atomically <em>tagged</em> with a {@code short} 166 * value using {@link #setForkJoinTaskTag} or {@link 167 * #compareAndSetForkJoinTaskTag} and checked using {@link 168 * #getForkJoinTaskTag}. The ForkJoinTask implementation does not use 169 * these {@code protected} methods or tags for any purpose, but they 170 * may be of use in the construction of specialized subclasses. For 171 * example, parallel graph traversals can use the supplied methods to 172 * avoid revisiting nodes/tasks that have already been processed. 173 * (Method names for tagging are bulky in part to encourage definition 174 * of methods that reflect their usage patterns.) 175 * 176 * <p>Most base support methods are {@code final}, to prevent 177 * overriding of implementations that are intrinsically tied to the 178 * underlying lightweight task scheduling framework. Developers 179 * creating new basic styles of fork/join processing should minimally 180 * implement {@code protected} methods {@link #exec}, {@link 181 * #setRawResult}, and {@link #getRawResult}, while also introducing 182 * an abstract computational method that can be implemented in its 183 * subclasses, possibly relying on other {@code protected} methods 184 * provided by this class. 185 * 186 * <p>ForkJoinTasks should perform relatively small amounts of 187 * computation. Large tasks should be split into smaller subtasks, 188 * usually via recursive decomposition. As a very rough rule of thumb, 189 * a task should perform more than 100 and less than 10000 basic 190 * computational steps, and should avoid indefinite looping. If tasks 191 * are too big, then parallelism cannot improve throughput. If too 192 * small, then memory and internal task maintenance overhead may 193 * overwhelm processing. 194 * 195 * <p>This class provides {@code adapt} methods for {@link Runnable} 196 * and {@link Callable}, that may be of use when mixing execution of 197 * {@code ForkJoinTasks} with other kinds of tasks. When all tasks are 198 * of this form, consider using a pool constructed in <em>asyncMode</em>. 199 * 200 * <p>ForkJoinTasks are {@code Serializable}, which enables them to be 201 * used in extensions such as remote execution frameworks. It is 202 * sensible to serialize tasks only before or after, but not during, 203 * execution. Serialization is not relied on during execution itself. 204 * 205 * @since 1.7 206 * @author Doug Lea 207 */ 208 public abstract class ForkJoinTask<V> implements Future<V>, Serializable { 209 210 /* 211 * See the internal documentation of class ForkJoinPool for a 212 * general implementation overview. ForkJoinTasks are mainly 213 * responsible for maintaining their "status" field amidst relays 214 * to methods in ForkJoinWorkerThread and ForkJoinPool. 215 * 216 * The methods of this class are more-or-less layered into 217 * (1) basic status maintenance 218 * (2) execution and awaiting completion 219 * (3) user-level methods that additionally report results. 220 * This is sometimes hard to see because this file orders exported 221 * methods in a way that flows well in javadocs. 222 */ 223 224 /* 225 * The status field holds run control status bits packed into a 226 * single int to minimize footprint and to ensure atomicity (via 227 * CAS). Status is initially zero, and takes on nonnegative 228 * values until completed, upon which status (anded with 229 * DONE_MASK) holds value NORMAL, CANCELLED, or EXCEPTIONAL. Tasks 230 * undergoing blocking waits by other threads have the SIGNAL bit 231 * set. Completion of a stolen task with SIGNAL set awakens any 232 * waiters via notifyAll. Even though suboptimal for some 233 * purposes, we use basic builtin wait/notify to take advantage of 234 * "monitor inflation" in JVMs that we would otherwise need to 235 * emulate to avoid adding further per-task bookkeeping overhead. 236 * We want these monitors to be "fat", i.e., not use biasing or 237 * thin-lock techniques, so use some odd coding idioms that tend 238 * to avoid them, mainly by arranging that every synchronized 239 * block performs a wait, notifyAll or both. 240 * 241 * These control bits occupy only (some of) the upper half (16 242 * bits) of status field. The lower bits are used for user-defined 243 * tags. 244 */ 245 246 /** The run status of this task */ 247 volatile int status; // accessed directly by pool and workers 248 static final int DONE_MASK = 0xf0000000; // mask out non-completion bits 249 static final int NORMAL = 0xf0000000; // must be negative 250 static final int CANCELLED = 0xc0000000; // must be < NORMAL 251 static final int EXCEPTIONAL = 0x80000000; // must be < CANCELLED 252 static final int SIGNAL = 0x00010000; // must be >= 1 << 16 253 static final int SMASK = 0x0000ffff; // short bits for tags 254 255 /** 256 * Marks completion and wakes up threads waiting to join this 257 * task. 258 * 259 * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL 260 * @return completion status on exit 261 */ setCompletion(int completion)262 private int setCompletion(int completion) { 263 for (int s;;) { 264 if ((s = status) < 0) 265 return s; 266 if (U.compareAndSwapInt(this, STATUS, s, s | completion)) { 267 if ((s >>> 16) != 0) 268 synchronized (this) { notifyAll(); } 269 return completion; 270 } 271 } 272 } 273 274 /** 275 * Primary execution method for stolen tasks. Unless done, calls 276 * exec and records status if completed, but doesn't wait for 277 * completion otherwise. 278 * 279 * @return status on exit from this method 280 */ doExec()281 final int doExec() { 282 int s; boolean completed; 283 if ((s = status) >= 0) { 284 try { 285 completed = exec(); 286 } catch (Throwable rex) { 287 return setExceptionalCompletion(rex); 288 } 289 if (completed) 290 s = setCompletion(NORMAL); 291 } 292 return s; 293 } 294 295 /** 296 * If not done, sets SIGNAL status and performs Object.wait(timeout). 297 * This task may or may not be done on exit. Ignores interrupts. 298 * 299 * @param timeout using Object.wait conventions. 300 */ internalWait(long timeout)301 final void internalWait(long timeout) { 302 int s; 303 if ((s = status) >= 0 && // force completer to issue notify 304 U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) { 305 synchronized (this) { 306 if (status >= 0) 307 try { wait(timeout); } catch (InterruptedException ie) { } 308 else 309 notifyAll(); 310 } 311 } 312 } 313 314 /** 315 * Blocks a non-worker-thread until completion. 316 * @return status upon completion 317 */ externalAwaitDone()318 private int externalAwaitDone() { 319 int s = ((this instanceof CountedCompleter) ? // try helping 320 ForkJoinPool.common.externalHelpComplete( 321 (CountedCompleter<?>)this, 0) : 322 ForkJoinPool.common.tryExternalUnpush(this) ? doExec() : 0); 323 if (s >= 0 && (s = status) >= 0) { 324 boolean interrupted = false; 325 do { 326 if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) { 327 synchronized (this) { 328 if (status >= 0) { 329 try { 330 wait(0L); 331 } catch (InterruptedException ie) { 332 interrupted = true; 333 } 334 } 335 else 336 notifyAll(); 337 } 338 } 339 } while ((s = status) >= 0); 340 if (interrupted) 341 Thread.currentThread().interrupt(); 342 } 343 return s; 344 } 345 346 /** 347 * Blocks a non-worker-thread until completion or interruption. 348 */ externalInterruptibleAwaitDone()349 private int externalInterruptibleAwaitDone() throws InterruptedException { 350 int s; 351 if (Thread.interrupted()) 352 throw new InterruptedException(); 353 if ((s = status) >= 0 && 354 (s = ((this instanceof CountedCompleter) ? 355 ForkJoinPool.common.externalHelpComplete( 356 (CountedCompleter<?>)this, 0) : 357 ForkJoinPool.common.tryExternalUnpush(this) ? doExec() : 358 0)) >= 0) { 359 while ((s = status) >= 0) { 360 if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) { 361 synchronized (this) { 362 if (status >= 0) 363 wait(0L); 364 else 365 notifyAll(); 366 } 367 } 368 } 369 } 370 return s; 371 } 372 373 /** 374 * Implementation for join, get, quietlyJoin. Directly handles 375 * only cases of already-completed, external wait, and 376 * unfork+exec. Others are relayed to ForkJoinPool.awaitJoin. 377 * 378 * @return status upon completion 379 */ doJoin()380 private int doJoin() { 381 int s; Thread t; ForkJoinWorkerThread wt; ForkJoinPool.WorkQueue w; 382 return (s = status) < 0 ? s : 383 ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ? 384 (w = (wt = (ForkJoinWorkerThread)t).workQueue). 385 tryUnpush(this) && (s = doExec()) < 0 ? s : 386 wt.pool.awaitJoin(w, this, 0L) : 387 externalAwaitDone(); 388 } 389 390 /** 391 * Implementation for invoke, quietlyInvoke. 392 * 393 * @return status upon completion 394 */ doInvoke()395 private int doInvoke() { 396 int s; Thread t; ForkJoinWorkerThread wt; 397 return (s = doExec()) < 0 ? s : 398 ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ? 399 (wt = (ForkJoinWorkerThread)t).pool. 400 awaitJoin(wt.workQueue, this, 0L) : 401 externalAwaitDone(); 402 } 403 404 // Exception table support 405 406 /** 407 * Table of exceptions thrown by tasks, to enable reporting by 408 * callers. Because exceptions are rare, we don't directly keep 409 * them with task objects, but instead use a weak ref table. Note 410 * that cancellation exceptions don't appear in the table, but are 411 * instead recorded as status values. 412 * 413 * Note: These statics are initialized below in static block. 414 */ 415 private static final ExceptionNode[] exceptionTable; 416 private static final ReentrantLock exceptionTableLock; 417 private static final ReferenceQueue<Object> exceptionTableRefQueue; 418 419 /** 420 * Fixed capacity for exceptionTable. 421 */ 422 private static final int EXCEPTION_MAP_CAPACITY = 32; 423 424 /** 425 * Key-value nodes for exception table. The chained hash table 426 * uses identity comparisons, full locking, and weak references 427 * for keys. The table has a fixed capacity because it only 428 * maintains task exceptions long enough for joiners to access 429 * them, so should never become very large for sustained 430 * periods. However, since we do not know when the last joiner 431 * completes, we must use weak references and expunge them. We do 432 * so on each operation (hence full locking). Also, some thread in 433 * any ForkJoinPool will call helpExpungeStaleExceptions when its 434 * pool becomes isQuiescent. 435 */ 436 static final class ExceptionNode extends WeakReference<ForkJoinTask<?>> { 437 final Throwable ex; 438 ExceptionNode next; 439 final long thrower; // use id not ref to avoid weak cycles 440 final int hashCode; // store task hashCode before weak ref disappears ExceptionNode(ForkJoinTask<?> task, Throwable ex, ExceptionNode next, ReferenceQueue<Object> exceptionTableRefQueue)441 ExceptionNode(ForkJoinTask<?> task, Throwable ex, ExceptionNode next, 442 ReferenceQueue<Object> exceptionTableRefQueue) { 443 super(task, exceptionTableRefQueue); 444 this.ex = ex; 445 this.next = next; 446 this.thrower = Thread.currentThread().getId(); 447 this.hashCode = System.identityHashCode(task); 448 } 449 } 450 451 /** 452 * Records exception and sets status. 453 * 454 * @return status on exit 455 */ recordExceptionalCompletion(Throwable ex)456 final int recordExceptionalCompletion(Throwable ex) { 457 int s; 458 if ((s = status) >= 0) { 459 int h = System.identityHashCode(this); 460 final ReentrantLock lock = exceptionTableLock; 461 lock.lock(); 462 try { 463 expungeStaleExceptions(); 464 ExceptionNode[] t = exceptionTable; 465 int i = h & (t.length - 1); 466 for (ExceptionNode e = t[i]; ; e = e.next) { 467 if (e == null) { 468 t[i] = new ExceptionNode(this, ex, t[i], 469 exceptionTableRefQueue); 470 break; 471 } 472 if (e.get() == this) // already present 473 break; 474 } 475 } finally { 476 lock.unlock(); 477 } 478 s = setCompletion(EXCEPTIONAL); 479 } 480 return s; 481 } 482 483 /** 484 * Records exception and possibly propagates. 485 * 486 * @return status on exit 487 */ setExceptionalCompletion(Throwable ex)488 private int setExceptionalCompletion(Throwable ex) { 489 int s = recordExceptionalCompletion(ex); 490 if ((s & DONE_MASK) == EXCEPTIONAL) 491 internalPropagateException(ex); 492 return s; 493 } 494 495 /** 496 * Hook for exception propagation support for tasks with completers. 497 */ internalPropagateException(Throwable ex)498 void internalPropagateException(Throwable ex) { 499 } 500 501 /** 502 * Cancels, ignoring any exceptions thrown by cancel. Used during 503 * worker and pool shutdown. Cancel is spec'ed not to throw any 504 * exceptions, but if it does anyway, we have no recourse during 505 * shutdown, so guard against this case. 506 */ cancelIgnoringExceptions(ForkJoinTask<?> t)507 static final void cancelIgnoringExceptions(ForkJoinTask<?> t) { 508 if (t != null && t.status >= 0) { 509 try { 510 t.cancel(false); 511 } catch (Throwable ignore) { 512 } 513 } 514 } 515 516 /** 517 * Removes exception node and clears status. 518 */ clearExceptionalCompletion()519 private void clearExceptionalCompletion() { 520 int h = System.identityHashCode(this); 521 final ReentrantLock lock = exceptionTableLock; 522 lock.lock(); 523 try { 524 ExceptionNode[] t = exceptionTable; 525 int i = h & (t.length - 1); 526 ExceptionNode e = t[i]; 527 ExceptionNode pred = null; 528 while (e != null) { 529 ExceptionNode next = e.next; 530 if (e.get() == this) { 531 if (pred == null) 532 t[i] = next; 533 else 534 pred.next = next; 535 break; 536 } 537 pred = e; 538 e = next; 539 } 540 expungeStaleExceptions(); 541 status = 0; 542 } finally { 543 lock.unlock(); 544 } 545 } 546 547 /** 548 * Returns a rethrowable exception for this task, if available. 549 * To provide accurate stack traces, if the exception was not 550 * thrown by the current thread, we try to create a new exception 551 * of the same type as the one thrown, but with the recorded 552 * exception as its cause. If there is no such constructor, we 553 * instead try to use a no-arg constructor, followed by initCause, 554 * to the same effect. If none of these apply, or any fail due to 555 * other exceptions, we return the recorded exception, which is 556 * still correct, although it may contain a misleading stack 557 * trace. 558 * 559 * @return the exception, or null if none 560 */ getThrowableException()561 private Throwable getThrowableException() { 562 int h = System.identityHashCode(this); 563 ExceptionNode e; 564 final ReentrantLock lock = exceptionTableLock; 565 lock.lock(); 566 try { 567 expungeStaleExceptions(); 568 ExceptionNode[] t = exceptionTable; 569 e = t[h & (t.length - 1)]; 570 while (e != null && e.get() != this) 571 e = e.next; 572 } finally { 573 lock.unlock(); 574 } 575 Throwable ex; 576 if (e == null || (ex = e.ex) == null) 577 return null; 578 if (e.thrower != Thread.currentThread().getId()) { 579 try { 580 Constructor<?> noArgCtor = null; 581 // public ctors only 582 for (Constructor<?> c : ex.getClass().getConstructors()) { 583 Class<?>[] ps = c.getParameterTypes(); 584 if (ps.length == 0) 585 noArgCtor = c; 586 else if (ps.length == 1 && ps[0] == Throwable.class) 587 return (Throwable)c.newInstance(ex); 588 } 589 if (noArgCtor != null) { 590 Throwable wx = (Throwable)noArgCtor.newInstance(); 591 wx.initCause(ex); 592 return wx; 593 } 594 } catch (Exception ignore) { 595 } 596 } 597 return ex; 598 } 599 600 /** 601 * Polls stale refs and removes them. Call only while holding lock. 602 */ expungeStaleExceptions()603 private static void expungeStaleExceptions() { 604 for (Object x; (x = exceptionTableRefQueue.poll()) != null;) { 605 if (x instanceof ExceptionNode) { 606 int hashCode = ((ExceptionNode)x).hashCode; 607 ExceptionNode[] t = exceptionTable; 608 int i = hashCode & (t.length - 1); 609 ExceptionNode e = t[i]; 610 ExceptionNode pred = null; 611 while (e != null) { 612 ExceptionNode next = e.next; 613 if (e == x) { 614 if (pred == null) 615 t[i] = next; 616 else 617 pred.next = next; 618 break; 619 } 620 pred = e; 621 e = next; 622 } 623 } 624 } 625 } 626 627 /** 628 * If lock is available, polls stale refs and removes them. 629 * Called from ForkJoinPool when pools become quiescent. 630 */ helpExpungeStaleExceptions()631 static final void helpExpungeStaleExceptions() { 632 final ReentrantLock lock = exceptionTableLock; 633 if (lock.tryLock()) { 634 try { 635 expungeStaleExceptions(); 636 } finally { 637 lock.unlock(); 638 } 639 } 640 } 641 642 /** 643 * A version of "sneaky throw" to relay exceptions. 644 */ rethrow(Throwable ex)645 static void rethrow(Throwable ex) { 646 ForkJoinTask.<RuntimeException>uncheckedThrow(ex); 647 } 648 649 /** 650 * The sneaky part of sneaky throw, relying on generics 651 * limitations to evade compiler complaints about rethrowing 652 * unchecked exceptions. 653 */ 654 @SuppressWarnings("unchecked") static <T extends Throwable> uncheckedThrow(Throwable t)655 void uncheckedThrow(Throwable t) throws T { 656 if (t != null) 657 throw (T)t; // rely on vacuous cast 658 else 659 throw new Error("Unknown Exception"); 660 } 661 662 /** 663 * Throws exception, if any, associated with the given status. 664 */ reportException(int s)665 private void reportException(int s) { 666 if (s == CANCELLED) 667 throw new CancellationException(); 668 if (s == EXCEPTIONAL) 669 rethrow(getThrowableException()); 670 } 671 672 // public methods 673 674 /** 675 * Arranges to asynchronously execute this task in the pool the 676 * current task is running in, if applicable, or using the {@link 677 * ForkJoinPool#commonPool()} if not {@link #inForkJoinPool}. While 678 * it is not necessarily enforced, it is a usage error to fork a 679 * task more than once unless it has completed and been 680 * reinitialized. Subsequent modifications to the state of this 681 * task or any data it operates on are not necessarily 682 * consistently observable by any thread other than the one 683 * executing it unless preceded by a call to {@link #join} or 684 * related methods, or a call to {@link #isDone} returning {@code 685 * true}. 686 * 687 * @return {@code this}, to simplify usage 688 */ fork()689 public final ForkJoinTask<V> fork() { 690 Thread t; 691 if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) 692 ((ForkJoinWorkerThread)t).workQueue.push(this); 693 else 694 ForkJoinPool.common.externalPush(this); 695 return this; 696 } 697 698 /** 699 * Returns the result of the computation when it {@link #isDone is 700 * done}. This method differs from {@link #get()} in that 701 * abnormal completion results in {@code RuntimeException} or 702 * {@code Error}, not {@code ExecutionException}, and that 703 * interrupts of the calling thread do <em>not</em> cause the 704 * method to abruptly return by throwing {@code 705 * InterruptedException}. 706 * 707 * @return the computed result 708 */ join()709 public final V join() { 710 int s; 711 if ((s = doJoin() & DONE_MASK) != NORMAL) 712 reportException(s); 713 return getRawResult(); 714 } 715 716 /** 717 * Commences performing this task, awaits its completion if 718 * necessary, and returns its result, or throws an (unchecked) 719 * {@code RuntimeException} or {@code Error} if the underlying 720 * computation did so. 721 * 722 * @return the computed result 723 */ invoke()724 public final V invoke() { 725 int s; 726 if ((s = doInvoke() & DONE_MASK) != NORMAL) 727 reportException(s); 728 return getRawResult(); 729 } 730 731 /** 732 * Forks the given tasks, returning when {@code isDone} holds for 733 * each task or an (unchecked) exception is encountered, in which 734 * case the exception is rethrown. If more than one task 735 * encounters an exception, then this method throws any one of 736 * these exceptions. If any task encounters an exception, the 737 * other may be cancelled. However, the execution status of 738 * individual tasks is not guaranteed upon exceptional return. The 739 * status of each task may be obtained using {@link 740 * #getException()} and related methods to check if they have been 741 * cancelled, completed normally or exceptionally, or left 742 * unprocessed. 743 * 744 * @param t1 the first task 745 * @param t2 the second task 746 * @throws NullPointerException if any task is null 747 */ invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2)748 public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) { 749 int s1, s2; 750 t2.fork(); 751 if ((s1 = t1.doInvoke() & DONE_MASK) != NORMAL) 752 t1.reportException(s1); 753 if ((s2 = t2.doJoin() & DONE_MASK) != NORMAL) 754 t2.reportException(s2); 755 } 756 757 /** 758 * Forks the given tasks, returning when {@code isDone} holds for 759 * each task or an (unchecked) exception is encountered, in which 760 * case the exception is rethrown. If more than one task 761 * encounters an exception, then this method throws any one of 762 * these exceptions. If any task encounters an exception, others 763 * may be cancelled. However, the execution status of individual 764 * tasks is not guaranteed upon exceptional return. The status of 765 * each task may be obtained using {@link #getException()} and 766 * related methods to check if they have been cancelled, completed 767 * normally or exceptionally, or left unprocessed. 768 * 769 * @param tasks the tasks 770 * @throws NullPointerException if any task is null 771 */ invokeAll(ForkJoinTask<?>.... tasks)772 public static void invokeAll(ForkJoinTask<?>... tasks) { 773 Throwable ex = null; 774 int last = tasks.length - 1; 775 for (int i = last; i >= 0; --i) { 776 ForkJoinTask<?> t = tasks[i]; 777 if (t == null) { 778 if (ex == null) 779 ex = new NullPointerException(); 780 } 781 else if (i != 0) 782 t.fork(); 783 else if (t.doInvoke() < NORMAL && ex == null) 784 ex = t.getException(); 785 } 786 for (int i = 1; i <= last; ++i) { 787 ForkJoinTask<?> t = tasks[i]; 788 if (t != null) { 789 if (ex != null) 790 t.cancel(false); 791 else if (t.doJoin() < NORMAL) 792 ex = t.getException(); 793 } 794 } 795 if (ex != null) 796 rethrow(ex); 797 } 798 799 /** 800 * Forks all tasks in the specified collection, returning when 801 * {@code isDone} holds for each task or an (unchecked) exception 802 * is encountered, in which case the exception is rethrown. If 803 * more than one task encounters an exception, then this method 804 * throws any one of these exceptions. If any task encounters an 805 * exception, others may be cancelled. However, the execution 806 * status of individual tasks is not guaranteed upon exceptional 807 * return. The status of each task may be obtained using {@link 808 * #getException()} and related methods to check if they have been 809 * cancelled, completed normally or exceptionally, or left 810 * unprocessed. 811 * 812 * @param tasks the collection of tasks 813 * @param <T> the type of the values returned from the tasks 814 * @return the tasks argument, to simplify usage 815 * @throws NullPointerException if tasks or any element are null 816 */ invokeAll(Collection<T> tasks)817 public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) { 818 if (!(tasks instanceof RandomAccess) || !(tasks instanceof List<?>)) { 819 invokeAll(tasks.toArray(new ForkJoinTask<?>[tasks.size()])); 820 return tasks; 821 } 822 @SuppressWarnings("unchecked") 823 List<? extends ForkJoinTask<?>> ts = 824 (List<? extends ForkJoinTask<?>>) tasks; 825 Throwable ex = null; 826 int last = ts.size() - 1; 827 for (int i = last; i >= 0; --i) { 828 ForkJoinTask<?> t = ts.get(i); 829 if (t == null) { 830 if (ex == null) 831 ex = new NullPointerException(); 832 } 833 else if (i != 0) 834 t.fork(); 835 else if (t.doInvoke() < NORMAL && ex == null) 836 ex = t.getException(); 837 } 838 for (int i = 1; i <= last; ++i) { 839 ForkJoinTask<?> t = ts.get(i); 840 if (t != null) { 841 if (ex != null) 842 t.cancel(false); 843 else if (t.doJoin() < NORMAL) 844 ex = t.getException(); 845 } 846 } 847 if (ex != null) 848 rethrow(ex); 849 return tasks; 850 } 851 852 /** 853 * Attempts to cancel execution of this task. This attempt will 854 * fail if the task has already completed or could not be 855 * cancelled for some other reason. If successful, and this task 856 * has not started when {@code cancel} is called, execution of 857 * this task is suppressed. After this method returns 858 * successfully, unless there is an intervening call to {@link 859 * #reinitialize}, subsequent calls to {@link #isCancelled}, 860 * {@link #isDone}, and {@code cancel} will return {@code true} 861 * and calls to {@link #join} and related methods will result in 862 * {@code CancellationException}. 863 * 864 * <p>This method may be overridden in subclasses, but if so, must 865 * still ensure that these properties hold. In particular, the 866 * {@code cancel} method itself must not throw exceptions. 867 * 868 * <p>This method is designed to be invoked by <em>other</em> 869 * tasks. To terminate the current task, you can just return or 870 * throw an unchecked exception from its computation method, or 871 * invoke {@link #completeExceptionally(Throwable)}. 872 * 873 * @param mayInterruptIfRunning this value has no effect in the 874 * default implementation because interrupts are not used to 875 * control cancellation. 876 * 877 * @return {@code true} if this task is now cancelled 878 */ cancel(boolean mayInterruptIfRunning)879 public boolean cancel(boolean mayInterruptIfRunning) { 880 return (setCompletion(CANCELLED) & DONE_MASK) == CANCELLED; 881 } 882 isDone()883 public final boolean isDone() { 884 return status < 0; 885 } 886 isCancelled()887 public final boolean isCancelled() { 888 return (status & DONE_MASK) == CANCELLED; 889 } 890 891 /** 892 * Returns {@code true} if this task threw an exception or was cancelled. 893 * 894 * @return {@code true} if this task threw an exception or was cancelled 895 */ isCompletedAbnormally()896 public final boolean isCompletedAbnormally() { 897 return status < NORMAL; 898 } 899 900 /** 901 * Returns {@code true} if this task completed without throwing an 902 * exception and was not cancelled. 903 * 904 * @return {@code true} if this task completed without throwing an 905 * exception and was not cancelled 906 */ isCompletedNormally()907 public final boolean isCompletedNormally() { 908 return (status & DONE_MASK) == NORMAL; 909 } 910 911 /** 912 * Returns the exception thrown by the base computation, or a 913 * {@code CancellationException} if cancelled, or {@code null} if 914 * none or if the method has not yet completed. 915 * 916 * @return the exception, or {@code null} if none 917 */ getException()918 public final Throwable getException() { 919 int s = status & DONE_MASK; 920 return ((s >= NORMAL) ? null : 921 (s == CANCELLED) ? new CancellationException() : 922 getThrowableException()); 923 } 924 925 /** 926 * Completes this task abnormally, and if not already aborted or 927 * cancelled, causes it to throw the given exception upon 928 * {@code join} and related operations. This method may be used 929 * to induce exceptions in asynchronous tasks, or to force 930 * completion of tasks that would not otherwise complete. Its use 931 * in other situations is discouraged. This method is 932 * overridable, but overridden versions must invoke {@code super} 933 * implementation to maintain guarantees. 934 * 935 * @param ex the exception to throw. If this exception is not a 936 * {@code RuntimeException} or {@code Error}, the actual exception 937 * thrown will be a {@code RuntimeException} with cause {@code ex}. 938 */ completeExceptionally(Throwable ex)939 public void completeExceptionally(Throwable ex) { 940 setExceptionalCompletion((ex instanceof RuntimeException) || 941 (ex instanceof Error) ? ex : 942 new RuntimeException(ex)); 943 } 944 945 /** 946 * Completes this task, and if not already aborted or cancelled, 947 * returning the given value as the result of subsequent 948 * invocations of {@code join} and related operations. This method 949 * may be used to provide results for asynchronous tasks, or to 950 * provide alternative handling for tasks that would not otherwise 951 * complete normally. Its use in other situations is 952 * discouraged. This method is overridable, but overridden 953 * versions must invoke {@code super} implementation to maintain 954 * guarantees. 955 * 956 * @param value the result value for this task 957 */ complete(V value)958 public void complete(V value) { 959 try { 960 setRawResult(value); 961 } catch (Throwable rex) { 962 setExceptionalCompletion(rex); 963 return; 964 } 965 setCompletion(NORMAL); 966 } 967 968 /** 969 * Completes this task normally without setting a value. The most 970 * recent value established by {@link #setRawResult} (or {@code 971 * null} by default) will be returned as the result of subsequent 972 * invocations of {@code join} and related operations. 973 * 974 * @since 1.8 975 */ quietlyComplete()976 public final void quietlyComplete() { 977 setCompletion(NORMAL); 978 } 979 980 /** 981 * Waits if necessary for the computation to complete, and then 982 * retrieves its result. 983 * 984 * @return the computed result 985 * @throws CancellationException if the computation was cancelled 986 * @throws ExecutionException if the computation threw an 987 * exception 988 * @throws InterruptedException if the current thread is not a 989 * member of a ForkJoinPool and was interrupted while waiting 990 */ get()991 public final V get() throws InterruptedException, ExecutionException { 992 int s = (Thread.currentThread() instanceof ForkJoinWorkerThread) ? 993 doJoin() : externalInterruptibleAwaitDone(); 994 if ((s &= DONE_MASK) == CANCELLED) 995 throw new CancellationException(); 996 if (s == EXCEPTIONAL) 997 throw new ExecutionException(getThrowableException()); 998 return getRawResult(); 999 } 1000 1001 /** 1002 * Waits if necessary for at most the given time for the computation 1003 * to complete, and then retrieves its result, if available. 1004 * 1005 * @param timeout the maximum time to wait 1006 * @param unit the time unit of the timeout argument 1007 * @return the computed result 1008 * @throws CancellationException if the computation was cancelled 1009 * @throws ExecutionException if the computation threw an 1010 * exception 1011 * @throws InterruptedException if the current thread is not a 1012 * member of a ForkJoinPool and was interrupted while waiting 1013 * @throws TimeoutException if the wait timed out 1014 */ get(long timeout, TimeUnit unit)1015 public final V get(long timeout, TimeUnit unit) 1016 throws InterruptedException, ExecutionException, TimeoutException { 1017 int s; 1018 long nanos = unit.toNanos(timeout); 1019 if (Thread.interrupted()) 1020 throw new InterruptedException(); 1021 if ((s = status) >= 0 && nanos > 0L) { 1022 long d = System.nanoTime() + nanos; 1023 long deadline = (d == 0L) ? 1L : d; // avoid 0 1024 Thread t = Thread.currentThread(); 1025 if (t instanceof ForkJoinWorkerThread) { 1026 ForkJoinWorkerThread wt = (ForkJoinWorkerThread)t; 1027 s = wt.pool.awaitJoin(wt.workQueue, this, deadline); 1028 } 1029 else if ((s = ((this instanceof CountedCompleter) ? 1030 ForkJoinPool.common.externalHelpComplete( 1031 (CountedCompleter<?>)this, 0) : 1032 ForkJoinPool.common.tryExternalUnpush(this) ? 1033 doExec() : 0)) >= 0) { 1034 long ns, ms; // measure in nanosecs, but wait in millisecs 1035 while ((s = status) >= 0 && 1036 (ns = deadline - System.nanoTime()) > 0L) { 1037 if ((ms = TimeUnit.NANOSECONDS.toMillis(ns)) > 0L && 1038 U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) { 1039 synchronized (this) { 1040 if (status >= 0) 1041 wait(ms); // OK to throw InterruptedException 1042 else 1043 notifyAll(); 1044 } 1045 } 1046 } 1047 } 1048 } 1049 if (s >= 0) 1050 s = status; 1051 if ((s &= DONE_MASK) != NORMAL) { 1052 if (s == CANCELLED) 1053 throw new CancellationException(); 1054 if (s != EXCEPTIONAL) 1055 throw new TimeoutException(); 1056 throw new ExecutionException(getThrowableException()); 1057 } 1058 return getRawResult(); 1059 } 1060 1061 /** 1062 * Joins this task, without returning its result or throwing its 1063 * exception. This method may be useful when processing 1064 * collections of tasks when some have been cancelled or otherwise 1065 * known to have aborted. 1066 */ quietlyJoin()1067 public final void quietlyJoin() { 1068 doJoin(); 1069 } 1070 1071 /** 1072 * Commences performing this task and awaits its completion if 1073 * necessary, without returning its result or throwing its 1074 * exception. 1075 */ quietlyInvoke()1076 public final void quietlyInvoke() { 1077 doInvoke(); 1078 } 1079 1080 /** 1081 * Possibly executes tasks until the pool hosting the current task 1082 * {@linkplain ForkJoinPool#isQuiescent is quiescent}. This 1083 * method may be of use in designs in which many tasks are forked, 1084 * but none are explicitly joined, instead executing them until 1085 * all are processed. 1086 */ helpQuiesce()1087 public static void helpQuiesce() { 1088 Thread t; 1089 if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) { 1090 ForkJoinWorkerThread wt = (ForkJoinWorkerThread)t; 1091 wt.pool.helpQuiescePool(wt.workQueue); 1092 } 1093 else 1094 ForkJoinPool.quiesceCommonPool(); 1095 } 1096 1097 /** 1098 * Resets the internal bookkeeping state of this task, allowing a 1099 * subsequent {@code fork}. This method allows repeated reuse of 1100 * this task, but only if reuse occurs when this task has either 1101 * never been forked, or has been forked, then completed and all 1102 * outstanding joins of this task have also completed. Effects 1103 * under any other usage conditions are not guaranteed. 1104 * This method may be useful when executing 1105 * pre-constructed trees of subtasks in loops. 1106 * 1107 * <p>Upon completion of this method, {@code isDone()} reports 1108 * {@code false}, and {@code getException()} reports {@code 1109 * null}. However, the value returned by {@code getRawResult} is 1110 * unaffected. To clear this value, you can invoke {@code 1111 * setRawResult(null)}. 1112 */ reinitialize()1113 public void reinitialize() { 1114 if ((status & DONE_MASK) == EXCEPTIONAL) 1115 clearExceptionalCompletion(); 1116 else 1117 status = 0; 1118 } 1119 1120 /** 1121 * Returns the pool hosting the current thread, or {@code null} 1122 * if the current thread is executing outside of any ForkJoinPool. 1123 * 1124 * <p>This method returns {@code null} if and only if {@link 1125 * #inForkJoinPool} returns {@code false}. 1126 * 1127 * @return the pool, or {@code null} if none 1128 */ getPool()1129 public static ForkJoinPool getPool() { 1130 Thread t = Thread.currentThread(); 1131 return (t instanceof ForkJoinWorkerThread) ? 1132 ((ForkJoinWorkerThread) t).pool : null; 1133 } 1134 1135 /** 1136 * Returns {@code true} if the current thread is a {@link 1137 * ForkJoinWorkerThread} executing as a ForkJoinPool computation. 1138 * 1139 * @return {@code true} if the current thread is a {@link 1140 * ForkJoinWorkerThread} executing as a ForkJoinPool computation, 1141 * or {@code false} otherwise 1142 */ inForkJoinPool()1143 public static boolean inForkJoinPool() { 1144 return Thread.currentThread() instanceof ForkJoinWorkerThread; 1145 } 1146 1147 /** 1148 * Tries to unschedule this task for execution. This method will 1149 * typically (but is not guaranteed to) succeed if this task is 1150 * the most recently forked task by the current thread, and has 1151 * not commenced executing in another thread. This method may be 1152 * useful when arranging alternative local processing of tasks 1153 * that could have been, but were not, stolen. 1154 * 1155 * @return {@code true} if unforked 1156 */ tryUnfork()1157 public boolean tryUnfork() { 1158 Thread t; 1159 return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ? 1160 ((ForkJoinWorkerThread)t).workQueue.tryUnpush(this) : 1161 ForkJoinPool.common.tryExternalUnpush(this)); 1162 } 1163 1164 /** 1165 * Returns an estimate of the number of tasks that have been 1166 * forked by the current worker thread but not yet executed. This 1167 * value may be useful for heuristic decisions about whether to 1168 * fork other tasks. 1169 * 1170 * @return the number of tasks 1171 */ getQueuedTaskCount()1172 public static int getQueuedTaskCount() { 1173 Thread t; ForkJoinPool.WorkQueue q; 1174 if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) 1175 q = ((ForkJoinWorkerThread)t).workQueue; 1176 else 1177 q = ForkJoinPool.commonSubmitterQueue(); 1178 return (q == null) ? 0 : q.queueSize(); 1179 } 1180 1181 /** 1182 * Returns an estimate of how many more locally queued tasks are 1183 * held by the current worker thread than there are other worker 1184 * threads that might steal them, or zero if this thread is not 1185 * operating in a ForkJoinPool. This value may be useful for 1186 * heuristic decisions about whether to fork other tasks. In many 1187 * usages of ForkJoinTasks, at steady state, each worker should 1188 * aim to maintain a small constant surplus (for example, 3) of 1189 * tasks, and to process computations locally if this threshold is 1190 * exceeded. 1191 * 1192 * @return the surplus number of tasks, which may be negative 1193 */ getSurplusQueuedTaskCount()1194 public static int getSurplusQueuedTaskCount() { 1195 return ForkJoinPool.getSurplusQueuedTaskCount(); 1196 } 1197 1198 // Extension methods 1199 1200 /** 1201 * Returns the result that would be returned by {@link #join}, even 1202 * if this task completed abnormally, or {@code null} if this task 1203 * is not known to have been completed. This method is designed 1204 * to aid debugging, as well as to support extensions. Its use in 1205 * any other context is discouraged. 1206 * 1207 * @return the result, or {@code null} if not completed 1208 */ getRawResult()1209 public abstract V getRawResult(); 1210 1211 /** 1212 * Forces the given value to be returned as a result. This method 1213 * is designed to support extensions, and should not in general be 1214 * called otherwise. 1215 * 1216 * @param value the value 1217 */ setRawResult(V value)1218 protected abstract void setRawResult(V value); 1219 1220 /** 1221 * Immediately performs the base action of this task and returns 1222 * true if, upon return from this method, this task is guaranteed 1223 * to have completed normally. This method may return false 1224 * otherwise, to indicate that this task is not necessarily 1225 * complete (or is not known to be complete), for example in 1226 * asynchronous actions that require explicit invocations of 1227 * completion methods. This method may also throw an (unchecked) 1228 * exception to indicate abnormal exit. This method is designed to 1229 * support extensions, and should not in general be called 1230 * otherwise. 1231 * 1232 * @return {@code true} if this task is known to have completed normally 1233 */ exec()1234 protected abstract boolean exec(); 1235 1236 /** 1237 * Returns, but does not unschedule or execute, a task queued by 1238 * the current thread but not yet executed, if one is immediately 1239 * available. There is no guarantee that this task will actually 1240 * be polled or executed next. Conversely, this method may return 1241 * null even if a task exists but cannot be accessed without 1242 * contention with other threads. This method is designed 1243 * primarily to support extensions, and is unlikely to be useful 1244 * otherwise. 1245 * 1246 * @return the next task, or {@code null} if none are available 1247 */ peekNextLocalTask()1248 protected static ForkJoinTask<?> peekNextLocalTask() { 1249 Thread t; ForkJoinPool.WorkQueue q; 1250 if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) 1251 q = ((ForkJoinWorkerThread)t).workQueue; 1252 else 1253 q = ForkJoinPool.commonSubmitterQueue(); 1254 return (q == null) ? null : q.peek(); 1255 } 1256 1257 /** 1258 * Unschedules and returns, without executing, the next task 1259 * queued by the current thread but not yet executed, if the 1260 * current thread is operating in a ForkJoinPool. This method is 1261 * designed primarily to support extensions, and is unlikely to be 1262 * useful otherwise. 1263 * 1264 * @return the next task, or {@code null} if none are available 1265 */ pollNextLocalTask()1266 protected static ForkJoinTask<?> pollNextLocalTask() { 1267 Thread t; 1268 return ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ? 1269 ((ForkJoinWorkerThread)t).workQueue.nextLocalTask() : 1270 null; 1271 } 1272 1273 /** 1274 * If the current thread is operating in a ForkJoinPool, 1275 * unschedules and returns, without executing, the next task 1276 * queued by the current thread but not yet executed, if one is 1277 * available, or if not available, a task that was forked by some 1278 * other thread, if available. Availability may be transient, so a 1279 * {@code null} result does not necessarily imply quiescence of 1280 * the pool this task is operating in. This method is designed 1281 * primarily to support extensions, and is unlikely to be useful 1282 * otherwise. 1283 * 1284 * @return a task, or {@code null} if none are available 1285 */ pollTask()1286 protected static ForkJoinTask<?> pollTask() { 1287 Thread t; ForkJoinWorkerThread wt; 1288 return ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ? 1289 (wt = (ForkJoinWorkerThread)t).pool.nextTaskFor(wt.workQueue) : 1290 null; 1291 } 1292 1293 /** 1294 * If the current thread is operating in a ForkJoinPool, 1295 * unschedules and returns, without executing, a task externally 1296 * submitted to the pool, if one is available. Availability may be 1297 * transient, so a {@code null} result does not necessarily imply 1298 * quiescence of the pool. This method is designed primarily to 1299 * support extensions, and is unlikely to be useful otherwise. 1300 * 1301 * @return a task, or {@code null} if none are available 1302 * @since 9 1303 * @hide 1304 */ 1305 // Android-changed: hidden pollSubmission()1306 protected static ForkJoinTask<?> pollSubmission() { 1307 Thread t; 1308 return ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ? 1309 ((ForkJoinWorkerThread)t).pool.pollSubmission() : null; 1310 } 1311 1312 // tag operations 1313 1314 /** 1315 * Returns the tag for this task. 1316 * 1317 * @return the tag for this task 1318 * @since 1.8 1319 */ getForkJoinTaskTag()1320 public final short getForkJoinTaskTag() { 1321 return (short)status; 1322 } 1323 1324 /** 1325 * Atomically sets the tag value for this task and returns the old value. 1326 * 1327 * @param newValue the new tag value 1328 * @return the previous value of the tag 1329 * @since 1.8 1330 */ setForkJoinTaskTag(short newValue)1331 public final short setForkJoinTaskTag(short newValue) { 1332 for (int s;;) { 1333 if (U.compareAndSwapInt(this, STATUS, s = status, 1334 (s & ~SMASK) | (newValue & SMASK))) 1335 return (short)s; 1336 } 1337 } 1338 1339 /** 1340 * Atomically conditionally sets the tag value for this task. 1341 * Among other applications, tags can be used as visit markers 1342 * in tasks operating on graphs, as in methods that check: {@code 1343 * if (task.compareAndSetForkJoinTaskTag((short)0, (short)1))} 1344 * before processing, otherwise exiting because the node has 1345 * already been visited. 1346 * 1347 * @param expect the expected tag value 1348 * @param update the new tag value 1349 * @return {@code true} if successful; i.e., the current value was 1350 * equal to {@code expect} and was changed to {@code update}. 1351 * @since 1.8 1352 */ compareAndSetForkJoinTaskTag(short expect, short update)1353 public final boolean compareAndSetForkJoinTaskTag(short expect, short update) { 1354 for (int s;;) { 1355 if ((short)(s = status) != expect) 1356 return false; 1357 if (U.compareAndSwapInt(this, STATUS, s, 1358 (s & ~SMASK) | (update & SMASK))) 1359 return true; 1360 } 1361 } 1362 1363 /** 1364 * Adapter for Runnables. This implements RunnableFuture 1365 * to be compliant with AbstractExecutorService constraints 1366 * when used in ForkJoinPool. 1367 */ 1368 static final class AdaptedRunnable<T> extends ForkJoinTask<T> 1369 implements RunnableFuture<T> { 1370 final Runnable runnable; 1371 T result; AdaptedRunnable(Runnable runnable, T result)1372 AdaptedRunnable(Runnable runnable, T result) { 1373 if (runnable == null) throw new NullPointerException(); 1374 this.runnable = runnable; 1375 this.result = result; // OK to set this even before completion 1376 } getRawResult()1377 public final T getRawResult() { return result; } setRawResult(T v)1378 public final void setRawResult(T v) { result = v; } exec()1379 public final boolean exec() { runnable.run(); return true; } run()1380 public final void run() { invoke(); } 1381 private static final long serialVersionUID = 5232453952276885070L; 1382 } 1383 1384 /** 1385 * Adapter for Runnables without results. 1386 */ 1387 static final class AdaptedRunnableAction extends ForkJoinTask<Void> 1388 implements RunnableFuture<Void> { 1389 final Runnable runnable; AdaptedRunnableAction(Runnable runnable)1390 AdaptedRunnableAction(Runnable runnable) { 1391 if (runnable == null) throw new NullPointerException(); 1392 this.runnable = runnable; 1393 } getRawResult()1394 public final Void getRawResult() { return null; } setRawResult(Void v)1395 public final void setRawResult(Void v) { } exec()1396 public final boolean exec() { runnable.run(); return true; } run()1397 public final void run() { invoke(); } 1398 private static final long serialVersionUID = 5232453952276885070L; 1399 } 1400 1401 /** 1402 * Adapter for Runnables in which failure forces worker exception. 1403 */ 1404 static final class RunnableExecuteAction extends ForkJoinTask<Void> { 1405 final Runnable runnable; RunnableExecuteAction(Runnable runnable)1406 RunnableExecuteAction(Runnable runnable) { 1407 if (runnable == null) throw new NullPointerException(); 1408 this.runnable = runnable; 1409 } getRawResult()1410 public final Void getRawResult() { return null; } setRawResult(Void v)1411 public final void setRawResult(Void v) { } exec()1412 public final boolean exec() { runnable.run(); return true; } internalPropagateException(Throwable ex)1413 void internalPropagateException(Throwable ex) { 1414 rethrow(ex); // rethrow outside exec() catches. 1415 } 1416 private static final long serialVersionUID = 5232453952276885070L; 1417 } 1418 1419 /** 1420 * Adapter for Callables. 1421 */ 1422 static final class AdaptedCallable<T> extends ForkJoinTask<T> 1423 implements RunnableFuture<T> { 1424 final Callable<? extends T> callable; 1425 T result; AdaptedCallable(Callable<? extends T> callable)1426 AdaptedCallable(Callable<? extends T> callable) { 1427 if (callable == null) throw new NullPointerException(); 1428 this.callable = callable; 1429 } getRawResult()1430 public final T getRawResult() { return result; } setRawResult(T v)1431 public final void setRawResult(T v) { result = v; } exec()1432 public final boolean exec() { 1433 try { 1434 result = callable.call(); 1435 return true; 1436 } catch (RuntimeException rex) { 1437 throw rex; 1438 } catch (Exception ex) { 1439 throw new RuntimeException(ex); 1440 } 1441 } run()1442 public final void run() { invoke(); } 1443 private static final long serialVersionUID = 2838392045355241008L; 1444 } 1445 1446 /** 1447 * Returns a new {@code ForkJoinTask} that performs the {@code run} 1448 * method of the given {@code Runnable} as its action, and returns 1449 * a null result upon {@link #join}. 1450 * 1451 * @param runnable the runnable action 1452 * @return the task 1453 */ adapt(Runnable runnable)1454 public static ForkJoinTask<?> adapt(Runnable runnable) { 1455 return new AdaptedRunnableAction(runnable); 1456 } 1457 1458 /** 1459 * Returns a new {@code ForkJoinTask} that performs the {@code run} 1460 * method of the given {@code Runnable} as its action, and returns 1461 * the given result upon {@link #join}. 1462 * 1463 * @param runnable the runnable action 1464 * @param result the result upon completion 1465 * @param <T> the type of the result 1466 * @return the task 1467 */ adapt(Runnable runnable, T result)1468 public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) { 1469 return new AdaptedRunnable<T>(runnable, result); 1470 } 1471 1472 /** 1473 * Returns a new {@code ForkJoinTask} that performs the {@code call} 1474 * method of the given {@code Callable} as its action, and returns 1475 * its result upon {@link #join}, translating any checked exceptions 1476 * encountered into {@code RuntimeException}. 1477 * 1478 * @param callable the callable action 1479 * @param <T> the type of the callable's result 1480 * @return the task 1481 */ adapt(Callable<? extends T> callable)1482 public static <T> ForkJoinTask<T> adapt(Callable<? extends T> callable) { 1483 return new AdaptedCallable<T>(callable); 1484 } 1485 1486 // Serialization support 1487 1488 private static final long serialVersionUID = -7721805057305804111L; 1489 1490 /** 1491 * Saves this task to a stream (that is, serializes it). 1492 * 1493 * @param s the stream 1494 * @throws java.io.IOException if an I/O error occurs 1495 * @serialData the current run status and the exception thrown 1496 * during execution, or {@code null} if none 1497 */ writeObject(java.io.ObjectOutputStream s)1498 private void writeObject(java.io.ObjectOutputStream s) 1499 throws java.io.IOException { 1500 s.defaultWriteObject(); 1501 s.writeObject(getException()); 1502 } 1503 1504 /** 1505 * Reconstitutes this task from a stream (that is, deserializes it). 1506 * @param s the stream 1507 * @throws ClassNotFoundException if the class of a serialized object 1508 * could not be found 1509 * @throws java.io.IOException if an I/O error occurs 1510 */ readObject(java.io.ObjectInputStream s)1511 private void readObject(java.io.ObjectInputStream s) 1512 throws java.io.IOException, ClassNotFoundException { 1513 s.defaultReadObject(); 1514 Object ex = s.readObject(); 1515 if (ex != null) 1516 setExceptionalCompletion((Throwable)ex); 1517 } 1518 1519 // Unsafe mechanics 1520 private static final sun.misc.Unsafe U = sun.misc.Unsafe.getUnsafe(); 1521 private static final long STATUS; 1522 1523 static { 1524 exceptionTableLock = new ReentrantLock(); 1525 exceptionTableRefQueue = new ReferenceQueue<Object>(); 1526 exceptionTable = new ExceptionNode[EXCEPTION_MAP_CAPACITY]; 1527 try { 1528 STATUS = U.objectFieldOffset 1529 (ForkJoinTask.class.getDeclaredField("status")); 1530 } catch (ReflectiveOperationException e) { 1531 throw new Error(e); 1532 } 1533 } 1534 1535 } 1536