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