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