ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/ForkJoinTask.java
Revision: 1.52
Committed: Sat Jul 24 20:28:18 2010 UTC (13 years, 9 months ago) by dl
Branch: MAIN
Changes since 1.51: +10 -9 lines
Log Message:
Fix and simplify joinTask

File Contents

# Content
1 /*
2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 * Expert Group and released to the public domain, as explained at
4 * http://creativecommons.org/licenses/publicdomain
5 */
6
7 package jsr166y;
8
9 import java.util.concurrent.*;
10
11 import java.io.Serializable;
12 import java.util.Collection;
13 import java.util.Collections;
14 import java.util.List;
15 import java.util.RandomAccess;
16 import java.util.Map;
17 import java.util.WeakHashMap;
18
19 /**
20 * Abstract base class for tasks that run within a {@link ForkJoinPool}.
21 * A {@code ForkJoinTask} is a thread-like entity that is much
22 * lighter weight than a normal thread. Huge numbers of tasks and
23 * subtasks may be hosted by a small number of actual threads in a
24 * ForkJoinPool, at the price of some usage limitations.
25 *
26 * <p>A "main" {@code ForkJoinTask} begins execution when submitted
27 * to a {@link ForkJoinPool}. Once started, it will usually in turn
28 * start other subtasks. As indicated by the name of this class,
29 * many programs using {@code ForkJoinTask} employ only methods
30 * {@link #fork} and {@link #join}, or derivatives such as {@link
31 * #invokeAll}. However, this class also provides a number of other
32 * methods that can come into play in advanced usages, as well as
33 * extension mechanics that allow support of new forms of fork/join
34 * processing.
35 *
36 * <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}.
37 * The efficiency of {@code ForkJoinTask}s stems from a set of
38 * restrictions (that are only partially statically enforceable)
39 * reflecting their intended use as computational tasks calculating
40 * pure functions or operating on purely isolated objects. The
41 * primary coordination mechanisms are {@link #fork}, that arranges
42 * asynchronous execution, and {@link #join}, that doesn't proceed
43 * until the task's result has been computed. Computations should
44 * avoid {@code synchronized} methods or blocks, and should minimize
45 * other blocking synchronization apart from joining other tasks or
46 * using synchronizers such as Phasers that are advertised to
47 * cooperate with fork/join scheduling. Tasks should also not perform
48 * blocking IO, and should ideally access variables that are
49 * completely independent of those accessed by other running
50 * tasks. Minor breaches of these restrictions, for example using
51 * shared output streams, may be tolerable in practice, but frequent
52 * use may result in poor performance, and the potential to
53 * indefinitely stall if the number of threads not waiting for IO or
54 * other external synchronization becomes exhausted. This usage
55 * restriction is in part enforced by not permitting checked
56 * exceptions such as {@code IOExceptions} to be thrown. However,
57 * computations may still encounter unchecked exceptions, that are
58 * rethrown to callers attempting to join them. These exceptions may
59 * additionally include {@link RejectedExecutionException} stemming
60 * from internal resource exhaustion, such as failure to allocate
61 * internal task queues.
62 *
63 * <p>The primary method for awaiting completion and extracting
64 * results of a task is {@link #join}, but there are several variants:
65 * The {@link Future#get} methods support interruptible and/or timed
66 * waits for completion and report results using {@code Future}
67 * conventions. Method {@link #invoke} is semantically
68 * equivalent to {@code fork(); join()} but always attempts to begin
69 * execution in the current thread. The "<em>quiet</em>" forms of
70 * these methods do not extract results or report exceptions. These
71 * may be useful when a set of tasks are being executed, and you need
72 * to delay processing of results or exceptions until all complete.
73 * Method {@code invokeAll} (available in multiple versions)
74 * performs the most common form of parallel invocation: forking a set
75 * of tasks and joining them all.
76 *
77 * <p>The execution status of tasks may be queried at several levels
78 * of detail: {@link #isDone} is true if a task completed in any way
79 * (including the case where a task was cancelled without executing);
80 * {@link #isCompletedNormally} is true if a task completed without
81 * cancellation or encountering an exception; {@link #isCancelled} is
82 * true if the task was cancelled (in which case {@link #getException}
83 * returns a {@link java.util.concurrent.CancellationException}); and
84 * {@link #isCompletedAbnormally} is true if a task was either
85 * cancelled or encountered an exception, in which case {@link
86 * #getException} will return either the encountered exception or
87 * {@link java.util.concurrent.CancellationException}.
88 *
89 * <p>The ForkJoinTask class is not usually directly subclassed.
90 * Instead, you subclass one of the abstract classes that support a
91 * particular style of fork/join processing, typically {@link
92 * RecursiveAction} for computations that do not return results, or
93 * {@link RecursiveTask} for those that do. Normally, a concrete
94 * ForkJoinTask subclass declares fields comprising its parameters,
95 * established in a constructor, and then defines a {@code compute}
96 * method that somehow uses the control methods supplied by this base
97 * class. While these methods have {@code public} access (to allow
98 * instances of different task subclasses to call each other's
99 * methods), some of them may only be called from within other
100 * ForkJoinTasks (as may be determined using method {@link
101 * #inForkJoinPool}). Attempts to invoke them in other contexts
102 * result in exceptions or errors, possibly including
103 * ClassCastException.
104 *
105 * <p>Most base support methods are {@code final}, to prevent
106 * overriding of implementations that are intrinsically tied to the
107 * underlying lightweight task scheduling framework. Developers
108 * creating new basic styles of fork/join processing should minimally
109 * implement {@code protected} methods {@link #exec}, {@link
110 * #setRawResult}, and {@link #getRawResult}, while also introducing
111 * an abstract computational method that can be implemented in its
112 * subclasses, possibly relying on other {@code protected} methods
113 * provided by this class.
114 *
115 * <p>ForkJoinTasks should perform relatively small amounts of
116 * computation. Large tasks should be split into smaller subtasks,
117 * usually via recursive decomposition. As a very rough rule of thumb,
118 * a task should perform more than 100 and less than 10000 basic
119 * computational steps. If tasks are too big, then parallelism cannot
120 * improve throughput. If too small, then memory and internal task
121 * maintenance overhead may overwhelm processing.
122 *
123 * <p>This class provides {@code adapt} methods for {@link Runnable}
124 * and {@link Callable}, that may be of use when mixing execution of
125 * {@code ForkJoinTasks} with other kinds of tasks. When all tasks are
126 * of this form, consider using a pool constructed in <em>asyncMode</em>.
127 *
128 * <p>ForkJoinTasks are {@code Serializable}, which enables them to be
129 * used in extensions such as remote execution frameworks. It is
130 * sensible to serialize tasks only before or after, but not during,
131 * execution. Serialization is not relied on during execution itself.
132 *
133 * @since 1.7
134 * @author Doug Lea
135 */
136 public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
137
138 /*
139 * See the internal documentation of class ForkJoinPool for a
140 * general implementation overview. ForkJoinTasks are mainly
141 * responsible for maintaining their "status" field amidst relays
142 * to methods in ForkJoinWorkerThread and ForkJoinPool. The
143 * methods of this class are more-or-less layered into (1) basic
144 * status maintenance (2) execution and awaiting completion (3)
145 * user-level methods that additionally report results. This is
146 * sometimes hard to see because this file orders exported methods
147 * in a way that flows well in javadocs.
148 */
149
150 /*
151 * The status field holds run control status bits packed into a
152 * single int to minimize footprint and to ensure atomicity (via
153 * CAS). Status is initially zero, and takes on nonnegative
154 * values until completed, upon which status holds value
155 * COMPLETED. CANCELLED, or EXCEPTIONAL. Tasks undergoing blocking
156 * waits by other threads have the SIGNAL bit set. Completion of
157 * a stolen task with SIGNAL set awakens any waiters via
158 * notifyAll. Even though suboptimal for some purposes, we use
159 * basic builtin wait/notify to take advantage of "monitor
160 * inflation" in JVMs that we would otherwise need to emulate to
161 * avoid adding further per-task bookkeeping overhead. We want
162 * these monitors to be "fat", i.e., not use biasing or thin-lock
163 * techniques, so use some odd coding idioms that tend to avoid
164 * them.
165 */
166
167 /** Run status of this task */
168 volatile int status; // accessed directly by pool and workers
169
170 private static final int NORMAL = -1;
171 private static final int CANCELLED = -2;
172 private static final int EXCEPTIONAL = -3;
173 private static final int SIGNAL = 1;
174
175 /**
176 * Table of exceptions thrown by tasks, to enable reporting by
177 * callers. Because exceptions are rare, we don't directly keep
178 * them with task objects, but instead use a weak ref table. Note
179 * that cancellation exceptions don't appear in the table, but are
180 * instead recorded as status values.
181 * TODO: Use ConcurrentReferenceHashMap
182 */
183 static final Map<ForkJoinTask<?>, Throwable> exceptionMap =
184 Collections.synchronizedMap
185 (new WeakHashMap<ForkJoinTask<?>, Throwable>());
186
187 // Maintaining completion status
188
189 /**
190 * Marks completion and wakes up threads waiting to join this task,
191 * also clearing signal request bits.
192 *
193 * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
194 * @return status on exit
195 */
196 private int setCompletion(int completion) {
197 int s;
198 while ((s = status) >= 0) {
199 if (UNSAFE.compareAndSwapInt(this, statusOffset, s, completion)) {
200 if (s != 0)
201 synchronized (this) { notifyAll(); }
202 return completion;
203 }
204 }
205 return s;
206 }
207
208 /**
209 * Record exception and set exceptional completion
210 * @return status on exit
211 */
212 private int setExceptionalCompletion(Throwable rex) {
213 exceptionMap.put(this, rex);
214 return setCompletion(EXCEPTIONAL);
215 }
216
217 /**
218 * Blocks a worker thread until completion. Called only by pool.
219 */
220 final void internalAwaitDone() {
221 int s; // the odd construction reduces lock bias effects
222 while ((s = status) >= 0) {
223 try {
224 synchronized(this) {
225 if (UNSAFE.compareAndSwapInt(this, statusOffset, s,SIGNAL))
226 wait();
227 }
228 } catch (InterruptedException ie) {
229 cancelIfTerminating();
230 }
231 }
232 }
233
234 /**
235 * Blocks a non-worker-thread until completion.
236 * @return status on exit
237 */
238 private int externalAwaitDone() {
239 int s;
240 while ((s = status) >= 0) {
241 synchronized(this) {
242 if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)){
243 boolean interrupted = false;
244 while ((s = status) >= 0) {
245 try {
246 wait();
247 } catch (InterruptedException ie) {
248 interrupted = true;
249 }
250 }
251 if (interrupted)
252 Thread.currentThread().interrupt();
253 break;
254 }
255 }
256 }
257 return s;
258 }
259
260 /**
261 * Unless done, calls exec and records status if completed, but
262 * doesn't wait for completion otherwise. Primary execution method
263 * for ForkJoinWorkerThread.
264 */
265 final void tryExec() {
266 try {
267 if (status < 0 || !exec())
268 return;
269 } catch (Throwable rex) {
270 setExceptionalCompletion(rex);
271 return;
272 }
273 setCompletion(NORMAL); // must be outside try block
274 }
275
276 /**
277 * If not done and this task is next in worker queue, runs it,
278 * else waits for it.
279 * @return status on exit
280 */
281 private int doJoin() {
282 int stat;
283 Thread t;
284 ForkJoinWorkerThread w;
285 if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
286 if ((stat = status) < 0)
287 return stat;
288 if ((w = (ForkJoinWorkerThread) t).unpushTask(this)) {
289 boolean completed;
290 try {
291 completed = exec();
292 } catch (Throwable rex) {
293 return setExceptionalCompletion(rex);
294 }
295 if (completed)
296 return setCompletion(NORMAL);
297 }
298 return w.joinTask(this);
299 }
300 return externalAwaitDone();
301 }
302
303 /**
304 * Unless done, calls exec and records status if completed, or
305 * waits for completion otherwise.
306 * @return status on exit
307 */
308 private int doInvoke() {
309 int stat;
310 if ((stat = status) >= 0) {
311 boolean completed;
312 try {
313 completed = exec();
314 } catch (Throwable rex) {
315 return setExceptionalCompletion(rex);
316 }
317 stat = completed ? setCompletion(NORMAL) : doJoin();
318 }
319 return stat;
320 }
321
322 /**
323 * Returns result or throws exception associated with given status.
324 * @param s the status
325 */
326 private V reportResult(int s) {
327 Throwable ex;
328 if (s < NORMAL && (ex = getException()) != null)
329 UNSAFE.throwException(ex);
330 return getRawResult();
331 }
332
333 // public methods
334
335 /**
336 * Arranges to asynchronously execute this task. While it is not
337 * necessarily enforced, it is a usage error to fork a task more
338 * than once unless it has completed and been reinitialized.
339 * Subsequent modifications to the state of this task or any data
340 * it operates on are not necessarily consistently observable by
341 * any thread other than the one executing it unless preceded by a
342 * call to {@link #join} or related methods, or a call to {@link
343 * #isDone} returning {@code true}.
344 *
345 * <p>This method may be invoked only from within {@code
346 * ForkJoinTask} computations (as may be determined using method
347 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
348 * result in exceptions or errors, possibly including {@code
349 * ClassCastException}.
350 *
351 * @return {@code this}, to simplify usage
352 */
353 public final ForkJoinTask<V> fork() {
354 ((ForkJoinWorkerThread) Thread.currentThread())
355 .pushTask(this);
356 return this;
357 }
358
359 /**
360 * Returns the result of the computation when it {@link #isDone is done}.
361 * This method differs from {@link #get()} in that
362 * abnormal completion results in {@code RuntimeException} or
363 * {@code Error}, not {@code ExecutionException}.
364 *
365 * @return the computed result
366 */
367 public final V join() {
368 return reportResult(doJoin());
369 }
370
371 /**
372 * Commences performing this task, awaits its completion if
373 * necessary, and return its result, or throws an (unchecked)
374 * exception if the underlying computation did so.
375 *
376 * @return the computed result
377 */
378 public final V invoke() {
379 return reportResult(doInvoke());
380 }
381
382 /**
383 * Forks the given tasks, returning when {@code isDone} holds for
384 * each task or an (unchecked) exception is encountered, in which
385 * case the exception is rethrown. If either task encounters an
386 * exception, the other one may be, but is not guaranteed to be,
387 * cancelled. If both tasks throw an exception, then this method
388 * throws one of them. The individual status of each task may be
389 * checked using {@link #getException()} and related methods.
390 *
391 * <p>This method may be invoked only from within {@code
392 * ForkJoinTask} computations (as may be determined using method
393 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
394 * result in exceptions or errors, possibly including {@code
395 * ClassCastException}.
396 *
397 * @param t1 the first task
398 * @param t2 the second task
399 * @throws NullPointerException if any task is null
400 */
401 public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) {
402 t2.fork();
403 t1.invoke();
404 t2.join();
405 }
406
407 /**
408 * Forks the given tasks, returning when {@code isDone} holds for
409 * each task or an (unchecked) exception is encountered, in which
410 * case the exception is rethrown. If any task encounters an
411 * exception, others may be, but are not guaranteed to be,
412 * cancelled. If more than one task encounters an exception, then
413 * this method throws any one of these exceptions. The individual
414 * status of each task may be checked using {@link #getException()}
415 * and related methods.
416 *
417 * <p>This method may be invoked only from within {@code
418 * ForkJoinTask} computations (as may be determined using method
419 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
420 * result in exceptions or errors, possibly including {@code
421 * ClassCastException}.
422 *
423 * @param tasks the tasks
424 * @throws NullPointerException if any task is null
425 */
426 public static void invokeAll(ForkJoinTask<?>... tasks) {
427 Throwable ex = null;
428 int last = tasks.length - 1;
429 for (int i = last; i >= 0; --i) {
430 ForkJoinTask<?> t = tasks[i];
431 if (t == null) {
432 if (ex == null)
433 ex = new NullPointerException();
434 }
435 else if (i != 0)
436 t.fork();
437 else if (t.doInvoke() < NORMAL && ex == null)
438 ex = t.getException();
439 }
440 for (int i = 1; i <= last; ++i) {
441 ForkJoinTask<?> t = tasks[i];
442 if (t != null) {
443 if (ex != null)
444 t.cancel(false);
445 else if (t.doJoin() < NORMAL && ex == null)
446 ex = t.getException();
447 }
448 }
449 if (ex != null)
450 UNSAFE.throwException(ex);
451 }
452
453 /**
454 * Forks all tasks in the specified collection, returning when
455 * {@code isDone} holds for each task or an (unchecked) exception
456 * is encountered. If any task encounters an exception, others
457 * may be, but are not guaranteed to be, cancelled. If more than
458 * one task encounters an exception, then this method throws any
459 * one of these exceptions. The individual status of each task
460 * may be checked using {@link #getException()} and related
461 * methods. The behavior of this operation is undefined if the
462 * specified collection is modified while the operation is in
463 * progress.
464 *
465 * <p>This method may be invoked only from within {@code
466 * ForkJoinTask} computations (as may be determined using method
467 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
468 * result in exceptions or errors, possibly including {@code
469 * ClassCastException}.
470 *
471 * @param tasks the collection of tasks
472 * @return the tasks argument, to simplify usage
473 * @throws NullPointerException if tasks or any element are null
474 */
475 public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) {
476 if (!(tasks instanceof RandomAccess) || !(tasks instanceof List<?>)) {
477 invokeAll(tasks.toArray(new ForkJoinTask<?>[tasks.size()]));
478 return tasks;
479 }
480 @SuppressWarnings("unchecked")
481 List<? extends ForkJoinTask<?>> ts =
482 (List<? extends ForkJoinTask<?>>) tasks;
483 Throwable ex = null;
484 int last = ts.size() - 1;
485 for (int i = last; i >= 0; --i) {
486 ForkJoinTask<?> t = ts.get(i);
487 if (t == null) {
488 if (ex == null)
489 ex = new NullPointerException();
490 }
491 else if (i != 0)
492 t.fork();
493 else if (t.doInvoke() < NORMAL && ex == null)
494 ex = t.getException();
495 }
496 for (int i = 1; i <= last; ++i) {
497 ForkJoinTask<?> t = ts.get(i);
498 if (t != null) {
499 if (ex != null)
500 t.cancel(false);
501 else if (t.doJoin() < NORMAL && ex == null)
502 ex = t.getException();
503 }
504 }
505 if (ex != null)
506 UNSAFE.throwException(ex);
507 return tasks;
508 }
509
510 /**
511 * Attempts to cancel execution of this task. This attempt will
512 * fail if the task has already completed, has already been
513 * cancelled, or could not be cancelled for some other reason. If
514 * successful, and this task has not started when cancel is
515 * called, execution of this task is suppressed, {@link
516 * #isCancelled} will report true, and {@link #join} will result
517 * in a {@code CancellationException} being thrown.
518 *
519 * <p>This method may be overridden in subclasses, but if so, must
520 * still ensure that these minimal properties hold. In particular,
521 * the {@code cancel} method itself must not throw exceptions.
522 *
523 * <p>This method is designed to be invoked by <em>other</em>
524 * tasks. To terminate the current task, you can just return or
525 * throw an unchecked exception from its computation method, or
526 * invoke {@link #completeExceptionally}.
527 *
528 * @param mayInterruptIfRunning this value is ignored in the
529 * default implementation because tasks are not
530 * cancelled via interruption
531 *
532 * @return {@code true} if this task is now cancelled
533 */
534 public boolean cancel(boolean mayInterruptIfRunning) {
535 return setCompletion(CANCELLED) == CANCELLED;
536 }
537
538 /**
539 * Cancels, ignoring any exceptions thrown by cancel. Used during
540 * worker and pool shutdown. Cancel is spec'ed not to throw any
541 * exceptions, but if it does anyway, we have no recourse during
542 * shutdown, so guard against this case.
543 */
544 final void cancelIgnoringExceptions() {
545 try {
546 cancel(false);
547 } catch (Throwable ignore) {
548 }
549 }
550
551 /**
552 * Cancels ignoring exceptions if worker is terminating
553 */
554 final void cancelIfTerminating() {
555 Thread t = Thread.currentThread();
556 if ((t instanceof ForkJoinWorkerThread) &&
557 ((ForkJoinWorkerThread) t).isTerminating()) {
558 try {
559 cancel(false);
560 } catch (Throwable ignore) {
561 }
562 }
563 }
564
565 public final boolean isDone() {
566 return status < 0;
567 }
568
569 public final boolean isCancelled() {
570 return status == CANCELLED;
571 }
572
573 /**
574 * Returns {@code true} if this task threw an exception or was cancelled.
575 *
576 * @return {@code true} if this task threw an exception or was cancelled
577 */
578 public final boolean isCompletedAbnormally() {
579 return status < NORMAL;
580 }
581
582 /**
583 * Returns {@code true} if this task completed without throwing an
584 * exception and was not cancelled.
585 *
586 * @return {@code true} if this task completed without throwing an
587 * exception and was not cancelled
588 */
589 public final boolean isCompletedNormally() {
590 return status == NORMAL;
591 }
592
593 /**
594 * Returns the exception thrown by the base computation, or a
595 * {@code CancellationException} if cancelled, or {@code null} if
596 * none or if the method has not yet completed.
597 *
598 * @return the exception, or {@code null} if none
599 */
600 public final Throwable getException() {
601 int s = status;
602 return ((s >= NORMAL) ? null :
603 (s == CANCELLED) ? new CancellationException() :
604 exceptionMap.get(this));
605 }
606
607 /**
608 * Completes this task abnormally, and if not already aborted or
609 * cancelled, causes it to throw the given exception upon
610 * {@code join} and related operations. This method may be used
611 * to induce exceptions in asynchronous tasks, or to force
612 * completion of tasks that would not otherwise complete. Its use
613 * in other situations is discouraged. This method is
614 * overridable, but overridden versions must invoke {@code super}
615 * implementation to maintain guarantees.
616 *
617 * @param ex the exception to throw. If this exception is not a
618 * {@code RuntimeException} or {@code Error}, the actual exception
619 * thrown will be a {@code RuntimeException} with cause {@code ex}.
620 */
621 public void completeExceptionally(Throwable ex) {
622 setExceptionalCompletion((ex instanceof RuntimeException) ||
623 (ex instanceof Error) ? ex :
624 new RuntimeException(ex));
625 }
626
627 /**
628 * Completes this task, and if not already aborted or cancelled,
629 * returning a {@code null} result upon {@code join} and related
630 * operations. This method may be used to provide results for
631 * asynchronous tasks, or to provide alternative handling for
632 * tasks that would not otherwise complete normally. Its use in
633 * other situations is discouraged. This method is
634 * overridable, but overridden versions must invoke {@code super}
635 * implementation to maintain guarantees.
636 *
637 * @param value the result value for this task
638 */
639 public void complete(V value) {
640 try {
641 setRawResult(value);
642 } catch (Throwable rex) {
643 setExceptionalCompletion(rex);
644 return;
645 }
646 setCompletion(NORMAL);
647 }
648
649 public final V get() throws InterruptedException, ExecutionException {
650 int s = doJoin();
651 if (Thread.interrupted())
652 throw new InterruptedException();
653 if (s < NORMAL) {
654 Throwable ex;
655 if (s == CANCELLED)
656 throw new CancellationException();
657 if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
658 throw new ExecutionException(ex);
659 }
660 return getRawResult();
661 }
662
663 public final V get(long timeout, TimeUnit unit)
664 throws InterruptedException, ExecutionException, TimeoutException {
665 Thread t = Thread.currentThread();
666 ForkJoinPool pool;
667 if (t instanceof ForkJoinWorkerThread) {
668 ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
669 if (status >= 0 && w.unpushTask(this))
670 tryExec();
671 pool = w.pool;
672 }
673 else
674 pool = null;
675 /*
676 * Timed wait loop intermixes cases for FJ (pool != null) and
677 * non FJ threads. For FJ, decrement pool count but don't try
678 * for replacement; increment count on completion. For non-FJ,
679 * deal with interrupts. This is messy, but a little less so
680 * than is splitting the FJ and nonFJ cases.
681 */
682 boolean interrupted = false;
683 boolean dec = false; // true if pool count decremented
684 for (;;) {
685 if (Thread.interrupted() && pool == null) {
686 interrupted = true;
687 break;
688 }
689 int s = status;
690 if (s < 0)
691 break;
692 if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)) {
693 long startTime = System.nanoTime();
694 long nanos = unit.toNanos(timeout);
695 long nt; // wait time
696 while (status >= 0 &&
697 (nt = nanos - (System.nanoTime() - startTime)) > 0) {
698 if (pool != null && !dec)
699 dec = pool.tryDecrementRunningCount();
700 else {
701 long ms = nt / 1000000;
702 int ns = (int) (nt % 1000000);
703 try {
704 synchronized(this) {
705 if (status >= 0)
706 wait(ms, ns);
707 }
708 } catch (InterruptedException ie) {
709 if (pool != null)
710 cancelIfTerminating();
711 else {
712 interrupted = true;
713 break;
714 }
715 }
716 }
717 }
718 break;
719 }
720 }
721 if (pool != null && dec)
722 pool.incrementRunningCount();
723 if (interrupted)
724 throw new InterruptedException();
725 int es = status;
726 if (es != NORMAL) {
727 Throwable ex;
728 if (es == CANCELLED)
729 throw new CancellationException();
730 if (es == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
731 throw new ExecutionException(ex);
732 throw new TimeoutException();
733 }
734 return getRawResult();
735 }
736
737 /**
738 * Joins this task, without returning its result or throwing an
739 * exception. This method may be useful when processing
740 * collections of tasks when some have been cancelled or otherwise
741 * known to have aborted.
742 */
743 public final void quietlyJoin() {
744 doJoin();
745 }
746
747 /**
748 * Commences performing this task and awaits its completion if
749 * necessary, without returning its result or throwing an
750 * exception. This method may be useful when processing
751 * collections of tasks when some have been cancelled or otherwise
752 * known to have aborted.
753 */
754 public final void quietlyInvoke() {
755 doInvoke();
756 }
757
758 /**
759 * Possibly executes tasks until the pool hosting the current task
760 * {@link ForkJoinPool#isQuiescent is quiescent}. This method may
761 * be of use in designs in which many tasks are forked, but none
762 * are explicitly joined, instead executing them until all are
763 * processed.
764 *
765 * <p>This method may be invoked only from within {@code
766 * ForkJoinTask} computations (as may be determined using method
767 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
768 * result in exceptions or errors, possibly including {@code
769 * ClassCastException}.
770 */
771 public static void helpQuiesce() {
772 ((ForkJoinWorkerThread) Thread.currentThread())
773 .helpQuiescePool();
774 }
775
776 /**
777 * Resets the internal bookkeeping state of this task, allowing a
778 * subsequent {@code fork}. This method allows repeated reuse of
779 * this task, but only if reuse occurs when this task has either
780 * never been forked, or has been forked, then completed and all
781 * outstanding joins of this task have also completed. Effects
782 * under any other usage conditions are not guaranteed.
783 * This method may be useful when executing
784 * pre-constructed trees of subtasks in loops.
785 */
786 public void reinitialize() {
787 if (status == EXCEPTIONAL)
788 exceptionMap.remove(this);
789 status = 0;
790 }
791
792 /**
793 * Returns the pool hosting the current task execution, or null
794 * if this task is executing outside of any ForkJoinPool.
795 *
796 * @see #inForkJoinPool
797 * @return the pool, or {@code null} if none
798 */
799 public static ForkJoinPool getPool() {
800 Thread t = Thread.currentThread();
801 return (t instanceof ForkJoinWorkerThread) ?
802 ((ForkJoinWorkerThread) t).pool : null;
803 }
804
805 /**
806 * Returns {@code true} if the current thread is executing as a
807 * ForkJoinPool computation.
808 *
809 * @return {@code true} if the current thread is executing as a
810 * ForkJoinPool computation, or false otherwise
811 */
812 public static boolean inForkJoinPool() {
813 return Thread.currentThread() instanceof ForkJoinWorkerThread;
814 }
815
816 /**
817 * Tries to unschedule this task for execution. This method will
818 * typically succeed if this task is the most recently forked task
819 * by the current thread, and has not commenced executing in
820 * another thread. This method may be useful when arranging
821 * alternative local processing of tasks that could have been, but
822 * were not, stolen.
823 *
824 * <p>This method may be invoked only from within {@code
825 * ForkJoinTask} computations (as may be determined using method
826 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
827 * result in exceptions or errors, possibly including {@code
828 * ClassCastException}.
829 *
830 * @return {@code true} if unforked
831 */
832 public boolean tryUnfork() {
833 return ((ForkJoinWorkerThread) Thread.currentThread())
834 .unpushTask(this);
835 }
836
837 /**
838 * Returns an estimate of the number of tasks that have been
839 * forked by the current worker thread but not yet executed. This
840 * value may be useful for heuristic decisions about whether to
841 * fork other tasks.
842 *
843 * <p>This method may be invoked only from within {@code
844 * ForkJoinTask} computations (as may be determined using method
845 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
846 * result in exceptions or errors, possibly including {@code
847 * ClassCastException}.
848 *
849 * @return the number of tasks
850 */
851 public static int getQueuedTaskCount() {
852 return ((ForkJoinWorkerThread) Thread.currentThread())
853 .getQueueSize();
854 }
855
856 /**
857 * Returns an estimate of how many more locally queued tasks are
858 * held by the current worker thread than there are other worker
859 * threads that might steal them. This value may be useful for
860 * heuristic decisions about whether to fork other tasks. In many
861 * usages of ForkJoinTasks, at steady state, each worker should
862 * aim to maintain a small constant surplus (for example, 3) of
863 * tasks, and to process computations locally if this threshold is
864 * exceeded.
865 *
866 * <p>This method may be invoked only from within {@code
867 * ForkJoinTask} computations (as may be determined using method
868 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
869 * result in exceptions or errors, possibly including {@code
870 * ClassCastException}.
871 *
872 * @return the surplus number of tasks, which may be negative
873 */
874 public static int getSurplusQueuedTaskCount() {
875 return ((ForkJoinWorkerThread) Thread.currentThread())
876 .getEstimatedSurplusTaskCount();
877 }
878
879 // Extension methods
880
881 /**
882 * Returns the result that would be returned by {@link #join}, even
883 * if this task completed abnormally, or {@code null} if this task
884 * is not known to have been completed. This method is designed
885 * to aid debugging, as well as to support extensions. Its use in
886 * any other context is discouraged.
887 *
888 * @return the result, or {@code null} if not completed
889 */
890 public abstract V getRawResult();
891
892 /**
893 * Forces the given value to be returned as a result. This method
894 * is designed to support extensions, and should not in general be
895 * called otherwise.
896 *
897 * @param value the value
898 */
899 protected abstract void setRawResult(V value);
900
901 /**
902 * Immediately performs the base action of this task. This method
903 * is designed to support extensions, and should not in general be
904 * called otherwise. The return value controls whether this task
905 * is considered to be done normally. It may return false in
906 * asynchronous actions that require explicit invocations of
907 * {@link #complete} to become joinable. It may also throw an
908 * (unchecked) exception to indicate abnormal exit.
909 *
910 * @return {@code true} if completed normally
911 */
912 protected abstract boolean exec();
913
914 /**
915 * Returns, but does not unschedule or execute, a task queued by
916 * the current thread but not yet executed, if one is immediately
917 * available. There is no guarantee that this task will actually
918 * be polled or executed next. Conversely, this method may return
919 * null even if a task exists but cannot be accessed without
920 * contention with other threads. This method is designed
921 * primarily to support extensions, and is unlikely to be useful
922 * otherwise.
923 *
924 * <p>This method may be invoked only from within {@code
925 * ForkJoinTask} computations (as may be determined using method
926 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
927 * result in exceptions or errors, possibly including {@code
928 * ClassCastException}.
929 *
930 * @return the next task, or {@code null} if none are available
931 */
932 protected static ForkJoinTask<?> peekNextLocalTask() {
933 return ((ForkJoinWorkerThread) Thread.currentThread())
934 .peekTask();
935 }
936
937 /**
938 * Unschedules and returns, without executing, the next task
939 * queued by the current thread but not yet executed. This method
940 * is designed primarily to support extensions, and is unlikely to
941 * be useful otherwise.
942 *
943 * <p>This method may be invoked only from within {@code
944 * ForkJoinTask} computations (as may be determined using method
945 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
946 * result in exceptions or errors, possibly including {@code
947 * ClassCastException}.
948 *
949 * @return the next task, or {@code null} if none are available
950 */
951 protected static ForkJoinTask<?> pollNextLocalTask() {
952 return ((ForkJoinWorkerThread) Thread.currentThread())
953 .pollLocalTask();
954 }
955
956 /**
957 * Unschedules and returns, without executing, the next task
958 * queued by the current thread but not yet executed, if one is
959 * available, or if not available, a task that was forked by some
960 * other thread, if available. Availability may be transient, so a
961 * {@code null} result does not necessarily imply quiescence
962 * of the pool this task is operating in. This method is designed
963 * primarily to support extensions, and is unlikely to be useful
964 * otherwise.
965 *
966 * <p>This method may be invoked only from within {@code
967 * ForkJoinTask} computations (as may be determined using method
968 * {@link #inForkJoinPool}). Attempts to invoke in other contexts
969 * result in exceptions or errors, possibly including {@code
970 * ClassCastException}.
971 *
972 * @return a task, or {@code null} if none are available
973 */
974 protected static ForkJoinTask<?> pollTask() {
975 return ((ForkJoinWorkerThread) Thread.currentThread())
976 .pollTask();
977 }
978
979 /**
980 * Adaptor for Runnables. This implements RunnableFuture
981 * to be compliant with AbstractExecutorService constraints
982 * when used in ForkJoinPool.
983 */
984 static final class AdaptedRunnable<T> extends ForkJoinTask<T>
985 implements RunnableFuture<T> {
986 final Runnable runnable;
987 final T resultOnCompletion;
988 T result;
989 AdaptedRunnable(Runnable runnable, T result) {
990 if (runnable == null) throw new NullPointerException();
991 this.runnable = runnable;
992 this.resultOnCompletion = result;
993 }
994 public T getRawResult() { return result; }
995 public void setRawResult(T v) { result = v; }
996 public boolean exec() {
997 runnable.run();
998 result = resultOnCompletion;
999 return true;
1000 }
1001 public void run() { invoke(); }
1002 private static final long serialVersionUID = 5232453952276885070L;
1003 }
1004
1005 /**
1006 * Adaptor for Callables
1007 */
1008 static final class AdaptedCallable<T> extends ForkJoinTask<T>
1009 implements RunnableFuture<T> {
1010 final Callable<? extends T> callable;
1011 T result;
1012 AdaptedCallable(Callable<? extends T> callable) {
1013 if (callable == null) throw new NullPointerException();
1014 this.callable = callable;
1015 }
1016 public T getRawResult() { return result; }
1017 public void setRawResult(T v) { result = v; }
1018 public boolean exec() {
1019 try {
1020 result = callable.call();
1021 return true;
1022 } catch (Error err) {
1023 throw err;
1024 } catch (RuntimeException rex) {
1025 throw rex;
1026 } catch (Exception ex) {
1027 throw new RuntimeException(ex);
1028 }
1029 }
1030 public void run() { invoke(); }
1031 private static final long serialVersionUID = 2838392045355241008L;
1032 }
1033
1034 /**
1035 * Returns a new {@code ForkJoinTask} that performs the {@code run}
1036 * method of the given {@code Runnable} as its action, and returns
1037 * a null result upon {@link #join}.
1038 *
1039 * @param runnable the runnable action
1040 * @return the task
1041 */
1042 public static ForkJoinTask<?> adapt(Runnable runnable) {
1043 return new AdaptedRunnable<Void>(runnable, null);
1044 }
1045
1046 /**
1047 * Returns a new {@code ForkJoinTask} that performs the {@code run}
1048 * method of the given {@code Runnable} as its action, and returns
1049 * the given result upon {@link #join}.
1050 *
1051 * @param runnable the runnable action
1052 * @param result the result upon completion
1053 * @return the task
1054 */
1055 public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) {
1056 return new AdaptedRunnable<T>(runnable, result);
1057 }
1058
1059 /**
1060 * Returns a new {@code ForkJoinTask} that performs the {@code call}
1061 * method of the given {@code Callable} as its action, and returns
1062 * its result upon {@link #join}, translating any checked exceptions
1063 * encountered into {@code RuntimeException}.
1064 *
1065 * @param callable the callable action
1066 * @return the task
1067 */
1068 public static <T> ForkJoinTask<T> adapt(Callable<? extends T> callable) {
1069 return new AdaptedCallable<T>(callable);
1070 }
1071
1072 // Serialization support
1073
1074 private static final long serialVersionUID = -7721805057305804111L;
1075
1076 /**
1077 * Saves the state to a stream.
1078 *
1079 * @serialData the current run status and the exception thrown
1080 * during execution, or {@code null} if none
1081 * @param s the stream
1082 */
1083 private void writeObject(java.io.ObjectOutputStream s)
1084 throws java.io.IOException {
1085 s.defaultWriteObject();
1086 s.writeObject(getException());
1087 }
1088
1089 /**
1090 * Reconstitutes the instance from a stream.
1091 *
1092 * @param s the stream
1093 */
1094 private void readObject(java.io.ObjectInputStream s)
1095 throws java.io.IOException, ClassNotFoundException {
1096 s.defaultReadObject();
1097 Object ex = s.readObject();
1098 if (ex != null)
1099 setExceptionalCompletion((Throwable) ex);
1100 }
1101
1102 // Unsafe mechanics
1103
1104 private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1105 private static final long statusOffset =
1106 objectFieldOffset("status", ForkJoinTask.class);
1107
1108 private static long objectFieldOffset(String field, Class<?> klazz) {
1109 try {
1110 return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1111 } catch (NoSuchFieldException e) {
1112 // Convert Exception to corresponding Error
1113 NoSuchFieldError error = new NoSuchFieldError(field);
1114 error.initCause(e);
1115 throw error;
1116 }
1117 }
1118
1119 /**
1120 * Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package.
1121 * Replace with a simple call to Unsafe.getUnsafe when integrating
1122 * into a jdk.
1123 *
1124 * @return a sun.misc.Unsafe
1125 */
1126 private static sun.misc.Unsafe getUnsafe() {
1127 try {
1128 return sun.misc.Unsafe.getUnsafe();
1129 } catch (SecurityException se) {
1130 try {
1131 return java.security.AccessController.doPrivileged
1132 (new java.security
1133 .PrivilegedExceptionAction<sun.misc.Unsafe>() {
1134 public sun.misc.Unsafe run() throws Exception {
1135 java.lang.reflect.Field f = sun.misc
1136 .Unsafe.class.getDeclaredField("theUnsafe");
1137 f.setAccessible(true);
1138 return (sun.misc.Unsafe) f.get(null);
1139 }});
1140 } catch (java.security.PrivilegedActionException e) {
1141 throw new RuntimeException("Could not initialize intrinsics",
1142 e.getCause());
1143 }
1144 }
1145 }
1146 }