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