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