rt/emul/compact/src/main/java/java/util/concurrent/ForkJoinPool.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 19 Mar 2016 13:15:11 +0100
changeset 1896 9984d9a62bc0
parent 1895 bfaf3300b7ba
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.util.ArrayList;
jaroslav@1890
    39
import java.util.Arrays;
jaroslav@1890
    40
import java.util.Collection;
jaroslav@1890
    41
import java.util.Collections;
jaroslav@1890
    42
import java.util.List;
jaroslav@1890
    43
import java.util.Random;
jaroslav@1890
    44
import java.util.concurrent.AbstractExecutorService;
jaroslav@1890
    45
import java.util.concurrent.Callable;
jaroslav@1890
    46
import java.util.concurrent.ExecutorService;
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.atomic.AtomicInteger;
jaroslav@1890
    52
import java.util.concurrent.locks.LockSupport;
jaroslav@1890
    53
import java.util.concurrent.locks.ReentrantLock;
jaroslav@1890
    54
import java.util.concurrent.locks.Condition;
jaroslav@1890
    55
jaroslav@1890
    56
/**
jaroslav@1890
    57
 * An {@link ExecutorService} for running {@link ForkJoinTask}s.
jaroslav@1890
    58
 * A {@code ForkJoinPool} provides the entry point for submissions
jaroslav@1890
    59
 * from non-{@code ForkJoinTask} clients, as well as management and
jaroslav@1890
    60
 * monitoring operations.
jaroslav@1890
    61
 *
jaroslav@1890
    62
 * <p>A {@code ForkJoinPool} differs from other kinds of {@link
jaroslav@1890
    63
 * ExecutorService} mainly by virtue of employing
jaroslav@1890
    64
 * <em>work-stealing</em>: all threads in the pool attempt to find and
jaroslav@1890
    65
 * execute subtasks created by other active tasks (eventually blocking
jaroslav@1890
    66
 * waiting for work if none exist). This enables efficient processing
jaroslav@1890
    67
 * when most tasks spawn other subtasks (as do most {@code
jaroslav@1890
    68
 * ForkJoinTask}s). When setting <em>asyncMode</em> to true in
jaroslav@1890
    69
 * constructors, {@code ForkJoinPool}s may also be appropriate for use
jaroslav@1890
    70
 * with event-style tasks that are never joined.
jaroslav@1890
    71
 *
jaroslav@1890
    72
 * <p>A {@code ForkJoinPool} is constructed with a given target
jaroslav@1890
    73
 * parallelism level; by default, equal to the number of available
jaroslav@1890
    74
 * processors. The pool attempts to maintain enough active (or
jaroslav@1890
    75
 * available) threads by dynamically adding, suspending, or resuming
jaroslav@1890
    76
 * internal worker threads, even if some tasks are stalled waiting to
jaroslav@1890
    77
 * join others. However, no such adjustments are guaranteed in the
jaroslav@1890
    78
 * face of blocked IO or other unmanaged synchronization. The nested
jaroslav@1890
    79
 * {@link ManagedBlocker} interface enables extension of the kinds of
jaroslav@1890
    80
 * synchronization accommodated.
jaroslav@1890
    81
 *
jaroslav@1890
    82
 * <p>In addition to execution and lifecycle control methods, this
jaroslav@1890
    83
 * class provides status check methods (for example
jaroslav@1890
    84
 * {@link #getStealCount}) that are intended to aid in developing,
jaroslav@1890
    85
 * tuning, and monitoring fork/join applications. Also, method
jaroslav@1890
    86
 * {@link #toString} returns indications of pool state in a
jaroslav@1890
    87
 * convenient form for informal monitoring.
jaroslav@1890
    88
 *
jaroslav@1890
    89
 * <p> As is the case with other ExecutorServices, there are three
jaroslav@1890
    90
 * main task execution methods summarized in the following
jaroslav@1890
    91
 * table. These are designed to be used by clients not already engaged
jaroslav@1890
    92
 * in fork/join computations in the current pool.  The main forms of
jaroslav@1890
    93
 * these methods accept instances of {@code ForkJoinTask}, but
jaroslav@1890
    94
 * overloaded forms also allow mixed execution of plain {@code
jaroslav@1890
    95
 * Runnable}- or {@code Callable}- based activities as well.  However,
jaroslav@1890
    96
 * tasks that are already executing in a pool should normally
jaroslav@1890
    97
 * <em>NOT</em> use these pool execution methods, but instead use the
jaroslav@1890
    98
 * within-computation forms listed in the table.
jaroslav@1890
    99
 *
jaroslav@1890
   100
 * <table BORDER CELLPADDING=3 CELLSPACING=1>
jaroslav@1890
   101
 *  <tr>
jaroslav@1890
   102
 *    <td></td>
jaroslav@1890
   103
 *    <td ALIGN=CENTER> <b>Call from non-fork/join clients</b></td>
jaroslav@1890
   104
 *    <td ALIGN=CENTER> <b>Call from within fork/join computations</b></td>
jaroslav@1890
   105
 *  </tr>
jaroslav@1890
   106
 *  <tr>
jaroslav@1890
   107
 *    <td> <b>Arrange async execution</td>
jaroslav@1890
   108
 *    <td> {@link #execute(ForkJoinTask)}</td>
jaroslav@1890
   109
 *    <td> {@link ForkJoinTask#fork}</td>
jaroslav@1890
   110
 *  </tr>
jaroslav@1890
   111
 *  <tr>
jaroslav@1890
   112
 *    <td> <b>Await and obtain result</td>
jaroslav@1890
   113
 *    <td> {@link #invoke(ForkJoinTask)}</td>
jaroslav@1890
   114
 *    <td> {@link ForkJoinTask#invoke}</td>
jaroslav@1890
   115
 *  </tr>
jaroslav@1890
   116
 *  <tr>
jaroslav@1890
   117
 *    <td> <b>Arrange exec and obtain Future</td>
jaroslav@1890
   118
 *    <td> {@link #submit(ForkJoinTask)}</td>
jaroslav@1890
   119
 *    <td> {@link ForkJoinTask#fork} (ForkJoinTasks <em>are</em> Futures)</td>
jaroslav@1890
   120
 *  </tr>
jaroslav@1890
   121
 * </table>
jaroslav@1890
   122
 *
jaroslav@1890
   123
 * <p><b>Sample Usage.</b> Normally a single {@code ForkJoinPool} is
jaroslav@1890
   124
 * used for all parallel task execution in a program or subsystem.
jaroslav@1890
   125
 * Otherwise, use would not usually outweigh the construction and
jaroslav@1890
   126
 * bookkeeping overhead of creating a large set of threads. For
jaroslav@1890
   127
 * example, a common pool could be used for the {@code SortTasks}
jaroslav@1890
   128
 * illustrated in {@link RecursiveAction}. Because {@code
jaroslav@1890
   129
 * ForkJoinPool} uses threads in {@linkplain java.lang.Thread#isDaemon
jaroslav@1890
   130
 * daemon} mode, there is typically no need to explicitly {@link
jaroslav@1890
   131
 * #shutdown} such a pool upon program exit.
jaroslav@1890
   132
 *
jaroslav@1890
   133
 * <pre>
jaroslav@1890
   134
 * static final ForkJoinPool mainPool = new ForkJoinPool();
jaroslav@1890
   135
 * ...
jaroslav@1890
   136
 * public void sort(long[] array) {
jaroslav@1890
   137
 *   mainPool.invoke(new SortTask(array, 0, array.length));
jaroslav@1890
   138
 * }
jaroslav@1890
   139
 * </pre>
jaroslav@1890
   140
 *
jaroslav@1890
   141
 * <p><b>Implementation notes</b>: This implementation restricts the
jaroslav@1890
   142
 * maximum number of running threads to 32767. Attempts to create
jaroslav@1890
   143
 * pools with greater than the maximum number result in
jaroslav@1890
   144
 * {@code IllegalArgumentException}.
jaroslav@1890
   145
 *
jaroslav@1890
   146
 * <p>This implementation rejects submitted tasks (that is, by throwing
jaroslav@1890
   147
 * {@link RejectedExecutionException}) only when the pool is shut down
jaroslav@1890
   148
 * or internal resources have been exhausted.
jaroslav@1890
   149
 *
jaroslav@1890
   150
 * @since 1.7
jaroslav@1890
   151
 * @author Doug Lea
jaroslav@1890
   152
 */
jaroslav@1890
   153
