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