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