public class ForkJoinPool extends AbstractExecutorService {
jaroslav@1890
   154
jaroslav@1890
   155
    /*
jaroslav@1890
   156
     * Implementation Overview
jaroslav@1890
   157
     *
jaroslav@1890
   158
     * This class provides the central bookkeeping and control for a
jaroslav@1890
   159
     * set of worker threads: Submissions from non-FJ threads enter
jaroslav@1890
   160
     * into a submission queue. Workers take these tasks and typically
jaroslav@1890
   161
     * split them into subtasks that may be stolen by other workers.
jaroslav@1890
   162
     * Preference rules give first priority to processing tasks from
jaroslav@1890
   163
     * their own queues (LIFO or FIFO, depending on mode), then to
jaroslav@1890
   164
     * randomized FIFO steals of tasks in other worker queues, and
jaroslav@1890
   165
     * lastly to new submissions.
jaroslav@1890
   166
     *
jaroslav@1890
   167
     * The main throughput advantages of work-stealing stem from
jaroslav@1890
   168
     * decentralized control -- workers mostly take tasks from
jaroslav@1890
   169
     * themselves or each other. We cannot negate this in the
jaroslav@1890
   170
     * implementation of other management responsibilities. The main
jaroslav@1890
   171
     * tactic for avoiding bottlenecks is packing nearly all
jaroslav@1890
   172
     * essentially atomic control state into a single 64bit volatile
jaroslav@1890
   173
     * variable ("ctl"). This variable is read on the order of 10-100
jaroslav@1890
   174
     * times as often as it is modified (always via CAS). (There is
jaroslav@1890
   175
     * some additional control state, for example variable "shutdown"
jaroslav@1890
   176
     * for which we can cope with uncoordinated updates.)  This
jaroslav@1890
   177
     * streamlines synchronization and control at the expense of messy
jaroslav@1890
   178
     * constructions needed to repack status bits upon updates.
jaroslav@1890
   179
     * Updates tend not to contend with each other except during
jaroslav@1890
   180
     * bursts while submitted tasks begin or end.  In some cases when
jaroslav@1890
   181
     * they do contend, threads can instead do something else
jaroslav@1890
   182
     * (usually, scan for tasks) until contention subsides.
jaroslav@1890
   183
     *
jaroslav@1890
   184
     * To enable packing, we restrict maximum parallelism to (1<<15)-1
jaroslav@1890
   185
     * (which is far in excess of normal operating range) to allow
jaroslav@1890
   186
     * ids, counts, and their negations (used for thresholding) to fit
jaroslav@1890
   187
     * into 16bit fields.
jaroslav@1890
   188
     *
jaroslav@1890
   189
     * Recording Workers.  Workers are recorded in the "workers" array
jaroslav@1890
   190
     * that is created upon pool construction and expanded if (rarely)
jaroslav@1890
   191
     * necessary.  This is an array as opposed to some other data
jaroslav@1890
   192
     * structure to support index-based random steals by workers.
jaroslav@1890
   193
     * Updates to the array recording new workers and unrecording
jaroslav@1890
   194
     * terminated ones are protected from each other by a seqLock
jaroslav@1890
   195
     * (scanGuard) but the array is otherwise concurrently readable,
jaroslav@1890
   196
     * and accessed directly by workers. To simplify index-based
jaroslav@1890
   197
     * operations, the array size is always a power of two, and all
jaroslav@1890
   198
     * readers must tolerate null slots. To avoid flailing during
jaroslav@1890
   199
     * start-up, the array is presized to hold twice #parallelism
jaroslav@1890
   200
     * workers (which is unlikely to need further resizing during
jaroslav@1890
   201
     * execution). But to avoid dealing with so many null slots,
jaroslav@1890
   202
     * variable scanGuard includes a mask for the nearest power of two
jaroslav@1890
   203
     * that contains all current workers.  All worker thread creation
jaroslav@1890
   204
     * is on-demand, triggered by task submissions, replacement of
jaroslav@1890
   205
     * terminated workers, and/or compensation for blocked
jaroslav@1890
   206
     * workers. However, all other support code is set up to work with
jaroslav@1890
   207
     * other policies.  To ensure that we do not hold on to worker
jaroslav@1890
   208
     * references that would prevent GC, ALL accesses to workers are
jaroslav@1890
   209
     * via indices into the workers array (which is one source of some
jaroslav@1890
   210
     * of the messy code constructions here). In essence, the workers
jaroslav@1890
   211
     * array serves as a weak reference mechanism. Thus for example
jaroslav@1890
   212
     * the wait queue field of ctl stores worker indices, not worker
jaroslav@1890
   213
     * references.  Access to the workers in associated methods (for
jaroslav@1890
   214
     * example signalWork) must both index-check and null-check the
jaroslav@1890
   215
     * IDs. All such accesses ignore bad IDs by returning out early
jaroslav@1890
   216
     * from what they are doing, since this can only be associated
jaroslav@1890
   217
     * with termination, in which case it is OK to give up.
jaroslav@1890
   218
     *
jaroslav@1890
   219
     * All uses of the workers array, as well as queue arrays, check
jaroslav@1890
   220
     * that the array is non-null (even if previously non-null). This
jaroslav@1890
   221
     * allows nulling during termination, which is currently not
jaroslav@1890
   222
     * necessary, but remains an option for resource-revocation-based
jaroslav@1890
   223
     * shutdown schemes.
jaroslav@1890
   224
     *
jaroslav@1890
   225
     * Wait Queuing. Unlike HPC work-stealing frameworks, we cannot
jaroslav@1890
   226
     * let workers spin indefinitely scanning for tasks when none can
jaroslav@1890
   227
     * be found immediately, and we cannot start/resume workers unless
jaroslav@1890
   228
     * there appear to be tasks available.  On the other hand, we must
jaroslav@1890
   229
     * quickly prod them into action when new tasks are submitted or
jaroslav@1890
   230
     * generated.  We park/unpark workers after placing in an event
jaroslav@1890
   231
     * wait queue when they cannot find work. This "queue" is actually
jaroslav@1890
   232
     * a simple Treiber stack, headed by the "id" field of ctl, plus a
jaroslav@1890
   233
     * 15bit counter value to both wake up waiters (by advancing their
jaroslav@1890
   234
     * count) and avoid ABA effects. Successors are held in worker
jaroslav@1890
   235
     * field "nextWait".  Queuing deals with several intrinsic races,
jaroslav@1890
   236
     * mainly that a task-producing thread can miss seeing (and
jaroslav@1890
   237
     * signalling) another thread that gave up looking for work but
jaroslav@1890
   238
     * has not yet entered the wait queue. We solve this by requiring
jaroslav@1890
   239
     * a full sweep of all workers both before (in scan()) and after
jaroslav@1890
   240
     * (in tryAwaitWork()) a newly waiting worker is added to the wait
jaroslav@1890
   241
     * queue. During a rescan, the worker might release some other
jaroslav@1890
   242
     * queued worker rather than itself, which has the same net
jaroslav@1890
   243
     * effect. Because enqueued workers may actually be rescanning
jaroslav@1890
   244
     * rather than waiting, we set and clear the "parked" field of
jaroslav@1890
   245
     * ForkJoinWorkerThread to reduce unnecessary calls to unpark.
jaroslav@1890
   246
     * (Use of the parked field requires a secondary recheck to avoid
jaroslav@1890
   247
     * missed signals.)
jaroslav@1890
   248
     *
jaroslav@1890
   249
     * Signalling.  We create or wake up workers only when there
jaroslav@1890
   250
     * appears to be at least one task they might be able to find and
jaroslav@1890
   251
     * execute.  When a submission is added or another worker adds a
jaroslav@1890
   252
     * task to a queue that previously had two or fewer tasks, they
jaroslav@1890
   253
     * signal waiting workers (or trigger creation of new ones if
jaroslav@1890
   254
     * fewer than the given parallelism level -- see signalWork).
jaroslav@1890
   255
     * These primary signals are buttressed by signals during rescans
jaroslav@1890
   256
     * as well as those performed when a worker steals a task and
jaroslav@1890
   257
     * notices that there are more tasks too; together these cover the
jaroslav@1890
   258
     * signals needed in cases when more than two tasks are pushed
jaroslav@1890
   259
     * but untaken.
jaroslav@1890
   260
     *
jaroslav@1890
   261
     * Trimming workers. To release resources after periods of lack of
jaroslav@1890
   262
     * use, a worker starting to wait when the pool is quiescent will
jaroslav@1890
   263
     * time out and terminate if the pool has remained quiescent for
jaroslav@1890
   264
     * SHRINK_RATE nanosecs. This will slowly propagate, eventually
jaroslav@1890
   265
     * terminating all workers after long periods of non-use.
jaroslav@1890
   266
     *
jaroslav@1890
   267
     * Submissions. External submissions are maintained in an
jaroslav@1890
   268
     * array-based queue that is structured identically to
jaroslav@1890
   269
     * ForkJoinWorkerThread queues except for the use of
jaroslav@1890
   270
     * submissionLock in method addSubmission. Unlike the case for
jaroslav@1890
   271
     * worker queues, multiple external threads can add new
jaroslav@1890
   272
     * submissions, so adding requires a lock.
jaroslav@1890
   273
     *
jaroslav@1890
   274
     * Compensation. Beyond work-stealing support and lifecycle
jaroslav@1890
   275
     * control, the main responsibility of this framework is to take
jaroslav@1890
   276
     * actions when one worker is waiting to join a task stolen (or
jaroslav@1890
   277
     * always held by) another.  Because we are multiplexing many
jaroslav@1890
   278
     * tasks on to a pool of workers, we can't just let them block (as
jaroslav@1890
   279
     * in Thread.join).  We also cannot just reassign the joiner's
jaroslav@1890
   280
     * run-time stack with another and replace it later, which would
jaroslav@1890
   281
     * be a form of "continuation", that even if possible is not
jaroslav@1890
   282
     * necessarily a good idea since we sometimes need both an
jaroslav@1890
   283
     * unblocked task and its continuation to progress. Instead we
jaroslav@1890
   284
     * combine two tactics:
jaroslav@1890
   285
     *
jaroslav@1890
   286
     *   Helping: Arranging for the joiner to execute some task that it
jaroslav@1890
   287
     *      would be running if the steal had not occurred.  Method
jaroslav@1890
   288
     *      ForkJoinWorkerThread.joinTask tracks joining->stealing
jaroslav@1890
   289
     *      links to try to find such a task.
jaroslav@1890
   290
     *
jaroslav@1890
   291
     *   Compensating: Unless there are already enough live threads,
jaroslav@1890
   292
     *      method tryPreBlock() may create or re-activate a spare
jaroslav@1890
   293
     *      thread to compensate for blocked joiners until they
jaroslav@1890
   294
     *      unblock.
jaroslav@1890
   295
     *
jaroslav@1890
   296
     * The ManagedBlocker extension API can't use helping so relies
jaroslav@1890
   297
     * only on compensation in method awaitBlocker.
jaroslav@1890
   298
     *
jaroslav@1890
   299
     * It is impossible to keep exactly the target parallelism number
jaroslav@1890
   300
     * of threads running at any given time.  Determining the
jaroslav@1890
   301
     * existence of conservatively safe helping targets, the
jaroslav@1890
   302
     * availability of already-created spares, and the apparent need
jaroslav@1890
   303
     * to create new spares are all racy and require heuristic
jaroslav@1890
   304
     * guidance, so we rely on multiple retries of each.  Currently,
jaroslav@1890
   305
     * in keeping with on-demand signalling policy, we compensate only
jaroslav@1890
   306
     * if blocking would leave less than one active (non-waiting,
jaroslav@1890
   307
     * non-blocked) worker. Additionally, to avoid some false alarms
jaroslav@1890
   308
     * due to GC, lagging counters, system activity, etc, compensated
jaroslav@1890
   309
     * blocking for joins is only attempted after rechecks stabilize
jaroslav@1890
   310
     * (retries are interspersed with Thread.yield, for good
jaroslav@1890
   311
     * citizenship).  The variable blockedCount, incremented before
jaroslav@1890
   312
     * blocking and decremented after, is sometimes needed to
jaroslav@1890
   313
     * distinguish cases of waiting for work vs blocking on joins or
jaroslav@1890
   314
     * other managed sync. Both cases are equivalent for most pool
jaroslav@1890
   315
     * control, so we can update non-atomically. (Additionally,
jaroslav@1890
   316
     * contention on blockedCount alleviates some contention on ctl).
jaroslav@1890
   317
     *
jaroslav@1890
   318
     * Shutdown and Termination. A call to shutdownNow atomically sets
jaroslav@1890
   319
     * the ctl stop bit and then (non-atomically) sets each workers
jaroslav@1890
   320
     * "terminate" status, cancels all unprocessed tasks, and wakes up
jaroslav@1890
   321
     * all waiting workers.  Detecting whether termination should
jaroslav@1890
   322
     * commence after a non-abrupt shutdown() call requires more work
jaroslav@1890
   323
     * and bookkeeping. We need consensus about quiesence (i.e., that
jaroslav@1890
   324
     * there is no more work) which is reflected in active counts so
jaroslav@1890
   325
     * long as there are no current blockers, as well as possible
jaroslav@1890
   326
     * re-evaluations during independent changes in blocking or
jaroslav@1890
   327
     * quiescing workers.
jaroslav@1890
   328
     *
jaroslav@1890
   329
     * Style notes: There is a lot of representation-level coupling
jaroslav@1890
   330
     * among classes ForkJoinPool, ForkJoinWorkerThread, and
jaroslav@1890
   331
     * ForkJoinTask.  Most fields of ForkJoinWorkerThread maintain
jaroslav@1890
   332
     * data structures managed by ForkJoinPool, so are directly
jaroslav@1890
   333
     * accessed.  Conversely we allow access to "workers" array by
jaroslav@1890
   334
     * workers, and direct access to ForkJoinTask.status by both
jaroslav@1890
   335
     * ForkJoinPool and ForkJoinWorkerThread.  There is little point
jaroslav@1890
   336
     * trying to reduce this, since any associated future changes in
jaroslav@1890
   337
     * representations will need to be accompanied by algorithmic
jaroslav@1890
   338
     * changes anyway. All together, these low-level implementation
jaroslav@1890
   339
     * choices produce as much as a factor of 4 performance
jaroslav@1890
   340
     * improvement compared to naive implementations, and enable the
jaroslav@1890
   341
     * processing of billions of tasks per second, at the expense of
jaroslav@1890
   342
     * some ugliness.
jaroslav@1890
   343
     *
jaroslav@1890
   344
     * Methods signalWork() and scan() are the main bottlenecks so are
jaroslav@1890
   345
     * especially heavily micro-optimized/mangled.  There are lots of
jaroslav@1890
   346
     * inline assignments (of form "while ((local = field) != 0)")
jaroslav@1890
   347
     * which are usually the simplest way to ensure the required read
jaroslav@1890
   348
     * orderings (which are sometimes critical). This leads to a
jaroslav@1890
   349
     * "C"-like style of listing declarations of these locals at the
jaroslav@1890
   350
     * heads of methods or blocks.  There are several occurrences of
jaroslav@1890
   351
     * the unusual "do {} while (!cas...)"  which is the simplest way
jaroslav@1890
   352
     * to force an update of a CAS'ed variable. There are also other
jaroslav@1890
   353
     * coding oddities that help some methods perform reasonably even
jaroslav@1890
   354
     * when interpreted (not compiled).
jaroslav@1890
   355
     *
jaroslav@1890
   356
     * The order of declarations in this file is: (1) declarations of
jaroslav@1890
   357
     * statics (2) fields (along with constants used when unpacking
jaroslav@1890
   358
     * some of them), listed in an order that tends to reduce
jaroslav@1890
   359
     * contention among them a bit under most JVMs.  (3) internal
jaroslav@1890
   360
     * control methods (4) callbacks and other support for
jaroslav@1890
   361
     * ForkJoinTask and ForkJoinWorkerThread classes, (5) exported
jaroslav@1890
   362
     * methods (plus a few little helpers). (6) static block
jaroslav@1890
   363
     * initializing all statics in a minimally dependent order.
jaroslav@1890
   364
     */
jaroslav@1890
   365
jaroslav@1890
   366
    /**
jaroslav@1890
   367
     * Factory for creating new {@link ForkJoinWorkerThread}s.
jaroslav@1890
   368
     * A {@code ForkJoinWorkerThreadFactory} must be defined and used
jaroslav@1890
   369
     * for {@code ForkJoinWorkerThread} subclasses that extend base
jaroslav@1890
   370
     * functionality or initialize threads with different contexts.
jaroslav@1890
   371
     */
jaroslav@1890
   372
    public static interface ForkJoinWorkerThreadFactory {
jaroslav@1890
   373
        /**
jaroslav@1890
   374
         * Returns a new worker thread operating in the given pool.
jaroslav@1890
   375
         *
jaroslav@1890
   376
         * @param pool the pool this thread works in
jaroslav@1890
   377
         * @throws NullPointerException if the pool is null
jaroslav@1890
   378
         */
jaroslav@1890
   379
        public ForkJoinWorkerThread newThread(ForkJoinPool pool);
jaroslav@1890
   380
    }
jaroslav@1890
   381
jaroslav@1890
   382
    /**
jaroslav@1890
   383
     * Default ForkJoinWorkerThreadFactory implementation; creates a
jaroslav@1890
   384
     * new ForkJoinWorkerThread.
jaroslav@1890
   385
     */
jaroslav@1890
   386
    static class DefaultForkJoinWorkerThreadFactory
jaroslav@1890
   387
        implements ForkJoinWorkerThreadFactory {
jaroslav@1890
   388
        public ForkJoinWorkerThread newThread(ForkJoinPool pool) {
jaroslav@1890
   389
            return new ForkJoinWorkerThread(pool);
jaroslav@1890
   390
        }
jaroslav@1890
   391
    }
jaroslav@1890
   392
jaroslav@1890
   393
    /**
jaroslav@1890
   394
     * Creates a new ForkJoinWorkerThread. This factory is used unless
jaroslav@1890
   395
     * overridden in ForkJoinPool constructors.
jaroslav@1890
   396
     */
jaroslav@1890
   397
    public static final ForkJoinWorkerThreadFactory
jaroslav@1890
   398
        defaultForkJoinWorkerThreadFactory;
jaroslav@1890
   399
jaroslav@1890
   400
    /**
jaroslav@1890
   401
     * If there is a security manager, makes sure caller has
jaroslav@1890
   402
     * permission to modify threads.
jaroslav@1890
   403
     */
jaroslav@1890
   404
    private static void checkPermission() {
jaroslav@1895
   405
        throw new SecurityException();
jaroslav@1890
   406
    }
jaroslav@1890
   407
jaroslav@1890
   408
    /**
jaroslav@1890
   409
     * Generator for assigning sequence numbers as pool names.
jaroslav@1890
   410
     */
jaroslav@1890
   411
    private static final AtomicInteger poolNumberGenerator;
jaroslav@1890
   412
jaroslav@1890
   413
    /**
jaroslav@1890
   414
     * Generator for initial random seeds for worker victim
jaroslav@1890
   415
     * selection. This is used only to create initial seeds. Random
jaroslav@1890
   416
     * steals use a cheaper xorshift generator per steal attempt. We
jaroslav@1890
   417
     * don't expect much contention on seedGenerator, so just use a
jaroslav@1890
   418
     * plain Random.
jaroslav@1890
   419
     */
jaroslav@1890
   420
    static final Random workerSeedGenerator;
jaroslav@1890
   421
jaroslav@1890
   422
    /**
jaroslav@1890
   423
     * Array holding all worker threads in the pool.  Initialized upon
jaroslav@1890
   424
     * construction. Array size must be a power of two.  Updates and
jaroslav@1890
   425
     * replacements are protected by scanGuard, but the array is
jaroslav@1890
   426
     * always kept in a consistent enough state to be randomly
jaroslav@1890
   427
     * accessed without locking by workers performing work-stealing,
jaroslav@1890
   428
     * as well as other traversal-based methods in this class, so long
jaroslav@1890
   429
     * as reads memory-acquire by first reading ctl. All readers must
jaroslav@1890
   430
     * tolerate that some array slots may be null.
jaroslav@1890
   431
     */
jaroslav@1890
   432
    ForkJoinWorkerThread[] workers;
jaroslav@1890
   433
jaroslav@1890
   434
    /**
jaroslav@1890
   435
     * Initial size for submission queue array. Must be a power of
jaroslav@1890
   436
     * two.  In many applications, these always stay small so we use a
jaroslav@1890
   437
     * small initial cap.
jaroslav@1890
   438
     */
jaroslav@1890
   439
    private static final int INITIAL_QUEUE_CAPACITY = 8;
jaroslav@1890
   440
jaroslav@1890
   441
    /**
jaroslav@1890
   442
     * Maximum size for submission queue array. Must be a power of two
jaroslav@1890
   443
     * less than or equal to 1 << (31 - width of array entry) to
jaroslav@1890
   444
     * ensure lack of index wraparound, but is capped at a lower
jaroslav@1890
   445
     * value to help users trap runaway computations.
jaroslav@1890
   446
     */
jaroslav@1890
   447
    private static final int MAXIMUM_QUEUE_CAPACITY = 1 << 24; // 16M
jaroslav@1890
   448
jaroslav@1890
   449
    /**
jaroslav@1890
   450
     * Array serving as submission queue. Initialized upon construction.
jaroslav@1890
   451
     */
jaroslav@1890
   452
    private ForkJoinTask<?>[] submissionQueue;
jaroslav@1890
   453
jaroslav@1890
   454
    /**
jaroslav@1890
   455
     * Lock protecting submissions array for addSubmission
jaroslav@1890
   456
     */
jaroslav@1890
   457
    private final ReentrantLock submissionLock;
jaroslav@1890
   458
jaroslav@1890
   459
    /**
jaroslav@1890
   460
     * Condition for awaitTermination, using submissionLock for
jaroslav@1890
   461
     * convenience.
jaroslav@1890
   462
     */
jaroslav@1890
   463
    private final Condition termination;
jaroslav@1890
   464
jaroslav@1890
   465
    /**
jaroslav@1890
   466
     * Creation factory for worker threads.
jaroslav@1890
   467
     */
jaroslav@1890
   468
    private final ForkJoinWorkerThreadFactory factory;
jaroslav@1890
   469
jaroslav@1890
   470
    /**
jaroslav@1890
   471
     * The uncaught exception handler used when any worker abruptly
jaroslav@1890
   472
     * terminates.
jaroslav@1890
   473
     */
jaroslav@1890
   474
    final Thread.UncaughtExceptionHandler ueh;
jaroslav@1890
   475
jaroslav@1890
   476
    /**
jaroslav@1890
   477
     * Prefix for assigning names to worker threads
jaroslav@1890
   478
     */
jaroslav@1890
   479
    private final String workerNamePrefix;
jaroslav@1890
   480
jaroslav@1890
   481
    /**
jaroslav@1890
   482
     * Sum of per-thread steal counts, updated only when threads are
jaroslav@1890
   483
     * idle or terminating.
jaroslav@1890
   484
     */
jaroslav@1890
   485
    private volatile long stealCount;
jaroslav@1890
   486
jaroslav@1890
   487
    /**
jaroslav@1890
   488
     * Main pool control -- a long packed with:
jaroslav@1890
   489
     * AC: Number of active running workers minus target parallelism (16 bits)
jaroslav@1890
   490
     * TC: Number of total workers minus target parallelism (16bits)
jaroslav@1890
   491
     * ST: true if pool is terminating (1 bit)
jaroslav@1890
   492
     * EC: the wait count of top waiting thread (15 bits)
jaroslav@1890
   493
     * ID: ~poolIndex of top of Treiber stack of waiting threads (16 bits)
jaroslav@1890
   494
     *
jaroslav@1890
   495
     * When convenient, we can extract the upper 32 bits of counts and
jaroslav@1890
   496
     * the lower 32 bits of queue state, u = (int)(ctl >>> 32) and e =
jaroslav@1890
   497
     * (int)ctl.  The ec field is never accessed alone, but always
jaroslav@1890
   498
     * together with id and st. The offsets of counts by the target
jaroslav@1890
   499
     * parallelism and the positionings of fields makes it possible to
jaroslav@1890
   500
     * perform the most common checks via sign tests of fields: When
jaroslav@1890
   501
     * ac is negative, there are not enough active workers, when tc is
jaroslav@1890
   502
     * negative, there are not enough total workers, when id is
jaroslav@1890
   503
     * negative, there is at least one waiting worker, and when e is
jaroslav@1890
   504
     * negative, the pool is terminating.  To deal with these possibly
jaroslav@1890
   505
     * negative fields, we use casts in and out of "short" and/or
jaroslav@1890
   506
     * signed shifts to maintain signedness.
jaroslav@1890
   507
     */
jaroslav@1890
   508
    volatile long ctl;
jaroslav@1890
   509
jaroslav@1890
   510
    // bit positions/shifts for fields
jaroslav@1890
   511
    private static final int  AC_SHIFT   = 48;
jaroslav@1890
   512
    private static final int  TC_SHIFT   = 32;
jaroslav@1890
   513
    private static final int  ST_SHIFT   = 31;
jaroslav@1890
   514
    private static final int  EC_SHIFT   = 16;
jaroslav@1890
   515
jaroslav@1890
   516
    // bounds
jaroslav@1890
   517
    private static final int  MAX_ID     = 0x7fff;  // max poolIndex
jaroslav@1890
   518
    private static final int  SMASK      = 0xffff;  // mask short bits
jaroslav@1890
   519
    private static final int  SHORT_SIGN = 1 << 15;
jaroslav@1890
   520
    private static final int  INT_SIGN   = 1 << 31;
jaroslav@1890
   521
jaroslav@1890
   522
    // masks
jaroslav@1890
   523
    private static final long STOP_BIT   = 0x0001L << ST_SHIFT;
jaroslav@1890
   524
    private static final long AC_MASK    = ((long)SMASK) << AC_SHIFT;
jaroslav@1890
   525
    private static final long TC_MASK    = ((long)SMASK) << TC_SHIFT;
jaroslav@1890
   526
jaroslav@1890
   527
    // units for incrementing and decrementing
jaroslav@1890
   528
    private static final long TC_UNIT    = 1L << TC_SHIFT;
jaroslav@1890
   529
    private static final long AC_UNIT    = 1L << AC_SHIFT;
jaroslav@1890
   530
jaroslav@1890
   531
    // masks and units for dealing with u = (int)(ctl >>> 32)
jaroslav@1890
   532
    private static final int  UAC_SHIFT  = AC_SHIFT - 32;
jaroslav@1890
   533
    private static final int  UTC_SHIFT  = TC_SHIFT - 32;
jaroslav@1890
   534
    private static final int  UAC_MASK   = SMASK << UAC_SHIFT;
jaroslav@1890
   535
    private static final int  UTC_MASK   = SMASK << UTC_SHIFT;
jaroslav@1890
   536
    private static final int  UAC_UNIT   = 1 << UAC_SHIFT;
jaroslav@1890
   537
    private static final int  UTC_UNIT   = 1 << UTC_SHIFT;
jaroslav@1890
   538
jaroslav@1890
   539
    // masks and units for dealing with e = (int)ctl
jaroslav@1890
   540
    private static final int  E_MASK     = 0x7fffffff; // no STOP_BIT
jaroslav@1890
   541
    private static final int  EC_UNIT    = 1 << EC_SHIFT;
jaroslav@1890
   542
jaroslav@1890
   543
    /**
jaroslav@1890
   544
     * The target parallelism level.
jaroslav@1890
   545
     */
jaroslav@1890
   546
    final int parallelism;
jaroslav@1890
   547
jaroslav@1890
   548
    /**
jaroslav@1890
   549
     * Index (mod submission queue length) of next element to take
jaroslav@1890
   550
     * from submission queue. Usage is identical to that for
jaroslav@1890
   551
     * per-worker queues -- see ForkJoinWorkerThread internal
jaroslav@1890
   552
     * documentation.
jaroslav@1890
   553
     */
jaroslav@1890
   554
    volatile int queueBase;
jaroslav@1890
   555
jaroslav@1890
   556
    /**
jaroslav@1890
   557
     * Index (mod submission queue length) of next element to add
jaroslav@1890
   558
     * in submission queue. Usage is identical to that for
jaroslav@1890
   559
     * per-worker queues -- see ForkJoinWorkerThread internal
jaroslav@1890
   560
     * documentation.
jaroslav@1890
   561
     */
jaroslav@1890
   562
    int queueTop;
jaroslav@1890
   563
jaroslav@1890
   564
    /**
jaroslav@1890
   565
     * True when shutdown() has been called.
jaroslav@1890
   566
     */
jaroslav@1890
   567
    volatile boolean shutdown;
jaroslav@1890
   568
jaroslav@1890
   569
    /**
jaroslav@1890
   570
     * True if use local fifo, not default lifo, for local polling
jaroslav@1890
   571
     * Read by, and replicated by ForkJoinWorkerThreads
jaroslav@1890
   572
     */
jaroslav@1890
   573
    final boolean locallyFifo;
jaroslav@1890
   574
jaroslav@1890
   575
    /**
jaroslav@1890
   576
     * The number of threads in ForkJoinWorkerThreads.helpQuiescePool.
jaroslav@1890
   577
     * When non-zero, suppresses automatic shutdown when active
jaroslav@1890
   578
     * counts become zero.
jaroslav@1890
   579
     */
jaroslav@1890
   580
    volatile int quiescerCount;
jaroslav@1890
   581
jaroslav@1890
   582
    /**
jaroslav@1890
   583
     * The number of threads blocked in join.
jaroslav@1890
   584
     */
jaroslav@1890
   585
    volatile int blockedCount;
jaroslav@1890
   586
jaroslav@1890
   587
    /**
jaroslav@1890
   588
     * Counter for worker Thread names (unrelated to their poolIndex)
jaroslav@1890
   589
     */
jaroslav@1890
   590
    private volatile int nextWorkerNumber;
jaroslav@1890
   591
jaroslav@1890
   592
    /**
jaroslav@1890
   593
     * The index for the next created worker. Accessed under scanGuard.
jaroslav@1890
   594
     */
jaroslav@1890
   595
    private int nextWorkerIndex;
jaroslav@1890
   596
jaroslav@1890
   597
    /**
jaroslav@1890
   598
     * SeqLock and index masking for updates to workers array.  Locked
jaroslav@1890
   599
     * when SG_UNIT is set. Unlocking clears bit by adding
jaroslav@1890
   600
     * SG_UNIT. Staleness of read-only operations can be checked by
jaroslav@1890
   601
     * comparing scanGuard to value before the reads. The low 16 bits
jaroslav@1890
   602
     * (i.e, anding with SMASK) hold (the smallest power of two
jaroslav@1890
   603
     * covering all worker indices, minus one, and is used to avoid
jaroslav@1890
   604
     * dealing with large numbers of null slots when the workers array
jaroslav@1890
   605
     * is overallocated.
jaroslav@1890
   606
     */
jaroslav@1890
   607
    volatile int scanGuard;
jaroslav@1890
   608
jaroslav@1890
   609
    private static final int SG_UNIT = 1 << 16;
jaroslav@1890
   610
jaroslav@1890
   611
    /**
jaroslav@1890
   612
     * The wakeup interval (in nanoseconds) for a worker waiting for a
jaroslav@1890
   613
     * task when the pool is quiescent to instead try to shrink the
jaroslav@1890
   614
     * number of workers.  The exact value does not matter too
jaroslav@1890
   615
     * much. It must be short enough to release resources during
jaroslav@1890
   616
     * sustained periods of idleness, but not so short that threads
jaroslav@1890
   617
     * are continually re-created.
jaroslav@1890
   618
     */
jaroslav@1890
   619
    private static final long SHRINK_RATE =
jaroslav@1890
   620
        4L * 1000L * 1000L * 1000L; // 4 seconds
jaroslav@1890
   621
jaroslav@1890
   622
    /**
jaroslav@1890
   623
     * Top-level loop for worker threads: On each step: if the
jaroslav@1890
   624
     * previous step swept through all queues and found no tasks, or
jaroslav@1890
   625
     * there are excess threads, then possibly blocks. Otherwise,
jaroslav@1890
   626
     * scans for and, if found, executes a task. Returns when pool
jaroslav@1890
   627
     * and/or worker terminate.
jaroslav@1890
   628
     *
jaroslav@1890
   629
     * @param w the worker
jaroslav@1890
   630
     */
jaroslav@1890
   631
    final void work(ForkJoinWorkerThread w) {
jaroslav@1890
   632
        boolean swept = false;                // true on empty scans
jaroslav@1890
   633
        long c;
jaroslav@1890
   634
        while (!w.terminate && (int)(c = ctl) >= 0) {
jaroslav@1890
   635
            int a;                            // active count
jaroslav@1890
   636
            if (!swept && (a = (int)(c >> AC_SHIFT)) <= 0)
jaroslav@1890
   637
                swept = scan(w, a);
jaroslav@1890
   638
            else if (tryAwaitWork(w, c))
jaroslav@1890
   639
                swept = false;
jaroslav@1890
   640
        }
jaroslav@1890
   641
    }
jaroslav@1890
   642
jaroslav@1890
   643
    // Signalling
jaroslav@1890
   644
jaroslav@1890
   645
    /**
jaroslav@1890
   646
     * Wakes up or creates a worker.
jaroslav@1890
   647
     */
jaroslav@1890
   648
    final void signalWork() {
jaroslav@1890
   649
        /*
jaroslav@1890
   650
         * The while condition is true if: (there is are too few total
jaroslav@1890
   651
         * workers OR there is at least one waiter) AND (there are too
jaroslav@1890
   652
         * few active workers OR the pool is terminating).  The value
jaroslav@1890
   653
         * of e distinguishes the remaining cases: zero (no waiters)
jaroslav@1890
   654
         * for create, negative if terminating (in which case do
jaroslav@1890
   655
         * nothing), else release a waiter. The secondary checks for
jaroslav@1890
   656
         * release (non-null array etc) can fail if the pool begins
jaroslav@1890
   657
         * terminating after the test, and don't impose any added cost
jaroslav@1890
   658
         * because JVMs must perform null and bounds checks anyway.
jaroslav@1890
   659
         */
jaroslav@1890
   660
        long c; int e, u;
jaroslav@1890
   661
        while ((((e = (int)(c = ctl)) | (u = (int)(c >>> 32))) &
jaroslav@1890
   662
                (INT_SIGN|SHORT_SIGN)) == (INT_SIGN|SHORT_SIGN) && e >= 0) {
jaroslav@1890
   663
            if (e > 0) {                         // release a waiting worker
jaroslav@1890
   664
                int i; ForkJoinWorkerThread w; ForkJoinWorkerThread[] ws;
jaroslav@1890
   665
                if ((ws = workers) == null ||
jaroslav@1890
   666
                    (i = ~e & SMASK) >= ws.length ||
jaroslav@1890
   667
                    (w = ws[i]) == null)
jaroslav@1890
   668
                    break;
jaroslav@1890
   669
                long nc = (((long)(w.nextWait & E_MASK)) |
jaroslav@1890
   670
                           ((long)(u + UAC_UNIT) << 32));
jaroslav@1890
   671
                if (w.eventCount == e &&
jaroslav@1890
   672
                    UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc)) {
jaroslav@1890
   673
                    w.eventCount = (e + EC_UNIT) & E_MASK;
jaroslav@1890
   674
                    if (w.parked)
jaroslav@1890
   675
                        UNSAFE.unpark(w);
jaroslav@1890
   676
                    break;
jaroslav@1890
   677
                }
jaroslav@1890
   678
            }
jaroslav@1890
   679
            else if (UNSAFE.compareAndSwapLong
jaroslav@1890
   680
                     (this, ctlOffset, c,
jaroslav@1890
   681
                      (long)(((u + UTC_UNIT) & UTC_MASK) |
jaroslav@1890
   682
                             ((u + UAC_UNIT) & UAC_MASK)) << 32)) {
jaroslav@1890
   683
                addWorker();
jaroslav@1890
   684
                break;
jaroslav@1890
   685
            }
jaroslav@1890
   686
        }
jaroslav@1890
   687
    }
jaroslav@1890
   688
jaroslav@1890
   689
    /**
jaroslav@1890
   690
     * Variant of signalWork to help release waiters on rescans.
jaroslav@1890
   691
     * Tries once to release a waiter if active count < 0.
jaroslav@1890
   692
     *
jaroslav@1890
   693
     * @return false if failed due to contention, else true
jaroslav@1890
   694
     */
jaroslav@1890
   695
    private boolean tryReleaseWaiter() {
jaroslav@1890
   696
        long c; int e, i; ForkJoinWorkerThread w; ForkJoinWorkerThread[] ws;
jaroslav@1890
   697
        if ((e = (int)(c = ctl)) > 0 &&
jaroslav@1890
   698
            (int)(c >> AC_SHIFT) < 0 &&
jaroslav@1890
   699
            (ws = workers) != null &&
jaroslav@1890
   700
            (i = ~e & SMASK) < ws.length &&
jaroslav@1890
   701
            (w = ws[i]) != null) {
jaroslav@1890
   702
            long nc = ((long)(w.nextWait & E_MASK) |
jaroslav@1890
   703
                       ((c + AC_UNIT) & (AC_MASK|TC_MASK)));
jaroslav@1890
   704
            if (w.eventCount != e ||
jaroslav@1890
   705
                !UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc))
jaroslav@1890
   706
                return false;
jaroslav@1890
   707
            w.eventCount = (e + EC_UNIT) & E_MASK;
jaroslav@1890
   708
            if (w.parked)
jaroslav@1890
   709
                UNSAFE.unpark(w);
jaroslav@1890
   710
        }
jaroslav@1890
   711
        return true;
jaroslav@1890
   712
    }
jaroslav@1890
   713
jaroslav@1890
   714
    // Scanning for tasks
jaroslav@1890
   715
jaroslav@1890
   716
    /**
jaroslav@1890
   717
     * Scans for and, if found, executes one task. Scans start at a
jaroslav@1890
   718
     * random index of workers array, and randomly select the first
jaroslav@1890
   719
     * (2*#workers)-1 probes, and then, if all empty, resort to 2
jaroslav@1890
   720
     * circular sweeps, which is necessary to check quiescence. and
jaroslav@1890
   721
     * taking a submission only if no stealable tasks were found.  The
jaroslav@1890
   722
     * steal code inside the loop is a specialized form of
jaroslav@1890
   723
     * ForkJoinWorkerThread.deqTask, followed bookkeeping to support
jaroslav@1890
   724
     * helpJoinTask and signal propagation. The code for submission
jaroslav@1890
   725
     * queues is almost identical. On each steal, the worker completes
jaroslav@1890
   726
     * not only the task, but also all local tasks that this task may
jaroslav@1890
   727
     * have generated. On detecting staleness or contention when
jaroslav@1890
   728
     * trying to take a task, this method returns without finishing
jaroslav@1890
   729
     * sweep, which allows global state rechecks before retry.
jaroslav@1890
   730
     *
jaroslav@1890
   731
     * @param w the worker
jaroslav@1890
   732
     * @param a the number of active workers
jaroslav@1890
   733
     * @return true if swept all queues without finding a task
jaroslav@1890
   734
     */
jaroslav@1890
   735
    private boolean scan(ForkJoinWorkerThread w, int a) {
jaroslav@1890
   736
        int g = scanGuard; // mask 0 avoids useless scans if only one active
jaroslav@1890
   737
        int m = (parallelism == 1 - a && blockedCount == 0) ? 0 : g & SMASK;
jaroslav@1890
   738
        ForkJoinWorkerThread[] ws = workers;
jaroslav@1890
   739
        if (ws == null || ws.length <= m)         // staleness check
jaroslav@1890
   740
            return false;
jaroslav@1890
   741
        for (int r = w.seed, k = r, j = -(m + m); j <= m + m; ++j) {
jaroslav@1890
   742
            ForkJoinTask<?> t; ForkJoinTask<?>[] q; int b, i;
jaroslav@1890
   743
            ForkJoinWorkerThread v = ws[k & m];
jaroslav@1890
   744
            if (v != null && (b = v.queueBase) != v.queueTop &&
jaroslav@1890
   745
                (q = v.queue) != null && (i = (q.length - 1) & b) >= 0) {
jaroslav@1890
   746
                long u = (i << ASHIFT) + ABASE;
jaroslav@1890
   747
                if ((t = q[i]) != null && v.queueBase == b &&
jaroslav@1890
   748
                    UNSAFE.compareAndSwapObject(q, u, t, null)) {
jaroslav@1890
   749
                    int d = (v.queueBase = b + 1) - v.queueTop;
jaroslav@1890
   750
                    v.stealHint = w.poolIndex;
jaroslav@1890
   751
                    if (d != 0)
jaroslav@1890
   752
                        signalWork();             // propagate if nonempty
jaroslav@1890
   753
                    w.execTask(t);
jaroslav@1890
   754
                }
jaroslav@1890
   755
                r ^= r << 13; r ^= r >>> 17; w.seed = r ^ (r << 5);
jaroslav@1890
   756
                return false;                     // store next seed
jaroslav@1890
   757
            }
jaroslav@1890
   758
            else if (j < 0) {                     // xorshift
jaroslav@1890
   759
                r ^= r << 13; r ^= r >>> 17; k = r ^= r << 5;
jaroslav@1890
   760
            }
jaroslav@1890
   761
            else
jaroslav@1890
   762
                ++k;
jaroslav@1890
   763
        }
jaroslav@1890
   764
        if (scanGuard != g)                       // staleness check
jaroslav@1890
   765
            return false;
jaroslav@1890
   766
        else {                                    // try to take submission
jaroslav@1890
   767
            ForkJoinTask<?> t; ForkJoinTask<?>[] q; int b, i;
jaroslav@1890
   768
            if ((b = queueBase) != queueTop &&
jaroslav@1890
   769
                (q = submissionQueue) != null &&
jaroslav@1890
   770
                (i = (q.length - 1) & b) >= 0) {
jaroslav@1890
   771
                long u = (i << ASHIFT) + ABASE;
jaroslav@1890
   772
                if ((t = q[i]) != null && queueBase == b &&
jaroslav@1890
   773
                    UNSAFE.compareAndSwapObject(q, u, t, null)) {
jaroslav@1890
   774
                    queueBase = b + 1;
jaroslav@1890
   775
                    w.execTask(t);
jaroslav@1890
   776
                }
jaroslav@1890
   777
                return false;
jaroslav@1890
   778
            }
jaroslav@1890
   779
            return true;                         // all queues empty
jaroslav@1890
   780
        }
jaroslav@1890
   781
    }
jaroslav@1890
   782
jaroslav@1890
   783
    /**
jaroslav@1890
   784
     * Tries to enqueue worker w in wait queue and await change in
jaroslav@1890
   785
     * worker's eventCount.  If the pool is quiescent and there is
jaroslav@1890
   786
     * more than one worker, possibly terminates worker upon exit.
jaroslav@1890
   787
     * Otherwise, before blocking, rescans queues to avoid missed
jaroslav@1890
   788
     * signals.  Upon finding work, releases at least one worker
jaroslav@1890
   789
     * (which may be the current worker). Rescans restart upon
jaroslav@1890
   790
     * detected staleness or failure to release due to
jaroslav@1890
   791
     * contention. Note the unusual conventions about Thread.interrupt
jaroslav@1890
   792
     * here and elsewhere: Because interrupts are used solely to alert
jaroslav@1890
   793
     * threads to check termination, which is checked here anyway, we
jaroslav@1890
   794
     * clear status (using Thread.interrupted) before any call to
jaroslav@1890
   795
     * park, so that park does not immediately return due to status
jaroslav@1890
   796
     * being set via some other unrelated call to interrupt in user
jaroslav@1890
   797
     * code.
jaroslav@1890
   798
     *
jaroslav@1890
   799
     * @param w the calling worker
jaroslav@1890
   800
     * @param c the ctl value on entry
jaroslav@1890
   801
     * @return true if waited or another thread was released upon enq
jaroslav@1890
   802
     */
jaroslav@1890
   803
    private boolean tryAwaitWork(ForkJoinWorkerThread w, long c) {
jaroslav@1890
   804
        int v = w.eventCount;
jaroslav@1890
   805
        w.nextWait = (int)c;                      // w's successor record
jaroslav@1890
   806
        long nc = (long)(v & E_MASK) | ((c - AC_UNIT) & (AC_MASK|TC_MASK));
jaroslav@1890
   807
        if (ctl != c || !UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc)) {
jaroslav@1890
   808
            long d = ctl; // return true if lost to a deq, to force scan
jaroslav@1890
   809
            return (int)d != (int)c && ((d - c) & AC_MASK) >= 0L;
jaroslav@1890
   810
        }
jaroslav@1890
   811
        for (int sc = w.stealCount; sc != 0;) {   // accumulate stealCount
jaroslav@1890
   812
            long s = stealCount;
jaroslav@1890
   813
            if (UNSAFE.compareAndSwapLong(this, stealCountOffset, s, s + sc))
jaroslav@1890
   814
                sc = w.stealCount = 0;
jaroslav@1890
   815
            else if (w.eventCount != v)
jaroslav@1890
   816
                return true;                      // update next time
jaroslav@1890
   817
        }
jaroslav@1890
   818
        if ((!shutdown || !tryTerminate(false)) &&
jaroslav@1890
   819
            (int)c != 0 && parallelism + (int)(nc >> AC_SHIFT) == 0 &&
jaroslav@1890
   820
            blockedCount == 0 && quiescerCount == 0)
jaroslav@1890
   821
            idleAwaitWork(w, nc, c, v);           // quiescent
jaroslav@1890
   822
        for (boolean rescanned = false;;) {
jaroslav@1890
   823
            if (w.eventCount != v)
jaroslav@1890
   824
                return true;
jaroslav@1890
   825
            if (!rescanned) {
jaroslav@1890
   826
                int g = scanGuard, m = g & SMASK;
jaroslav@1890
   827
                ForkJoinWorkerThread[] ws = workers;
jaroslav@1890
   828
                if (ws != null && m < ws.length) {
jaroslav@1890
   829
                    rescanned = true;
jaroslav@1890
   830
                    for (int i = 0; i <= m; ++i) {
jaroslav@1890
   831
                        ForkJoinWorkerThread u = ws[i];
jaroslav@1890
   832
                        if (u != null) {
jaroslav@1890
   833
                            if (u.queueBase != u.queueTop &&
jaroslav@1890
   834
                                !tryReleaseWaiter())
jaroslav@1890
   835
                                rescanned = false; // contended
jaroslav@1890
   836
                            if (w.eventCount != v)
jaroslav@1890
   837
                                return true;
jaroslav@1890
   838
                        }
jaroslav@1890
   839
                    }
jaroslav@1890
   840
                }
jaroslav@1890
   841
                if (scanGuard != g ||              // stale
jaroslav@1890
   842
                    (queueBase != queueTop && !tryReleaseWaiter()))
jaroslav@1890
   843
                    rescanned = false;
jaroslav@1890
   844
                if (!rescanned)
jaroslav@1890
   845
                    Thread.yield();                // reduce contention
jaroslav@1890
   846
                else
jaroslav@1890
   847
                    Thread.interrupted();          // clear before park
jaroslav@1890
   848
            }
jaroslav@1890
   849
            else {
jaroslav@1890
   850
                w.parked = true;                   // must recheck
jaroslav@1890
   851
                if (w.eventCount != v) {
jaroslav@1890
   852
                    w.parked = false;
jaroslav@1890
   853
                    return true;
jaroslav@1890
   854
                }
jaroslav@1890
   855
                LockSupport.park(this);
jaroslav@1890
   856
                rescanned = w.parked = false;
jaroslav@1890
   857
            }
jaroslav@1890
   858
        }
jaroslav@1890
   859
    }
jaroslav@1890
   860
jaroslav@1890
   861
    /**
jaroslav@1890
   862
     * If inactivating worker w has caused pool to become
jaroslav@1890
   863
     * quiescent, check for pool termination, and wait for event
jaroslav@1890
   864
     * for up to SHRINK_RATE nanosecs (rescans are unnecessary in
jaroslav@1890
   865
     * this case because quiescence reflects consensus about lack
jaroslav@1890
   866
     * of work). On timeout, if ctl has not changed, terminate the
jaroslav@1890
   867
     * worker. Upon its termination (see deregisterWorker), it may
jaroslav@1890
   868
     * wake up another worker to possibly repeat this process.
jaroslav@1890
   869
     *
jaroslav@1890
   870
     * @param w the calling worker
jaroslav@1890
   871
     * @param currentCtl the ctl value after enqueuing w
jaroslav@1890
   872
     * @param prevCtl the ctl value if w terminated
jaroslav@1890
   873
     * @param v the eventCount w awaits change
jaroslav@1890
   874
     */
jaroslav@1890
   875
    private void idleAwaitWork(ForkJoinWorkerThread w, long currentCtl,
jaroslav@1890
   876
                               long prevCtl, int v) {
jaroslav@1890
   877
        if (w.eventCount == v) {
jaroslav@1890
   878
            if (shutdown)
jaroslav@1890
   879
                tryTerminate(false);
jaroslav@1890
   880
            ForkJoinTask.helpExpungeStaleExceptions(); // help clean weak refs
jaroslav@1890
   881
            while (ctl == currentCtl) {
jaroslav@1890
   882
                long startTime = System.nanoTime();
jaroslav@1890
   883
                w.parked = true;
jaroslav@1890
   884
                if (w.eventCount == v)             // must recheck
jaroslav@1890
   885
                    LockSupport.parkNanos(this, SHRINK_RATE);
jaroslav@1890
   886
                w.parked = false;
jaroslav@1890
   887
                if (w.eventCount != v)
jaroslav@1890
   888
                    break;
jaroslav@1890
   889
                else if (System.nanoTime() - startTime <
jaroslav@1890
   890
                         SHRINK_RATE - (SHRINK_RATE / 10)) // timing slop
jaroslav@1890
   891
                    Thread.interrupted();          // spurious wakeup
jaroslav@1890
   892
                else if (UNSAFE.compareAndSwapLong(this, ctlOffset,
jaroslav@1890
   893
                                                   currentCtl, prevCtl)) {
jaroslav@1890
   894
                    w.terminate = true;            // restore previous
jaroslav@1890
   895
                    w.eventCount = ((int)currentCtl + EC_UNIT) & E_MASK;
jaroslav@1890
   896
                    break;
jaroslav@1890
   897
                }
jaroslav@1890
   898
            }
jaroslav@1890
   899
        }
jaroslav@1890
   900
    }
jaroslav@1890
   901
jaroslav@1890
   902
    // Submissions
jaroslav@1890
   903
jaroslav@1890
   904
    /**
jaroslav@1890
   905
     * Enqueues the given task in the submissionQueue.  Same idea as
jaroslav@1890
   906
     * ForkJoinWorkerThread.pushTask except for use of submissionLock.
jaroslav@1890
   907
     *
jaroslav@1890
   908
     * @param t the task
jaroslav@1890
   909
     */
jaroslav@1890
   910
    private void addSubmission(ForkJoinTask<?> t) {
jaroslav@1890
   911
        final ReentrantLock lock = this.submissionLock;
jaroslav@1890
   912
        lock.lock();
jaroslav@1890
   913
        try {
jaroslav@1890
   914
            ForkJoinTask<?>[] q; int s, m;
jaroslav@1890
   915
            if ((q = submissionQueue) != null) {    // ignore if queue removed
jaroslav@1890
   916
                long u = (((s = queueTop) & (m = q.length-1)) << ASHIFT)+ABASE;
jaroslav@1890
   917
                UNSAFE.putOrderedObject(q, u, t);
jaroslav@1890
   918
                queueTop = s + 1;
jaroslav@1890
   919
                if (s - queueBase == m)
jaroslav@1890
   920
                    growSubmissionQueue();
jaroslav@1890
   921
            }
jaroslav@1890
   922
        } finally {
jaroslav@1890
   923
            lock.unlock();
jaroslav@1890
   924
        }
jaroslav@1890
   925
        signalWork();
jaroslav@1890
   926
    }
jaroslav@1890
   927
jaroslav@1890
   928
    //  (pollSubmission is defined below with exported methods)
jaroslav@1890
   929
jaroslav@1890
   930
    /**
jaroslav@1890
   931
     * Creates or doubles submissionQueue array.
jaroslav@1890
   932
     * Basically identical to ForkJoinWorkerThread version.
jaroslav@1890
   933
     */
jaroslav@1890
   934
    private void growSubmissionQueue() {
jaroslav@1890
   935
        ForkJoinTask<?>[] oldQ = submissionQueue;
jaroslav@1890
   936
        int size = oldQ != null ? oldQ.length << 1 : INITIAL_QUEUE_CAPACITY;
jaroslav@1890
   937
        if (size > MAXIMUM_QUEUE_CAPACITY)
jaroslav@1890
   938
            throw new RejectedExecutionException("Queue capacity exceeded");
jaroslav@1890
   939
        if (size < INITIAL_QUEUE_CAPACITY)
jaroslav@1890
   940
            size = INITIAL_QUEUE_CAPACITY;
jaroslav@1890
   941
        ForkJoinTask<?>[] q = submissionQueue = new ForkJoinTask<?>[size];
jaroslav@1890
   942
        int mask = size - 1;
jaroslav@1890
   943
        int top = queueTop;
jaroslav@1890
   944
        int oldMask;
jaroslav@1890
   945
        if (oldQ != null && (oldMask = oldQ.length - 1) >= 0) {
jaroslav@1890
   946
            for (int b = queueBase; b != top; ++b) {
jaroslav@1890
   947
                long u = ((b & oldMask) << ASHIFT) + ABASE;
jaroslav@1890
   948
                Object x = UNSAFE.getObjectVolatile(oldQ, u);
jaroslav@1890
   949
                if (x != null && UNSAFE.compareAndSwapObject(oldQ, u, x, null))
jaroslav@1890
   950
                    UNSAFE.putObjectVolatile
jaroslav@1890
   951
                        (q, ((b & mask) << ASHIFT) + ABASE, x);
jaroslav@1890
   952
            }
jaroslav@1890
   953
        }
jaroslav@1890
   954
    }
jaroslav@1890
   955
jaroslav@1890
   956
    // Blocking support
jaroslav@1890
   957
jaroslav@1890
   958
    /**
jaroslav@1890
   959
     * Tries to increment blockedCount, decrement active count
jaroslav@1890
   960
     * (sometimes implicitly) and possibly release or create a
jaroslav@1890
   961
     * compensating worker in preparation for blocking. Fails
jaroslav@1890
   962
     * on contention or termination.
jaroslav@1890
   963
     *
jaroslav@1890
   964
     * @return true if the caller can block, else should recheck and retry
jaroslav@1890
   965
     */
jaroslav@1890
   966
    private boolean tryPreBlock() {
jaroslav@1890
   967
        int b = blockedCount;
jaroslav@1890
   968
        if (UNSAFE.compareAndSwapInt(this, blockedCountOffset, b, b + 1)) {
jaroslav@1890
   969
            int pc = parallelism;
jaroslav@1890
   970
            do {
jaroslav@1890
   971
                ForkJoinWorkerThread[] ws; ForkJoinWorkerThread w;
jaroslav@1890
   972
                int e, ac, tc, rc, i;
jaroslav@1890
   973
                long c = ctl;
jaroslav@1890
   974
                int u = (int)(c >>> 32);
jaroslav@1890
   975
                if ((e = (int)c) < 0) {
jaroslav@1890
   976
                                                 // skip -- terminating
jaroslav@1890
   977
                }
jaroslav@1890
   978
                else if ((ac = (u >> UAC_SHIFT)) <= 0 && e != 0 &&
jaroslav@1890
   979
                         (ws = workers) != null &&
jaroslav@1890
   980
                         (i = ~e & SMASK) < ws.length &&
jaroslav@1890
   981
                         (w = ws[i]) != null) {
jaroslav@1890
   982
                    long nc = ((long)(w.nextWait & E_MASK) |
jaroslav@1890
   983
                               (c & (AC_MASK|TC_MASK)));
jaroslav@1890
   984
                    if (w.eventCount == e &&
jaroslav@1890
   985
                        UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc)) {
jaroslav@1890
   986
                        w.eventCount = (e + EC_UNIT) & E_MASK;
jaroslav@1890
   987
                        if (w.parked)
jaroslav@1890
   988
                            UNSAFE.unpark(w);
jaroslav@1890
   989
                        return true;             // release an idle worker
jaroslav@1890
   990
                    }
jaroslav@1890
   991
                }
jaroslav@1890
   992
                else if ((tc = (short)(u >>> UTC_SHIFT)) >= 0 && ac + pc > 1) {
jaroslav@1890
   993
                    long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK);
jaroslav@1890
   994
                    if (UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc))
jaroslav@1890
   995
                        return true;             // no compensation needed
jaroslav@1890
   996
                }
jaroslav@1890
   997
                else if (tc + pc < MAX_ID) {
jaroslav@1890
   998
                    long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK);
jaroslav@1890
   999
                    if (UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc)) {
jaroslav@1890
  1000
                        addWorker();
jaroslav@1890
  1001
                        return true;            // create a replacement
jaroslav@1890
  1002
                    }
jaroslav@1890
  1003
                }
jaroslav@1890
  1004
                // try to back out on any failure and let caller retry
jaroslav@1890
  1005
            } while (!UNSAFE.compareAndSwapInt(this, blockedCountOffset,
jaroslav@1890
  1006
                                               b = blockedCount, b - 1));
jaroslav@1890
  1007
        }
jaroslav@1890
  1008
        return false;
jaroslav@1890
  1009
    }
jaroslav@1890
  1010
jaroslav@1890
  1011
    /**
jaroslav@1890
  1012
     * Decrements blockedCount and increments active count
jaroslav@1890
  1013
     */
jaroslav@1890
  1014
    private void postBlock() {
jaroslav@1890
  1015
        long c;
jaroslav@1890
  1016
        do {} while (!UNSAFE.compareAndSwapLong(this, ctlOffset,  // no mask
jaroslav@1890
  1017
                                                c = ctl, c + AC_UNIT));
jaroslav@1890
  1018
        int b;
jaroslav@1890
  1019
        do {} while (!UNSAFE.compareAndSwapInt(this, blockedCountOffset,
jaroslav@1890
  1020
                                               b = blockedCount, b - 1));
jaroslav@1890
  1021
    }
jaroslav@1890
  1022
jaroslav@1890
  1023
    /**
jaroslav@1890
  1024
     * Possibly blocks waiting for the given task to complete, or
jaroslav@1890
  1025
     * cancels the task if terminating.  Fails to wait if contended.
jaroslav@1890
  1026
     *
jaroslav@1890
  1027
     * @param joinMe the task
jaroslav@1890
  1028
     */
jaroslav@1890
  1029
    final void tryAwaitJoin(ForkJoinTask<?> joinMe) {
jaroslav@1890
  1030
        int s;
jaroslav@1890
  1031
        Thread.interrupted(); // clear interrupts before checking termination
jaroslav@1890
  1032
        if (joinMe.status >= 0) {
jaroslav@1890
  1033
            if (tryPreBlock()) {
jaroslav@1890
  1034
                joinMe.tryAwaitDone(0L);
jaroslav@1890
  1035
                postBlock();
jaroslav@1890
  1036
            }
jaroslav@1890
  1037
            else if ((ctl & STOP_BIT) != 0L)
jaroslav@1890
  1038
                joinMe.cancelIgnoringExceptions();
jaroslav@1890
  1039
        }
jaroslav@1890
  1040
    }
jaroslav@1890
  1041
jaroslav@1890
  1042
    /**
jaroslav@1890
  1043
     * Possibly blocks the given worker waiting for joinMe to
jaroslav@1890
  1044
     * complete or timeout
jaroslav@1890
  1045
     *
jaroslav@1890
  1046
     * @param joinMe the task
jaroslav@1890
  1047
     * @param millis the wait time for underlying Object.wait
jaroslav@1890
  1048
     */
jaroslav@1890
  1049
    final void timedAwaitJoin(ForkJoinTask<?> joinMe, long nanos) {
jaroslav@1890
  1050
        while (joinMe.status >= 0) {
jaroslav@1890
  1051
            Thread.interrupted();
jaroslav@1890
  1052
            if ((ctl & STOP_BIT) != 0L) {
jaroslav@1890
  1053
                joinMe.cancelIgnoringExceptions();
jaroslav@1890
  1054
                break;
jaroslav@1890
  1055
            }
jaroslav@1890
  1056
            if (tryPreBlock()) {
jaroslav@1890
  1057
                long last = System.nanoTime();
jaroslav@1890
  1058
                while (joinMe.status >= 0) {
jaroslav@1890
  1059
                    long millis = TimeUnit.NANOSECONDS.toMillis(nanos);
jaroslav@1890
  1060
                    if (millis <= 0)
jaroslav@1890
  1061
                        break;
jaroslav@1890
  1062
                    joinMe.tryAwaitDone(millis);
jaroslav@1890
  1063
                    if (joinMe.status < 0)
jaroslav@1890
  1064
                        break;
jaroslav@1890
  1065
                    if ((ctl & STOP_BIT) != 0L) {
jaroslav@1890
  1066
                        joinMe.cancelIgnoringExceptions();
jaroslav@1890
  1067
                        break;
jaroslav@1890
  1068
                    }
jaroslav@1890
  1069
                    long now = System.nanoTime();
jaroslav@1890
  1070
                    nanos -= now - last;
jaroslav@1890
  1071
                    last = now;
jaroslav@1890
  1072
                }
jaroslav@1890
  1073
                postBlock();
jaroslav@1890
  1074
                break;
jaroslav@1890
  1075
            }
jaroslav@1890
  1076
        }
jaroslav@1890
  1077
    }
jaroslav@1890
  1078
jaroslav@1890
  1079
    /**
jaroslav@1890
  1080
     * If necessary, compensates for blocker, and blocks
jaroslav@1890
  1081
     */
jaroslav@1890
  1082
    private void awaitBlocker(ManagedBlocker blocker)
jaroslav@1890
  1083
        throws InterruptedException {
jaroslav@1890
  1084
        while (!blocker.isReleasable()) {
jaroslav@1890
  1085
            if (tryPreBlock()) {
jaroslav@1890
  1086
                try {
jaroslav@1890
  1087
                    do {} while (!blocker.isReleasable() && !blocker.block());
jaroslav@1890
  1088
                } finally {
jaroslav@1890
  1089
                    postBlock();
jaroslav@1890
  1090
                }
jaroslav@1890
  1091
                break;
jaroslav@1890
  1092
            }
jaroslav@1890
  1093
        }
jaroslav@1890
  1094
    }
jaroslav@1890
  1095
jaroslav@1890
  1096
    // Creating, registering and deregistring workers
jaroslav@1890
  1097
jaroslav@1890
  1098
    /**
jaroslav@1890
  1099
     * Tries to create and start a worker; minimally rolls back counts
jaroslav@1890
  1100
     * on failure.
jaroslav@1890
  1101
     */
jaroslav@1890
  1102
    private void addWorker() {
jaroslav@1890
  1103
        Throwable ex = null;
jaroslav@1890
  1104
        ForkJoinWorkerThread t = null;
jaroslav@1890
  1105
        try {
jaroslav@1890
  1106
            t = factory.newThread(this);
jaroslav@1890
  1107
        } catch (Throwable e) {
jaroslav@1890
  1108
            ex = e;
jaroslav@1890
  1109
        }
jaroslav@1890
  1110
        if (t == null) {  // null or exceptional factory return
jaroslav@1890
  1111
            long c;       // adjust counts
jaroslav@1890
  1112
            do {} while (!UNSAFE.compareAndSwapLong
jaroslav@1890
  1113
                         (this, ctlOffset, c = ctl,
jaroslav@1890
  1114
                          (((c - AC_UNIT) & AC_MASK) |
jaroslav@1890
  1115
                           ((c - TC_UNIT) & TC_MASK) |
jaroslav@1890
  1116
                           (c & ~(AC_MASK|TC_MASK)))));
jaroslav@1890
  1117
            // Propagate exception if originating from an external caller
jaroslav@1890
  1118
            if (!tryTerminate(false) && ex != null &&
jaroslav@1890
  1119
                !(Thread.currentThread() instanceof ForkJoinWorkerThread))
jaroslav@1890
  1120
                UNSAFE.throwException(ex);
jaroslav@1890
  1121
        }
jaroslav@1890
  1122
        else
jaroslav@1890
  1123
            t.start();
jaroslav@1890
  1124
    }
jaroslav@1890
  1125
jaroslav@1890
  1126
    /**
jaroslav@1890
  1127
     * Callback from ForkJoinWorkerThread constructor to assign a
jaroslav@1890
  1128
     * public name
jaroslav@1890
  1129
     */
jaroslav@1890
  1130
    final String nextWorkerName() {
jaroslav@1890
  1131
        for (int n;;) {
jaroslav@1890
  1132
            if (UNSAFE.compareAndSwapInt(this, nextWorkerNumberOffset,
jaroslav@1890
  1133
                                         n = nextWorkerNumber, ++n))
jaroslav@1890
  1134
                return workerNamePrefix + n;
jaroslav@1890
  1135
        }
jaroslav@1890
  1136
    }
jaroslav@1890
  1137
jaroslav@1890
  1138
    /**
jaroslav@1890
  1139
     * Callback from ForkJoinWorkerThread constructor to
jaroslav@1890
  1140
     * determine its poolIndex and record in workers array.
jaroslav@1890
  1141
     *
jaroslav@1890
  1142
     * @param w the worker
jaroslav@1890
  1143
     * @return the worker's pool index
jaroslav@1890
  1144
     */
jaroslav@1890
  1145
    final int registerWorker(ForkJoinWorkerThread w) {
jaroslav@1890
  1146
        /*
jaroslav@1890
  1147
         * In the typical case, a new worker acquires the lock, uses
jaroslav@1890
  1148
         * next available index and returns quickly.  Since we should
jaroslav@1890
  1149
         * not block callers (ultimately from signalWork or
jaroslav@1890
  1150
         * tryPreBlock) waiting for the lock needed to do this, we
jaroslav@1890
  1151
         * instead help release other workers while waiting for the
jaroslav@1890
  1152
         * lock.
jaroslav@1890
  1153
         */
jaroslav@1890
  1154
        for (int g;;) {
jaroslav@1890
  1155
            ForkJoinWorkerThread[] ws;
jaroslav@1890
  1156
            if (((g = scanGuard) & SG_UNIT) == 0 &&
jaroslav@1890
  1157
                UNSAFE.compareAndSwapInt(this, scanGuardOffset,
jaroslav@1890
  1158
                                         g, g | SG_UNIT)) {
jaroslav@1890
  1159
                int k = nextWorkerIndex;
jaroslav@1890
  1160
                try {
jaroslav@1890
  1161
                    if ((ws = workers) != null) { // ignore on shutdown
jaroslav@1890
  1162
                        int n = ws.length;
jaroslav@1890
  1163
                        if (k < 0 || k >= n || ws[k] != null) {
jaroslav@1890
  1164
                            for (k = 0; k < n && ws[k] != null; ++k)
jaroslav@1890
  1165
                                ;
jaroslav@1890
  1166
                            if (k == n)
jaroslav@1890
  1167
                                ws = workers = Arrays.copyOf(ws, n << 1);
jaroslav@1890
  1168
                        }
jaroslav@1890
  1169
                        ws[k] = w;
jaroslav@1890
  1170
                        nextWorkerIndex = k + 1;
jaroslav@1890
  1171
                        int m = g & SMASK;
jaroslav@1890
  1172
                        g = (k > m) ? ((m << 1) + 1) & SMASK : g + (SG_UNIT<<1);
jaroslav@1890
  1173
                    }
jaroslav@1890
  1174
                } finally {
jaroslav@1890
  1175
                    scanGuard = g;
jaroslav@1890
  1176
                }
jaroslav@1890
  1177
                return k;
jaroslav@1890
  1178
            }
jaroslav@1890
  1179
            else if ((ws = workers) != null) { // help release others
jaroslav@1890
  1180
                for (ForkJoinWorkerThread u : ws) {
jaroslav@1890
  1181
                    if (u != null && u.queueBase != u.queueTop) {
jaroslav@1890
  1182
                        if (tryReleaseWaiter())
jaroslav@1890
  1183
                            break;
jaroslav@1890
  1184
                    }
jaroslav@1890
  1185
                }
jaroslav@1890
  1186
            }
jaroslav@1890
  1187
        }
jaroslav@1890
  1188
    }
jaroslav@1890
  1189
jaroslav@1890
  1190
    /**
jaroslav@1890
  1191
     * Final callback from terminating worker.  Removes record of
jaroslav@1890
  1192
     * worker from array, and adjusts counts. If pool is shutting
jaroslav@1890
  1193
     * down, tries to complete termination.
jaroslav@1890
  1194
     *
jaroslav@1890
  1195
     * @param w the worker
jaroslav@1890
  1196
     */
jaroslav@1890
  1197
    final void deregisterWorker(ForkJoinWorkerThread w, Throwable ex) {
jaroslav@1890
  1198
        int idx = w.poolIndex;
jaroslav@1890
  1199
        int sc = w.stealCount;
jaroslav@1890
  1200
        int steps = 0;
jaroslav@1890
  1201
        // Remove from array, adjust worker counts and collect steal count.
jaroslav@1890
  1202
        // We can intermix failed removes or adjusts with steal updates
jaroslav@1890
  1203
        do {
jaroslav@1890
  1204
            long s, c;
jaroslav@1890
  1205
            int g;
jaroslav@1890
  1206
            if (steps == 0 && ((g = scanGuard) & SG_UNIT) == 0 &&
jaroslav@1890
  1207
                UNSAFE.compareAndSwapInt(this, scanGuardOffset,
jaroslav@1890
  1208
                                         g, g |= SG_UNIT)) {
jaroslav@1890
  1209
                ForkJoinWorkerThread[] ws = workers;
jaroslav@1890
  1210
                if (ws != null && idx >= 0 &&
jaroslav@1890
  1211
                    idx < ws.length && ws[idx] == w)
jaroslav@1890
  1212
                    ws[idx] = null;    // verify
jaroslav@1890
  1213
                nextWorkerIndex = idx;
jaroslav@1890
  1214
                scanGuard = g + SG_UNIT;
jaroslav@1890
  1215
                steps = 1;
jaroslav@1890
  1216
            }
jaroslav@1890
  1217
            if (steps == 1 &&
jaroslav@1890
  1218
                UNSAFE.compareAndSwapLong(this, ctlOffset, c = ctl,
jaroslav@1890
  1219
                                          (((c - AC_UNIT) & AC_MASK) |
jaroslav@1890
  1220
                                           ((c - TC_UNIT) & TC_MASK) |
jaroslav@1890
  1221
                                           (c & ~(AC_MASK|TC_MASK)))))
jaroslav@1890
  1222
                steps = 2;
jaroslav@1890
  1223
            if (sc != 0 &&
jaroslav@1890
  1224
                UNSAFE.compareAndSwapLong(this, stealCountOffset,
jaroslav@1890
  1225
                                          s = stealCount, s + sc))
jaroslav@1890
  1226
                sc = 0;
jaroslav@1890
  1227
        } while (steps != 2 || sc != 0);
jaroslav@1890
  1228
        if (!tryTerminate(false)) {
jaroslav@1890
  1229
            if (ex != null)   // possibly replace if died abnormally
jaroslav@1890
  1230
                signalWork();
jaroslav@1890
  1231
            else
jaroslav@1890
  1232
                tryReleaseWaiter();
jaroslav@1890
  1233
        }
jaroslav@1890
  1234
    }
jaroslav@1890
  1235
jaroslav@1890
  1236
    // Shutdown and termination
jaroslav@1890
  1237
jaroslav@1890
  1238
    /**
jaroslav@1890
  1239
     * Possibly initiates and/or completes termination.
jaroslav@1890
  1240
     *
jaroslav@1890
  1241
     * @param now if true, unconditionally terminate, else only
jaroslav@1890
  1242
     * if shutdown and empty queue and no active workers
jaroslav@1890
  1243
     * @return true if now terminating or terminated
jaroslav@1890
  1244
     */
jaroslav@1890
  1245
    private boolean tryTerminate(boolean now) {
jaroslav@1890
  1246
        long c;
jaroslav@1890
  1247
        while (((c = ctl) & STOP_BIT) == 0) {
jaroslav@1890
  1248
            if (!now) {
jaroslav@1890
  1249
                if ((int)(c >> AC_SHIFT) != -parallelism)
jaroslav@1890
  1250
                    return false;
jaroslav@1890
  1251
                if (!shutdown || blockedCount != 0 || quiescerCount != 0 ||
jaroslav@1890
  1252
                    queueBase != queueTop) {
jaroslav@1890
  1253
                    if (ctl == c) // staleness check
jaroslav@1890
  1254
                        return false;
jaroslav@1890
  1255
                    continue;
jaroslav@1890
  1256
                }
jaroslav@1890
  1257
            }
jaroslav@1890
  1258
            if (UNSAFE.compareAndSwapLong(this, ctlOffset, c, c | STOP_BIT))
jaroslav@1890
  1259
                startTerminating();
jaroslav@1890
  1260
        }
jaroslav@1890
  1261
        if ((short)(c >>> TC_SHIFT) == -parallelism) { // signal when 0 workers
jaroslav@1890
  1262
            final ReentrantLock lock = this.submissionLock;
jaroslav@1890
  1263
            lock.lock();
jaroslav@1890
  1264
            try {
jaroslav@1890
  1265
                termination.signalAll();
jaroslav@1890
  1266
            } finally {
jaroslav@1890
  1267
                lock.unlock();
jaroslav@1890
  1268
            }
jaroslav@1890
  1269
        }
jaroslav@1890
  1270
        return true;
jaroslav@1890
  1271
    }
jaroslav@1890
  1272
jaroslav@1890
  1273
    /**
jaroslav@1890
  1274
     * Runs up to three passes through workers: (0) Setting
jaroslav@1890
  1275
     * termination status for each worker, followed by wakeups up to
jaroslav@1890
  1276
     * queued workers; (1) helping cancel tasks; (2) interrupting
jaroslav@1890
  1277
     * lagging threads (likely in external tasks, but possibly also
jaroslav@1890
  1278
     * blocked in joins).  Each pass repeats previous steps because of
jaroslav@1890
  1279
     * potential lagging thread creation.
jaroslav@1890
  1280
     */
jaroslav@1890
  1281
    private void startTerminating() {
jaroslav@1890
  1282
        cancelSubmissions();
jaroslav@1890
  1283
        for (int pass = 0; pass < 3; ++pass) {
jaroslav@1890
  1284
            ForkJoinWorkerThread[] ws = workers;
jaroslav@1890
  1285
            if (ws != null) {
jaroslav@1890
  1286
                for (ForkJoinWorkerThread w : ws) {
jaroslav@1890
  1287
                    if (w != null) {
jaroslav@1890
  1288
                        w.terminate = true;
jaroslav@1890
  1289
                        if (pass > 0) {
jaroslav@1890
  1290
                            w.cancelTasks();
jaroslav@1890
  1291
                            if (pass > 1 && !w.isInterrupted()) {
jaroslav@1890
  1292
                                try {
jaroslav@1890
  1293
                                    w.interrupt();
jaroslav@1890
  1294
                                } catch (SecurityException ignore) {
jaroslav@1890
  1295
                                }
jaroslav@1890
  1296
                            }
jaroslav@1890
  1297
                        }
jaroslav@1890
  1298
                    }
jaroslav@1890
  1299
                }
jaroslav@1890
  1300
                terminateWaiters();
jaroslav@1890
  1301
            }
jaroslav@1890
  1302
        }
jaroslav@1890
  1303
    }
jaroslav@1890
  1304
jaroslav@1890
  1305
    /**
jaroslav@1890
  1306
     * Polls and cancels all submissions. Called only during termination.
jaroslav@1890
  1307
     */
jaroslav@1890
  1308
    private void cancelSubmissions() {
jaroslav@1890
  1309
        while (queueBase != queueTop) {
jaroslav@1890
  1310
            ForkJoinTask<?> task = pollSubmission();
jaroslav@1890
  1311
            if (task != null) {
jaroslav@1890
  1312
                try {
jaroslav@1890
  1313
                    task.cancel(false);
jaroslav@1890
  1314
                } catch (Throwable ignore) {
jaroslav@1890
  1315
                }
jaroslav@1890
  1316
            }
jaroslav@1890
  1317
        }
jaroslav@1890
  1318
    }
jaroslav@1890
  1319
jaroslav@1890
  1320
    /**
jaroslav@1890
  1321
     * Tries to set the termination status of waiting workers, and
jaroslav@1890
  1322
     * then wakes them up (after which they will terminate).
jaroslav@1890
  1323
     */
jaroslav@1890
  1324
    private void terminateWaiters() {
jaroslav@1890
  1325
        ForkJoinWorkerThread[] ws = workers;
jaroslav@1890
  1326
        if (ws != null) {
jaroslav@1890
  1327
            ForkJoinWorkerThread w; long c; int i, e;
jaroslav@1890
  1328
            int n = ws.length;
jaroslav@1890
  1329
            while ((i = ~(e = (int)(c = ctl)) & SMASK) < n &&
jaroslav@1890
  1330
                   (w = ws[i]) != null && w.eventCount == (e & E_MASK)) {
jaroslav@1890
  1331
                if (UNSAFE.compareAndSwapLong(this, ctlOffset, c,
jaroslav@1890
  1332
                                              (long)(w.nextWait & E_MASK) |
jaroslav@1890
  1333
                                              ((c + AC_UNIT) & AC_MASK) |
jaroslav@1890
  1334
                                              (c & (TC_MASK|STOP_BIT)))) {
jaroslav@1890
  1335
                    w.terminate = true;
jaroslav@1890
  1336
                    w.eventCount = e + EC_UNIT;
jaroslav@1890
  1337
                    if (w.parked)
jaroslav@1890
  1338
                        UNSAFE.unpark(w);
jaroslav@1890
  1339
                }
jaroslav@1890
  1340
            }
jaroslav@1890
  1341
        }
jaroslav@1890
  1342
    }
jaroslav@1890
  1343
jaroslav@1890
  1344
    // misc ForkJoinWorkerThread support
jaroslav@1890
  1345
jaroslav@1890
  1346
    /**
jaroslav@1890
  1347
     * Increment or decrement quiescerCount. Needed only to prevent
jaroslav@1890
  1348
     * triggering shutdown if a worker is transiently inactive while
jaroslav@1890
  1349
     * checking quiescence.
jaroslav@1890
  1350
     *
jaroslav@1890
  1351
     * @param delta 1 for increment, -1 for decrement
jaroslav@1890
  1352
     */
jaroslav@1890
  1353
    final void addQuiescerCount(int delta) {
jaroslav@1890
  1354
        int c;
jaroslav@1890
  1355
        do {} while (!UNSAFE.compareAndSwapInt(this, quiescerCountOffset,
jaroslav@1890
  1356
                                               c = quiescerCount, c + delta));
jaroslav@1890
  1357
    }
jaroslav@1890
  1358
jaroslav@1890
  1359
    /**
jaroslav@1890
  1360
     * Directly increment or decrement active count without
jaroslav@1890
  1361
     * queuing. This method is used to transiently assert inactivation
jaroslav@1890
  1362
     * while checking quiescence.
jaroslav@1890
  1363
     *
jaroslav@1890
  1364
     * @param delta 1 for increment, -1 for decrement
jaroslav@1890
  1365
     */
jaroslav@1890
  1366
    final void addActiveCount(int delta) {
jaroslav@1890
  1367
        long d = delta < 0 ? -AC_UNIT : AC_UNIT;
jaroslav@1890
  1368
        long c;
jaroslav@1890
  1369
        do {} while (!UNSAFE.compareAndSwapLong(this, ctlOffset, c = ctl,
jaroslav@1890
  1370
                                                ((c + d) & AC_MASK) |
jaroslav@1890
  1371
                                                (c & ~AC_MASK)));
jaroslav@1890
  1372
    }
jaroslav@1890
  1373
jaroslav@1890
  1374
    /**
jaroslav@1890
  1375
     * Returns the approximate (non-atomic) number of idle threads per
jaroslav@1890
  1376
     * active thread.
jaroslav@1890
  1377
     */
jaroslav@1890
  1378
    final int idlePerActive() {
jaroslav@1890
  1379
        // Approximate at powers of two for small values, saturate past 4
jaroslav@1890
  1380
        int p = parallelism;
jaroslav@1890
  1381
        int a = p + (int)(ctl >> AC_SHIFT);
jaroslav@1890
  1382
        return (a > (p >>>= 1) ? 0 :
jaroslav@1890
  1383
                a > (p >>>= 1) ? 1 :
jaroslav@1890
  1384
                a > (p >>>= 1) ? 2 :
jaroslav@1890
  1385
                a > (p >>>= 1) ? 4 :
jaroslav@1890
  1386
                8);
jaroslav@1890
  1387
    }
jaroslav@1890
  1388
jaroslav@1890
  1389
    // Exported methods
jaroslav@1890
  1390
jaroslav@1890
  1391
    // Constructors
jaroslav@1890
  1392
jaroslav@1890
  1393
    /**
jaroslav@1890
  1394
     * Creates a {@code ForkJoinPool} with parallelism equal to {@link
jaroslav@1890
  1395
     * java.lang.Runtime#availableProcessors}, using the {@linkplain
jaroslav@1890
  1396
     * #defaultForkJoinWorkerThreadFactory default thread factory},
jaroslav@1890
  1397
     * no UncaughtExceptionHandler, and non-async LIFO processing mode.
jaroslav@1890
  1398
     *
jaroslav@1890
  1399
     * @throws SecurityException if a security manager exists and
jaroslav@1890
  1400
     *         the caller is not permitted to modify threads
jaroslav@1890
  1401
     *         because it does not hold {@link
jaroslav@1890
  1402
     *         java.lang.RuntimePermission}{@code ("modifyThread")}
jaroslav@1890
  1403
     */
jaroslav@1890
  1404
    public ForkJoinPool() {
jaroslav@1895
  1405
        this(1,
jaroslav@1890
  1406
             defaultForkJoinWorkerThreadFactory, null, false);
jaroslav@1890
  1407
    }
jaroslav@1890
  1408
jaroslav@1890
  1409
    /**
jaroslav@1890
  1410
     * Creates a {@code ForkJoinPool} with the indicated parallelism
jaroslav@1890
  1411
     * level, the {@linkplain
jaroslav@1890
  1412
     * #defaultForkJoinWorkerThreadFactory default thread factory},
jaroslav@1890
  1413
     * no UncaughtExceptionHandler, and non-async LIFO processing mode.
jaroslav@1890
  1414
     *
jaroslav@1890
  1415
     * @param parallelism the parallelism level
jaroslav@1890
  1416
     * @throws IllegalArgumentException if parallelism less than or
jaroslav@1890
  1417
     *         equal to zero, or greater than implementation limit
jaroslav@1890
  1418
     * @throws SecurityException if a security manager exists and
jaroslav@1890
  1419
     *         the caller is not permitted to modify threads
jaroslav@1890
  1420
     *         because it does not hold {@link
jaroslav@1890
  1421
     *         java.lang.RuntimePermission}{@code ("modifyThread")}
jaroslav@1890
  1422
     */
jaroslav@1890
  1423
    public ForkJoinPool(int parallelism) {
jaroslav@1890
  1424
        this(parallelism, defaultForkJoinWorkerThreadFactory, null, false);
jaroslav@1890
  1425
    }
jaroslav@1890
  1426
jaroslav@1890
  1427
    /**
jaroslav@1890
  1428
     * Creates a {@code ForkJoinPool} with the given parameters.
jaroslav@1890
  1429
     *
jaroslav@1890
  1430
     * @param parallelism the parallelism level. For default value,
jaroslav@1890
  1431
     * use {@link java.lang.Runtime#availableProcessors}.
jaroslav@1890
  1432
     * @param factory the factory for creating new threads. For default value,
jaroslav@1890
  1433
     * use {@link #defaultForkJoinWorkerThreadFactory}.
jaroslav@1890
  1434
     * @param handler the handler for internal worker threads that
jaroslav@1890
  1435
     * terminate due to unrecoverable errors encountered while executing
jaroslav@1890
  1436
     * tasks. For default value, use {@code null}.
jaroslav@1890
  1437
     * @param asyncMode if true,
jaroslav@1890
  1438
     * establishes local first-in-first-out scheduling mode for forked
jaroslav@1890
  1439
     * tasks that are never joined. This mode may be more appropriate
jaroslav@1890
  1440
     * than default locally stack-based mode in applications in which
jaroslav@1890
  1441
     * worker threads only process event-style asynchronous tasks.
jaroslav@1890
  1442
     * For default value, use {@code false}.
jaroslav@1890
  1443
     * @throws IllegalArgumentException if parallelism less than or
jaroslav@1890
  1444
     *         equal to zero, or greater than implementation limit
jaroslav@1890
  1445
     * @throws NullPointerException if the factory is null
jaroslav@1890
  1446
     * @throws SecurityException if a security manager exists and
jaroslav@1890
  1447
     *         the caller is not permitted to modify threads
jaroslav@1890
  1448
     *         because it does not hold {@link
jaroslav@1890
  1449
     *         java.lang.RuntimePermission}{@code ("modifyThread")}
jaroslav@1890
  1450
     */
jaroslav@1890
  1451
    public ForkJoinPool(int parallelism,
jaroslav@1890
  1452
                        ForkJoinWorkerThreadFactory factory,
jaroslav@1890
  1453
                        Thread.UncaughtExceptionHandler handler,
jaroslav@1890
  1454
                        boolean asyncMode) {
jaroslav@1890
  1455
        checkPermission();
jaroslav@1890
  1456
        if (factory == null)
jaroslav@1890
  1457
            throw new NullPointerException();
jaroslav@1890
  1458
        if (parallelism <= 0 || parallelism > MAX_ID)
jaroslav@1890
  1459
            throw new IllegalArgumentException();
jaroslav@1890
  1460
        this.parallelism = parallelism;
jaroslav@1890
  1461
        this.factory = factory;
jaroslav@1890
  1462
        this.ueh = handler;
jaroslav@1890
  1463
        this.locallyFifo = asyncMode;
jaroslav@1890
  1464
        long np = (long)(-parallelism); // offset ctl counts
jaroslav@1890
  1465
        this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
jaroslav@1890
  1466
        this.submissionQueue = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY];
jaroslav@1890
  1467
        // initialize workers array with room for 2*parallelism if possible
jaroslav@1890
  1468
        int n = parallelism << 1;
jaroslav@1890
  1469
        if (n >= MAX_ID)
jaroslav@1890
  1470
            n = MAX_ID;
jaroslav@1890
  1471
        else { // See Hackers Delight, sec 3.2, where n < (1 << 16)
jaroslav@1890
  1472
            n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8;
jaroslav@1890
  1473
        }
jaroslav@1890
  1474
        workers = new ForkJoinWorkerThread[n + 1];
jaroslav@1890
  1475
        this.submissionLock = new ReentrantLock();
jaroslav@1890
  1476
        this.termination = submissionLock.newCondition();
jaroslav@1890
  1477
        StringBuilder sb = new StringBuilder("ForkJoinPool-");
jaroslav@1890
  1478
        sb.append(poolNumberGenerator.incrementAndGet());
jaroslav@1890
  1479
        sb.append("-worker-");
jaroslav@1890
  1480
        this.workerNamePrefix = sb.toString();
jaroslav@1890
  1481
    }
jaroslav@1890
  1482
jaroslav@1890
  1483
    // Execution methods
jaroslav@1890
  1484
jaroslav@1890
  1485
    /**
jaroslav@1890
  1486
     * Performs the given task, returning its result upon completion.
jaroslav@1890
  1487
     * If the computation encounters an unchecked Exception or Error,
jaroslav@1890
  1488
     * it is rethrown as the outcome of this invocation.  Rethrown
jaroslav@1890
  1489
     * exceptions behave in the same way as regular exceptions, but,
jaroslav@1890
  1490
     * when possible, contain stack traces (as displayed for example
jaroslav@1890
  1491
     * using {@code ex.printStackTrace()}) of both the current thread
jaroslav@1890
  1492
     * as well as the thread actually encountering the exception;
jaroslav@1890
  1493
     * minimally only the latter.
jaroslav@1890
  1494
     *
jaroslav@1890
  1495
     * @param task the task
jaroslav@1890
  1496
     * @return the task's result
jaroslav@1890
  1497
     * @throws NullPointerException if the task is null
jaroslav@1890
  1498
     * @throws RejectedExecutionException if the task cannot be
jaroslav@1890
  1499
     *         scheduled for execution
jaroslav@1890
  1500
     */
jaroslav@1890
  1501
    public <T> T invoke(ForkJoinTask<T> task) {
jaroslav@1890
  1502
        Thread t = Thread.currentThread();
jaroslav@1890
  1503
        if (task == null)
jaroslav@1890
  1504
            throw new NullPointerException();
jaroslav@1890
  1505
        if (shutdown)
jaroslav@1890
  1506
            throw new RejectedExecutionException();
jaroslav@1890
  1507
        if ((t instanceof ForkJoinWorkerThread) &&
jaroslav@1890
  1508
            ((ForkJoinWorkerThread)t).pool == this)
jaroslav@1890
  1509
            return task.invoke();  // bypass submit if in same pool
jaroslav@1890
  1510
        else {
jaroslav@1890
  1511
            addSubmission(task);
jaroslav@1890
  1512
            return task.join();
jaroslav@1890
  1513
        }
jaroslav@1890
  1514
    }
jaroslav@1890
  1515
jaroslav@1890
  1516
    /**
jaroslav@1890
  1517
     * Unless terminating, forks task if within an ongoing FJ
jaroslav@1890
  1518
     * computation in the current pool, else submits as external task.
jaroslav@1890
  1519
     */
jaroslav@1890
  1520
    private <T> void forkOrSubmit(ForkJoinTask<T> task) {
jaroslav@1890
  1521
        ForkJoinWorkerThread w;
jaroslav@1890
  1522
        Thread t = Thread.currentThread();
jaroslav@1890
  1523
        if (shutdown)
jaroslav@1890
  1524
            throw new RejectedExecutionException();
jaroslav@1890
  1525
        if ((t instanceof ForkJoinWorkerThread) &&
jaroslav@1890
  1526
            (w = (ForkJoinWorkerThread)t).pool == this)
jaroslav@1890
  1527
            w.pushTask(task);
jaroslav@1890
  1528
        else
jaroslav@1890
  1529
            addSubmission(task);
jaroslav@1890
  1530
    }
jaroslav@1890
  1531
jaroslav@1890
  1532
    /**
jaroslav@1890
  1533
     * Arranges for (asynchronous) execution of the given task.
jaroslav@1890
  1534
     *
jaroslav@1890
  1535
     * @param task the task
jaroslav@1890
  1536
     * @throws NullPointerException if the task is null
jaroslav@1890
  1537
     * @throws RejectedExecutionException if the task cannot be
jaroslav@1890
  1538
     *         scheduled for execution
jaroslav@1890
  1539
     */
jaroslav@1890
  1540
    public void execute(ForkJoinTask<?> task) {
jaroslav@1890
  1541
        if (task == null)
jaroslav@1890
  1542
            throw new NullPointerException();
jaroslav@1890
  1543
        forkOrSubmit(task);
jaroslav@1890
  1544
    }
jaroslav@1890
  1545
jaroslav@1890
  1546
    // AbstractExecutorService methods
jaroslav@1890
  1547
jaroslav@1890
  1548
    /**
jaroslav@1890
  1549
     * @throws NullPointerException if the task is null
jaroslav@1890
  1550
     * @throws RejectedExecutionException if the task cannot be
jaroslav@1890
  1551
     *         scheduled for execution
jaroslav@1890
  1552
     */
jaroslav@1890
  1553
    public void execute(Runnable task) {
jaroslav@1890
  1554
        if (task == null)
jaroslav@1890
  1555
            throw new NullPointerException();
jaroslav@1890
  1556
        ForkJoinTask<?> job;
jaroslav@1890
  1557
        if (task instanceof ForkJoinTask<?>) // avoid re-wrap
jaroslav@1890
  1558
            job = (ForkJoinTask<?>) task;
jaroslav@1890
  1559
        else
jaroslav@1890
  1560
            job = ForkJoinTask.adapt(task, null);
jaroslav@1890
  1561
        forkOrSubmit(job);
jaroslav@1890
  1562
    }
jaroslav@1890
  1563
jaroslav@1890
  1564
    /**
jaroslav@1890
  1565
     * Submits a ForkJoinTask for execution.
jaroslav@1890
  1566
     *
jaroslav@1890
  1567
     * @param task the task to submit
jaroslav@1890
  1568
     * @return the task
jaroslav@1890
  1569
     * @throws NullPointerException if the task is null
jaroslav@1890
  1570
     * @throws RejectedExecutionException if the task cannot be
jaroslav@1890
  1571
     *         scheduled for execution
jaroslav@1890
  1572
     */
jaroslav@1890
  1573
    public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
jaroslav@1890
  1574
        if (task == null)
jaroslav@1890
  1575
            throw new NullPointerException();
jaroslav@1890
  1576
        forkOrSubmit(task);
jaroslav@1890
  1577
        return task;
jaroslav@1890
  1578
    }
jaroslav@1890
  1579
jaroslav@1890
  1580
    /**
jaroslav@1890
  1581
     * @throws NullPointerException if the task is null
jaroslav@1890
  1582
     * @throws RejectedExecutionException if the task cannot be
jaroslav@1890
  1583
     *         scheduled for execution
jaroslav@1890
  1584
     */
jaroslav@1890
  1585
    public <T> ForkJoinTask<T> submit(Callable<T> task) {
jaroslav@1890
  1586
        if (task == null)
jaroslav@1890
  1587
            throw new NullPointerException();
jaroslav@1890
  1588
        ForkJoinTask<T> job = ForkJoinTask.adapt(task);
jaroslav@1890
  1589
        forkOrSubmit(job);
jaroslav@1890
  1590
        return job;
jaroslav@1890
  1591
    }
jaroslav@1890
  1592
jaroslav@1890
  1593
    /**
jaroslav@1890
  1594
     * @throws NullPointerException if the task is null
jaroslav@1890
  1595
     * @throws RejectedExecutionException if the task cannot be
jaroslav@1890
  1596
     *         scheduled for execution
jaroslav@1890
  1597
     */
jaroslav@1890
  1598
    public <T> ForkJoinTask<T> submit(Runnable task, T result) {
jaroslav@1890
  1599
        if (task == null)
jaroslav@1890
  1600
            throw new NullPointerException();
jaroslav@1890
  1601
        ForkJoinTask<T> job = ForkJoinTask.adapt(task, result);
jaroslav@1890
  1602
        forkOrSubmit(job);
jaroslav@1890
  1603
        return job;
jaroslav@1890
  1604
    }
jaroslav@1890
  1605
jaroslav@1890
  1606
    /**
jaroslav@1890
  1607
     * @throws NullPointerException if the task is null
jaroslav@1890
  1608
     * @throws RejectedExecutionException if the task cannot be
jaroslav@1890
  1609
     *         scheduled for execution
jaroslav@1890
  1610
     */
jaroslav@1890
  1611
    public ForkJoinTask<?> submit(Runnable task) {
jaroslav@1890
  1612
        if (task == null)
jaroslav@1890
  1613
            throw new NullPointerException();
jaroslav@1890
  1614
        ForkJoinTask<?> job;
jaroslav@1890
  1615
        if (task instanceof ForkJoinTask<?>) // avoid re-wrap
jaroslav@1890
  1616
            job = (ForkJoinTask<?>) task;
jaroslav@1890
  1617
        else
jaroslav@1890
  1618
            job = ForkJoinTask.adapt(task, null);
jaroslav@1890
  1619
        forkOrSubmit(job);
jaroslav@1890
  1620
        return job;
jaroslav@1890
  1621
    }
jaroslav@1890
  1622
jaroslav@1890
  1623
    /**
jaroslav@1890
  1624
     * @throws NullPointerException       {@inheritDoc}
jaroslav@1890
  1625
     * @throws RejectedExecutionException {@inheritDoc}
jaroslav@1890
  1626
     */
jaroslav@1890
  1627
    public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
jaroslav@1890
  1628
        ArrayList<ForkJoinTask<T>> forkJoinTasks =
jaroslav@1890
  1629
            new ArrayList<ForkJoinTask<T>>(tasks.size());
jaroslav@1890
  1630
        for (Callable<T> task : tasks)
jaroslav@1890
  1631
            forkJoinTasks.add(ForkJoinTask.adapt(task));
jaroslav@1890
  1632
        invoke(new InvokeAll<T>(forkJoinTasks));
jaroslav@1890
  1633
jaroslav@1890
  1634
        @SuppressWarnings({"unchecked", "rawtypes"})
jaroslav@1890
  1635
            List<Future<T>> futures = (List<Future<T>>) (List) forkJoinTasks;
jaroslav@1890
  1636
        return futures;
jaroslav@1890
  1637
    }
jaroslav@1890
  1638
jaroslav@1890
  1639
    static final class InvokeAll<T> extends RecursiveAction {
jaroslav@1890
  1640
        final ArrayList<ForkJoinTask<T>> tasks;
jaroslav@1890
  1641
        InvokeAll(ArrayList<ForkJoinTask<T>> tasks) { this.tasks = tasks; }
jaroslav@1890
  1642
        public void compute() {
jaroslav@1890
  1643
            try { invokeAll(tasks); }
jaroslav@1890
  1644
            catch (Exception ignore) {}
jaroslav@1890
  1645
        }
jaroslav@1890
  1646
        private static final long serialVersionUID = -7914297376763021607L;
jaroslav@1890
  1647
    }
jaroslav@1890
  1648
jaroslav@1890
  1649
    /**
jaroslav@1890
  1650
     * Returns the factory used for constructing new workers.
jaroslav@1890
  1651
     *
jaroslav@1890
  1652
     * @return the factory used for constructing new workers
jaroslav@1890
  1653
     */
jaroslav@1890
  1654
    public ForkJoinWorkerThreadFactory getFactory() {
jaroslav@1890
  1655
        return factory;
jaroslav@1890
  1656
    }
jaroslav@1890
  1657
jaroslav@1890
  1658
    /**
jaroslav@1890
  1659
     * Returns the handler for internal worker threads that terminate
jaroslav@1890
  1660
     * due to unrecoverable errors encountered while executing tasks.
jaroslav@1890
  1661
     *
jaroslav@1890
  1662
     * @return the handler, or {@code null} if none
jaroslav@1890
  1663
     */
jaroslav@1890
  1664
    public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() {
jaroslav@1890
  1665
        return ueh;
jaroslav@1890
  1666
    }
jaroslav@1890
  1667
jaroslav@1890
  1668
    /**
jaroslav@1890
  1669
     * Returns the targeted parallelism level of this pool.
jaroslav@1890
  1670
     *
jaroslav@1890
  1671
     * @return the targeted parallelism level of this pool
jaroslav@1890
  1672
     */
jaroslav@1890
  1673
    public int getParallelism() {
jaroslav@1890
  1674
        return parallelism;
jaroslav@1890
  1675
    }
jaroslav@1890
  1676
jaroslav@1890
  1677
    /**
jaroslav@1890
  1678
     * Returns the number of worker threads that have started but not
jaroslav@1890
  1679
     * yet terminated.  The result returned by this method may differ
jaroslav@1890
  1680
     * from {@link #getParallelism} when threads are created to
jaroslav@1890
  1681
     * maintain parallelism when others are cooperatively blocked.
jaroslav@1890
  1682
     *
jaroslav@1890
  1683
     * @return the number of worker threads
jaroslav@1890
  1684
     */
jaroslav@1890
  1685
    public int getPoolSize() {
jaroslav@1890
  1686
        return parallelism + (short)(ctl >>> TC_SHIFT);
jaroslav@1890
  1687
    }
jaroslav@1890
  1688
jaroslav@1890
  1689
    /**
jaroslav@1890
  1690
     * Returns {@code true} if this pool uses local first-in-first-out
jaroslav@1890
  1691
     * scheduling mode for forked tasks that are never joined.
jaroslav@1890
  1692
     *
jaroslav@1890
  1693
     * @return {@code true} if this pool uses async mode
jaroslav@1890
  1694
     */
jaroslav@1890
  1695
    public boolean getAsyncMode() {
jaroslav@1890
  1696
        return locallyFifo;
jaroslav@1890
  1697
    }
jaroslav@1890
  1698
jaroslav@1890
  1699
    /**
jaroslav@1890
  1700
     * Returns an estimate of the number of worker threads that are
jaroslav@1890
  1701
     * not blocked waiting to join tasks or for other managed
jaroslav@1890
  1702
     * synchronization. This method may overestimate the
jaroslav@1890
  1703
     * number of running threads.
jaroslav@1890
  1704
     *
jaroslav@1890
  1705
     * @return the number of worker threads
jaroslav@1890
  1706
     */
jaroslav@1890
  1707
    public int getRunningThreadCount() {
jaroslav@1890
  1708
        int r = parallelism + (int)(ctl >> AC_SHIFT);
jaroslav@1890
  1709
        return (r <= 0) ? 0 : r; // suppress momentarily negative values
jaroslav@1890
  1710
    }
jaroslav@1890
  1711
jaroslav@1890
  1712
    /**
jaroslav@1890
  1713
     * Returns an estimate of the number of threads that are currently
jaroslav@1890
  1714
     * stealing or executing tasks. This method may overestimate the
jaroslav@1890
  1715
     * number of active threads.
jaroslav@1890
  1716
     *
jaroslav@1890
  1717
     * @return the number of active threads
jaroslav@1890
  1718
     */
jaroslav@1890
  1719
    public int getActiveThreadCount() {
jaroslav@1890
  1720
        int r = parallelism + (int)(ctl >> AC_SHIFT) + blockedCount;
jaroslav@1890
  1721
        return (r <= 0) ? 0 : r; // suppress momentarily negative values
jaroslav@1890
  1722
    }
jaroslav@1890
  1723
jaroslav@1890
  1724
    /**
jaroslav@1890
  1725
     * Returns {@code true} if all worker threads are currently idle.
jaroslav@1890
  1726
     * An idle worker is one that cannot obtain a task to execute
jaroslav@1890
  1727
     * because none are available to steal from other threads, and
jaroslav@1890
  1728
     * there are no pending submissions to the pool. This method is
jaroslav@1890
  1729
     * conservative; it might not return {@code true} immediately upon
jaroslav@1890
  1730
     * idleness of all threads, but will eventually become true if
jaroslav@1890
  1731
     * threads remain inactive.
jaroslav@1890
  1732
     *
jaroslav@1890
  1733
     * @return {@code true} if all threads are currently idle
jaroslav@1890
  1734
     */
jaroslav@1890
  1735
    public boolean isQuiescent() {
jaroslav@1890
  1736
        return parallelism + (int)(ctl >> AC_SHIFT) + blockedCount == 0;
jaroslav@1890
  1737
    }
jaroslav@1890
  1738
jaroslav@1890
  1739
    /**
jaroslav@1890
  1740
     * Returns an estimate of the total number of tasks stolen from
jaroslav@1890
  1741
     * one thread's work queue by another. The reported value
jaroslav@1890
  1742
     * underestimates the actual total number of steals when the pool
jaroslav@1890
  1743
     * is not quiescent. This value may be useful for monitoring and
jaroslav@1890
  1744
     * tuning fork/join programs: in general, steal counts should be
jaroslav@1890
  1745
     * high enough to keep threads busy, but low enough to avoid
jaroslav@1890
  1746
     * overhead and contention across threads.
jaroslav@1890
  1747
     *
jaroslav@1890
  1748
     * @return the number of steals
jaroslav@1890
  1749
     */
jaroslav@1890
  1750
    public long getStealCount() {
jaroslav@1890
  1751
        return stealCount;
jaroslav@1890
  1752
    }
jaroslav@1890
  1753
jaroslav@1890
  1754
    /**
jaroslav@1890
  1755
     * Returns an estimate of the total number of tasks currently held
jaroslav@1890
  1756
     * in queues by worker threads (but not including tasks submitted
jaroslav@1890
  1757
     * to the pool that have not begun executing). This value is only
jaroslav@1890
  1758
     * an approximation, obtained by iterating across all threads in
jaroslav@1890
  1759
     * the pool. This method may be useful for tuning task
jaroslav@1890
  1760
     * granularities.
jaroslav@1890
  1761
     *
jaroslav@1890
  1762
     * @return the number of queued tasks
jaroslav@1890
  1763
     */
jaroslav@1890
  1764
    public long getQueuedTaskCount() {
jaroslav@1890
  1765
        long count = 0;
jaroslav@1890
  1766
        ForkJoinWorkerThread[] ws;
jaroslav@1890
  1767
        if ((short)(ctl >>> TC_SHIFT) > -parallelism &&
jaroslav@1890
  1768
            (ws = workers) != null) {
jaroslav@1890
  1769
            for (ForkJoinWorkerThread w : ws)
jaroslav@1890
  1770
                if (w != null)
jaroslav@1890
  1771
                    count -= w.queueBase - w.queueTop; // must read base first
jaroslav@1890
  1772
        }
jaroslav@1890
  1773
        return count;
jaroslav@1890
  1774
    }
jaroslav@1890
  1775
jaroslav@1890
  1776
    /**
jaroslav@1890
  1777
     * Returns an estimate of the number of tasks submitted to this
jaroslav@1890
  1778
     * pool that have not yet begun executing.  This method may take
jaroslav@1890
  1779
     * time proportional to the number of submissions.
jaroslav@1890
  1780
     *
jaroslav@1890
  1781
     * @return the number of queued submissions
jaroslav@1890
  1782
     */
jaroslav@1890
  1783
    public int getQueuedSubmissionCount() {
jaroslav@1890
  1784
        return -queueBase + queueTop;
jaroslav@1890
  1785
    }
jaroslav@1890
  1786
jaroslav@1890
  1787
    /**
jaroslav@1890
  1788
     * Returns {@code true} if there are any tasks submitted to this
jaroslav@1890
  1789
     * pool that have not yet begun executing.
jaroslav@1890
  1790
     *
jaroslav@1890
  1791
     * @return {@code true} if there are any queued submissions
jaroslav@1890
  1792
     */
jaroslav@1890
  1793
    public boolean hasQueuedSubmissions() {
jaroslav@1890
  1794
        return queueBase != queueTop;
jaroslav@1890
  1795
    }
jaroslav@1890
  1796
jaroslav@1890
  1797
    /**
jaroslav@1890
  1798
     * Removes and returns the next unexecuted submission if one is
jaroslav@1890
  1799
     * available.  This method may be useful in extensions to this
jaroslav@1890
  1800
     * class that re-assign work in systems with multiple pools.
jaroslav@1890
  1801
     *
jaroslav@1890
  1802
     * @return the next submission, or {@code null} if none
jaroslav@1890
  1803
     */
jaroslav@1890
  1804
    protected ForkJoinTask<?> pollSubmission() {
jaroslav@1890
  1805
        ForkJoinTask<?> t; ForkJoinTask<?>[] q; int b, i;
jaroslav@1890
  1806
        while ((b = queueBase) != queueTop &&
jaroslav@1890
  1807
               (q = submissionQueue) != null &&
jaroslav@1890
  1808
               (i = (q.length - 1) & b) >= 0) {
jaroslav@1890
  1809
            long u = (i << ASHIFT) + ABASE;
jaroslav@1890
  1810
            if ((t = q[i]) != null &&
jaroslav@1890
  1811
                queueBase == b &&
jaroslav@1890
  1812
                UNSAFE.compareAndSwapObject(q, u, t, null)) {
jaroslav@1890
  1813
                queueBase = b + 1;
jaroslav@1890
  1814
                return t;
jaroslav@1890
  1815
            }
jaroslav@1890
  1816
        }
jaroslav@1890
  1817
        return null;
jaroslav@1890
  1818
    }
jaroslav@1890
  1819
jaroslav@1890
  1820
    /**
jaroslav@1890
  1821
     * Removes all available unexecuted submitted and forked tasks
jaroslav@1890
  1822
     * from scheduling queues and adds them to the given collection,
jaroslav@1890
  1823
     * without altering their execution status. These may include
jaroslav@1890
  1824
     * artificially generated or wrapped tasks. This method is
jaroslav@1890
  1825
     * designed to be invoked only when the pool is known to be
jaroslav@1890
  1826
     * quiescent. Invocations at other times may not remove all
jaroslav@1890
  1827
     * tasks. A failure encountered while attempting to add elements
jaroslav@1890
  1828
     * to collection {@code c} may result in elements being in
jaroslav@1890
  1829
     * neither, either or both collections when the associated
jaroslav@1890
  1830
     * exception is thrown.  The behavior of this operation is
jaroslav@1890
  1831
     * undefined if the specified collection is modified while the
jaroslav@1890
  1832
     * operation is in progress.
jaroslav@1890
  1833
     *
jaroslav@1890
  1834
     * @param c the collection to transfer elements into
jaroslav@1890
  1835
     * @return the number of elements transferred
jaroslav@1890
  1836
     */
jaroslav@1890
  1837
    protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
jaroslav@1890
  1838
        int count = 0;
jaroslav@1890
  1839
        while (queueBase != queueTop) {
jaroslav@1890
  1840
            ForkJoinTask<?> t = pollSubmission();
jaroslav@1890
  1841
            if (t != null) {
jaroslav@1890
  1842
                c.add(t);
jaroslav@1890
  1843
                ++count;
jaroslav@1890
  1844
            }
jaroslav@1890
  1845
        }
jaroslav@1890
  1846
        ForkJoinWorkerThread[] ws;
jaroslav@1890
  1847
        if ((short)(ctl >>> TC_SHIFT) > -parallelism &&
jaroslav@1890
  1848
            (ws = workers) != null) {
jaroslav@1890
  1849
            for (ForkJoinWorkerThread w : ws)
jaroslav@1890
  1850
                if (w != null)
jaroslav@1890
  1851
                    count += w.drainTasksTo(c);
jaroslav@1890
  1852
        }
jaroslav@1890
  1853
        return count;
jaroslav@1890
  1854
    }
jaroslav@1890
  1855
jaroslav@1890
  1856
    /**
jaroslav@1890
  1857
     * Returns a string identifying this pool, as well as its state,
jaroslav@1890
  1858
     * including indications of run state, parallelism level, and
jaroslav@1890
  1859
     * worker and task counts.
jaroslav@1890
  1860
     *
jaroslav@1890
  1861
     * @return a string identifying this pool, as well as its state
jaroslav@1890
  1862
     */
jaroslav@1890
  1863
    public String toString() {
jaroslav@1890
  1864
        long st = getStealCount();
jaroslav@1890
  1865
        long qt = getQueuedTaskCount();
jaroslav@1890
  1866
        long qs = getQueuedSubmissionCount();
jaroslav@1890
  1867
        int pc = parallelism;
jaroslav@1890
  1868
        long c = ctl;
jaroslav@1890
  1869
        int tc = pc + (short)(c >>> TC_SHIFT);
jaroslav@1890
  1870
        int rc = pc + (int)(c >> AC_SHIFT);
jaroslav@1890
  1871
        if (rc < 0) // ignore transient negative
jaroslav@1890
  1872
            rc = 0;
jaroslav@1890
  1873
        int ac = rc + blockedCount;
jaroslav@1890
  1874
        String level;
jaroslav@1890
  1875
        if ((c & STOP_BIT) != 0)
jaroslav@1890
  1876
            level = (tc == 0) ? "Terminated" : "Terminating";
jaroslav@1890
  1877
        else
jaroslav@1890
  1878
            level = shutdown ? "Shutting down" : "Running";
jaroslav@1890
  1879
        return super.toString() +
jaroslav@1890
  1880
            "[" + level +
jaroslav@1890
  1881
            ", parallelism = " + pc +
jaroslav@1890
  1882
            ", size = " + tc +
jaroslav@1890
  1883
            ", active = " + ac +
jaroslav@1890
  1884
            ", running = " + rc +
jaroslav@1890
  1885
            ", steals = " + st +
jaroslav@1890
  1886
            ", tasks = " + qt +
jaroslav@1890
  1887
            ", submissions = " + qs +
jaroslav@1890
  1888
            "]";
jaroslav@1890
  1889
    }
jaroslav@1890
  1890
jaroslav@1890
  1891
    /**
jaroslav@1890
  1892
     * Initiates an orderly shutdown in which previously submitted
jaroslav@1890
  1893
     * tasks are executed, but no new tasks will be accepted.
jaroslav@1890
  1894
     * Invocation has no additional effect if already shut down.
jaroslav@1890
  1895
     * Tasks that are in the process of being submitted concurrently
jaroslav@1890
  1896
     * during the course of this method may or may not be rejected.
jaroslav@1890
  1897
     *
jaroslav@1890
  1898
     * @throws SecurityException if a security manager exists and
jaroslav@1890
  1899
     *         the caller is not permitted to modify threads
jaroslav@1890
  1900
     *         because it does not hold {@link
jaroslav@1890
  1901
     *         java.lang.RuntimePermission}{@code ("modifyThread")}
jaroslav@1890
  1902
     */
jaroslav@1890
  1903
    public void shutdown() {
jaroslav@1890
  1904
        checkPermission();
jaroslav@1890
  1905
        shutdown = true;
jaroslav@1890
  1906
        tryTerminate(false);
jaroslav@1890
  1907
    }
jaroslav@1890
  1908
jaroslav@1890
  1909
    /**
jaroslav@1890
  1910
     * Attempts to cancel and/or stop all tasks, and reject all
jaroslav@1890
  1911
     * subsequently submitted tasks.  Tasks that are in the process of
jaroslav@1890
  1912
     * being submitted or executed concurrently during the course of
jaroslav@1890
  1913
     * this method may or may not be rejected. This method cancels
jaroslav@1890
  1914
     * both existing and unexecuted tasks, in order to permit
jaroslav@1890
  1915
     * termination in the presence of task dependencies. So the method
jaroslav@1890
  1916
     * always returns an empty list (unlike the case for some other
jaroslav@1890
  1917
     * Executors).
jaroslav@1890
  1918
     *
jaroslav@1890
  1919
     * @return an empty list
jaroslav@1890
  1920
     * @throws SecurityException if a security manager exists and
jaroslav@1890
  1921
     *         the caller is not permitted to modify threads
jaroslav@1890
  1922
     *         because it does not hold {@link
jaroslav@1890
  1923
     *         java.lang.RuntimePermission}{@code ("modifyThread")}
jaroslav@1890
  1924
     */
jaroslav@1890
  1925
    public List<Runnable> shutdownNow() {
jaroslav@1890
  1926
        checkPermission();
jaroslav@1890
  1927
        shutdown = true;
jaroslav@1890
  1928
        tryTerminate(true);
jaroslav@1890
  1929
        return Collections.emptyList();
jaroslav@1890
  1930
    }
jaroslav@1890
  1931
jaroslav@1890
  1932
    /**
jaroslav@1890
  1933
     * Returns {@code true} if all tasks have completed following shut down.
jaroslav@1890
  1934
     *
jaroslav@1890
  1935
     * @return {@code true} if all tasks have completed following shut down
jaroslav@1890
  1936
     */
jaroslav@1890
  1937
    public boolean isTerminated() {
jaroslav@1890
  1938
        long c = ctl;
jaroslav@1890
  1939
        return ((c & STOP_BIT) != 0L &&
jaroslav@1890
  1940
                (short)(c >>> TC_SHIFT) == -parallelism);
jaroslav@1890
  1941
    }
jaroslav@1890
  1942
jaroslav@1890
  1943
    /**
jaroslav@1890
  1944
     * Returns {@code true} if the process of termination has
jaroslav@1890
  1945
     * commenced but not yet completed.  This method may be useful for
jaroslav@1890
  1946
     * debugging. A return of {@code true} reported a sufficient
jaroslav@1890
  1947
     * period after shutdown may indicate that submitted tasks have
jaroslav@1890
  1948
     * ignored or suppressed interruption, or are waiting for IO,
jaroslav@1890
  1949
     * causing this executor not to properly terminate. (See the
jaroslav@1890
  1950
     * advisory notes for class {@link ForkJoinTask} stating that
jaroslav@1890
  1951
     * tasks should not normally entail blocking operations.  But if
jaroslav@1890
  1952
     * they do, they must abort them on interrupt.)
jaroslav@1890
  1953
     *
jaroslav@1890
  1954
     * @return {@code true} if terminating but not yet terminated
jaroslav@1890
  1955
     */
jaroslav@1890
  1956
    public boolean isTerminating() {
jaroslav@1890
  1957
        long c = ctl;
jaroslav@1890
  1958
        return ((c & STOP_BIT) != 0L &&
jaroslav@1890
  1959
                (short)(c >>> TC_SHIFT) != -parallelism);
jaroslav@1890
  1960
    }
jaroslav@1890
  1961
jaroslav@1890
  1962
    /**
jaroslav@1890
  1963
     * Returns true if terminating or terminated. Used by ForkJoinWorkerThread.
jaroslav@1890
  1964
     */
jaroslav@1890
  1965
    final boolean isAtLeastTerminating() {
jaroslav@1890
  1966
        return (ctl & STOP_BIT) != 0L;
jaroslav@1890
  1967
    }
jaroslav@1890
  1968
jaroslav@1890
  1969
    /**
jaroslav@1890
  1970
     * Returns {@code true} if this pool has been shut down.
jaroslav@1890
  1971
     *
jaroslav@1890
  1972
     * @return {@code true} if this pool has been shut down
jaroslav@1890
  1973
     */
jaroslav@1890
  1974
    public boolean isShutdown() {
jaroslav@1890
  1975
        return shutdown;
jaroslav@1890
  1976
    }
jaroslav@1890
  1977
jaroslav@1890
  1978
    /**
jaroslav@1890
  1979
     * Blocks until all tasks have completed execution after a shutdown
jaroslav@1890
  1980
     * request, or the timeout occurs, or the current thread is
jaroslav@1890
  1981
     * interrupted, whichever happens first.
jaroslav@1890
  1982
     *
jaroslav@1890
  1983
     * @param timeout the maximum time to wait
jaroslav@1890
  1984
     * @param unit the time unit of the timeout argument
jaroslav@1890
  1985
     * @return {@code true} if this executor terminated and
jaroslav@1890
  1986
     *         {@code false} if the timeout elapsed before termination
jaroslav@1890
  1987
     * @throws InterruptedException if interrupted while waiting
jaroslav@1890
  1988
     */
jaroslav@1890
  1989
    public boolean awaitTermination(long timeout, TimeUnit unit)
jaroslav@1890
  1990
        throws InterruptedException {
jaroslav@1890
  1991
        long nanos = unit.toNanos(timeout);
jaroslav@1890
  1992
        final ReentrantLock lock = this.submissionLock;
jaroslav@1890
  1993
        lock.lock();
jaroslav@1890
  1994
        try {
jaroslav@1890
  1995
            for (;;) {
jaroslav@1890
  1996
                if (isTerminated())
jaroslav@1890
  1997
                    return true;
jaroslav@1890
  1998
                if (nanos <= 0)
jaroslav@1890
  1999
                    return false;
jaroslav@1890
  2000
                nanos = termination.awaitNanos(nanos);
jaroslav@1890
  2001
            }
jaroslav@1890
  2002
        } finally {
jaroslav@1890
  2003
            lock.unlock();
jaroslav@1890
  2004
        }
jaroslav@1890
  2005
    }
jaroslav@1890
  2006
jaroslav@1890
  2007
    /**
jaroslav@1890
  2008
     * Interface for extending managed parallelism for tasks running
jaroslav@1890
  2009
     * in {@link ForkJoinPool}s.
jaroslav@1890
  2010
     *
jaroslav@1890
  2011
     * <p>A {@code ManagedBlocker} provides two methods.  Method
jaroslav@1890
  2012
     * {@code isReleasable} must return {@code true} if blocking is
jaroslav@1890
  2013
     * not necessary. Method {@code block} blocks the current thread
jaroslav@1890
  2014
     * if necessary (perhaps internally invoking {@code isReleasable}
jaroslav@1890
  2015
     * before actually blocking). These actions are performed by any
jaroslav@1890
  2016
     * thread invoking {@link ForkJoinPool#managedBlock}.  The
jaroslav@1890
  2017
     * unusual methods in this API accommodate synchronizers that may,
jaroslav@1890
  2018
     * but don't usually, block for long periods. Similarly, they
jaroslav@1890
  2019
     * allow more efficient internal handling of cases in which
jaroslav@1890
  2020
     * additional workers may be, but usually are not, needed to
jaroslav@1890
  2021
     * ensure sufficient parallelism.  Toward this end,
jaroslav@1890
  2022
     * implementations of method {@code isReleasable} must be amenable
jaroslav@1890
  2023
     * to repeated invocation.
jaroslav@1890
  2024
     *
jaroslav@1890
  2025
     * <p>For example, here is a ManagedBlocker based on a
jaroslav@1890
  2026
     * ReentrantLock:
jaroslav@1890
  2027
     *  <pre> {@code
jaroslav@1890
  2028
     * class ManagedLocker implements ManagedBlocker {
jaroslav@1890
  2029
     *   final ReentrantLock lock;
jaroslav@1890
  2030
     *   boolean hasLock = false;
jaroslav@1890
  2031
     *   ManagedLocker(ReentrantLock lock) { this.lock = lock; }
jaroslav@1890
  2032
     *   public boolean block() {
jaroslav@1890
  2033
     *     if (!hasLock)
jaroslav@1890
  2034
     *       lock.lock();
jaroslav@1890
  2035
     *     return true;
jaroslav@1890
  2036
     *   }
jaroslav@1890
  2037
     *   public boolean isReleasable() {
jaroslav@1890
  2038
     *     return hasLock || (hasLock = lock.tryLock());
jaroslav@1890
  2039
     *   }
jaroslav@1890
  2040
     * }}</pre>
jaroslav@1890
  2041
     *
jaroslav@1890
  2042
     * <p>Here is a class that possibly blocks waiting for an
jaroslav@1890
  2043
     * item on a given queue:
jaroslav@1890
  2044
     *  <pre> {@code
jaroslav@1890
  2045
     * class QueueTaker<E> implements ManagedBlocker {
jaroslav@1890
  2046
     *   final BlockingQueue<E> queue;
jaroslav@1890
  2047
     *   volatile E item = null;
jaroslav@1890
  2048
     *   QueueTaker(BlockingQueue<E> q) { this.queue = q; }
jaroslav@1890
  2049
     *   public boolean block() throws InterruptedException {
jaroslav@1890
  2050
     *     if (item == null)
jaroslav@1890
  2051
     *       item = queue.take();
jaroslav@1890
  2052
     *     return true;
jaroslav@1890
  2053
     *   }
jaroslav@1890
  2054
     *   public boolean isReleasable() {
jaroslav@1890
  2055
     *     return item != null || (item = queue.poll()) != null;
jaroslav@1890
  2056
     *   }
jaroslav@1890
  2057
     *   public E getItem() { // call after pool.managedBlock completes
jaroslav@1890
  2058
     *     return item;
jaroslav@1890
  2059
     *   }
jaroslav@1890
  2060
     * }}</pre>
jaroslav@1890
  2061
     */
jaroslav@1890
  2062
    public static interface ManagedBlocker {
jaroslav@1890
  2063
        /**
jaroslav@1890
  2064
         * Possibly blocks the current thread, for example waiting for
jaroslav@1890
  2065
         * a lock or condition.
jaroslav@1890
  2066
         *
jaroslav@1890
  2067
         * @return {@code true} if no additional blocking is necessary
jaroslav@1890
  2068
         * (i.e., if isReleasable would return true)
jaroslav@1890
  2069
         * @throws InterruptedException if interrupted while waiting
jaroslav@1890
  2070
         * (the method is not required to do so, but is allowed to)
jaroslav@1890
  2071
         */
jaroslav@1890
  2072
        boolean block() throws InterruptedException;
jaroslav@1890
  2073
jaroslav@1890
  2074
        /**
jaroslav@1890
  2075
         * Returns {@code true} if blocking is unnecessary.
jaroslav@1890
  2076
         */
jaroslav@1890
  2077
        boolean isReleasable();
jaroslav@1890
  2078
    }
jaroslav@1890
  2079
jaroslav@1890
  2080
    /**
jaroslav@1890
  2081
     * Blocks in accord with the given blocker.  If the current thread
jaroslav@1890
  2082
     * is a {@link ForkJoinWorkerThread}, this method possibly
jaroslav@1890
  2083
     * arranges for a spare thread to be activated if necessary to
jaroslav@1890
  2084
     * ensure sufficient parallelism while the current thread is blocked.
jaroslav@1890
  2085
     *
jaroslav@1890
  2086
     * <p>If the caller is not a {@link ForkJoinTask}, this method is
jaroslav@1890
  2087
     * behaviorally equivalent to
jaroslav@1890
  2088
     *  <pre> {@code
jaroslav@1890
  2089
     * while (!blocker.isReleasable())
jaroslav@1890
  2090
     *   if (blocker.block())
jaroslav@1890
  2091
     *     return;
jaroslav@1890
  2092
     * }</pre>
jaroslav@1890
  2093
     *
jaroslav@1890
  2094
     * If the caller is a {@code ForkJoinTask}, then the pool may
jaroslav@1890
  2095
     * first be expanded to ensure parallelism, and later adjusted.
jaroslav@1890
  2096
     *
jaroslav@1890
  2097
     * @param blocker the blocker
jaroslav@1890
  2098
     * @throws InterruptedException if blocker.block did so
jaroslav@1890
  2099
     */
jaroslav@1890
  2100
    public static void managedBlock(ManagedBlocker blocker)
jaroslav@1890
  2101
        throws InterruptedException {
jaroslav@1890
  2102
        Thread t = Thread.currentThread();
jaroslav@1890
  2103
        if (t instanceof ForkJoinWorkerThread) {
jaroslav@1890
  2104
            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
jaroslav@1890
  2105
            w.pool.awaitBlocker(blocker);
jaroslav@1890
  2106
        }
jaroslav@1890
  2107
        else {
jaroslav@1890
  2108
            do {} while (!blocker.isReleasable() && !blocker.block());
jaroslav@1890
  2109
        }
jaroslav@1890
  2110
    }
jaroslav@1890
  2111
jaroslav@1890
  2112
    // AbstractExecutorService overrides.  These rely on undocumented
jaroslav@1890
  2113
    // fact that ForkJoinTask.adapt returns ForkJoinTasks that also
jaroslav@1890
  2114
    // implement RunnableFuture.
jaroslav@1890
  2115
jaroslav@1890
  2116
    protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
jaroslav@1890
  2117
        return (RunnableFuture<T>) ForkJoinTask.adapt(runnable, value);
jaroslav@1890
  2118
    }
jaroslav@1890
  2119
jaroslav@1890
  2120
    protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
jaroslav@1890
  2121
        return (RunnableFuture<T>) ForkJoinTask.adapt(callable);
jaroslav@1890
  2122
    }
jaroslav@1890
  2123
jaroslav@1890
  2124
    // Unsafe mechanics
jaroslav@1896
  2125
    private static final Unsafe UNSAFE;
jaroslav@1890
  2126
    private static final long ctlOffset;
jaroslav@1890
  2127
    private static final long stealCountOffset;
jaroslav@1890
  2128
    private static final long blockedCountOffset;
jaroslav@1890
  2129
    private static final long quiescerCountOffset;
jaroslav@1890
  2130
    private static final long scanGuardOffset;
jaroslav@1890
  2131
    private static final long nextWorkerNumberOffset;
jaroslav@1890
  2132
    private static final long ABASE;
jaroslav@1890
  2133
    private static final int ASHIFT;
jaroslav@1890
  2134
jaroslav@1890
  2135
    static {
jaroslav@1890
  2136
        poolNumberGenerator = new AtomicInteger();
jaroslav@1890
  2137
        workerSeedGenerator = new Random();
jaroslav@1890
  2138
        defaultForkJoinWorkerThreadFactory =
jaroslav@1890
  2139
            new DefaultForkJoinWorkerThreadFactory();
jaroslav@1890
  2140
        int s;
jaroslav@1890
  2141
        try {
jaroslav@1896
  2142
            UNSAFE = Unsafe.getUnsafe();
jaroslav@1890
  2143
            Class k = ForkJoinPool.class;
jaroslav@1890
  2144
            ctlOffset = UNSAFE.objectFieldOffset
jaroslav@1890
  2145
                (k.getDeclaredField("ctl"));
jaroslav@1890
  2146
            stealCountOffset = UNSAFE.objectFieldOffset
jaroslav@1890
  2147
                (k.getDeclaredField("stealCount"));
jaroslav@1890
  2148
            blockedCountOffset = UNSAFE.objectFieldOffset
jaroslav@1890
  2149
                (k.getDeclaredField("blockedCount"));
jaroslav@1890
  2150
            quiescerCountOffset = UNSAFE.objectFieldOffset
jaroslav@1890
  2151
                (k.getDeclaredField("quiescerCount"));
jaroslav@1890
  2152
            scanGuardOffset = UNSAFE.objectFieldOffset
jaroslav@1890
  2153
                (k.getDeclaredField("scanGuard"));
jaroslav@1890
  2154
            nextWorkerNumberOffset = UNSAFE.objectFieldOffset
jaroslav@1890
  2155
                (k.getDeclaredField("nextWorkerNumber"));
jaroslav@1890
  2156
            Class a = ForkJoinTask[].class;
jaroslav@1890
  2157
            ABASE = UNSAFE.arrayBaseOffset(a);
jaroslav@1890
  2158
            s = UNSAFE.arrayIndexScale(a);
jaroslav@1890
  2159
        } catch (Exception e) {
jaroslav@1890
  2160
            throw new Error(e);
jaroslav@1890
  2161
        }
jaroslav@1890
  2162
        if ((s & (s-1)) != 0)
jaroslav@1890
  2163
            throw new Error("data type scale not a power of two");
jaroslav@1890
  2164
        ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
jaroslav@1890
  2165
    }
jaroslav@1890
  2166
jaroslav@1890
  2167
}