1771N/A/*
1771N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
1771N/A *
1771N/A * This code is free software; you can redistribute it and/or modify it
1771N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
1771N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
1771N/A *
1771N/A * This code is distributed in the hope that it will be useful, but WITHOUT
1771N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
1771N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
1771N/A * version 2 for more details (a copy is included in the LICENSE file that
1771N/A * accompanied this code).
1771N/A *
1771N/A * You should have received a copy of the GNU General Public License version
1771N/A * 2 along with this work; if not, write to the Free Software Foundation,
1771N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
1771N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
1771N/A */
1771N/A
1771N/A/*
1771N/A * This file is available under and governed by the GNU General Public
1771N/A * License version 2 only, as published by the Free Software Foundation.
1771N/A * However, the following notice accompanied the original version of this
1771N/A * file:
1771N/A *
1771N/A * Written by Doug Lea with assistance from members of JCP JSR-166
1771N/A * Expert Group and released to the public domain, as explained at
3984N/A * http://creativecommons.org/publicdomain/zero/1.0/
1771N/A */
1771N/A
1771N/Apackage java.util.concurrent;
1771N/A
1771N/Aimport java.util.ArrayList;
1771N/Aimport java.util.Arrays;
1771N/Aimport java.util.Collection;
1771N/Aimport java.util.Collections;
1771N/Aimport java.util.List;
3736N/Aimport java.util.Random;
2754N/Aimport java.util.concurrent.AbstractExecutorService;
2754N/Aimport java.util.concurrent.Callable;
2754N/Aimport java.util.concurrent.ExecutorService;
2754N/Aimport java.util.concurrent.Future;
2754N/Aimport java.util.concurrent.RejectedExecutionException;
2754N/Aimport java.util.concurrent.RunnableFuture;
2754N/Aimport java.util.concurrent.TimeUnit;
2754N/Aimport java.util.concurrent.TimeoutException;
2754N/Aimport java.util.concurrent.atomic.AtomicInteger;
1771N/Aimport java.util.concurrent.locks.LockSupport;
1771N/Aimport java.util.concurrent.locks.ReentrantLock;
3736N/Aimport java.util.concurrent.locks.Condition;
1771N/A
1771N/A/**
1771N/A * An {@link ExecutorService} for running {@link ForkJoinTask}s.
1771N/A * A {@code ForkJoinPool} provides the entry point for submissions
2754N/A * from non-{@code ForkJoinTask} clients, as well as management and
1771N/A * monitoring operations.
1771N/A *
1771N/A * <p>A {@code ForkJoinPool} differs from other kinds of {@link
1771N/A * ExecutorService} mainly by virtue of employing
1771N/A * <em>work-stealing</em>: all threads in the pool attempt to find and
1771N/A * execute subtasks created by other active tasks (eventually blocking
1771N/A * waiting for work if none exist). This enables efficient processing
1771N/A * when most tasks spawn other subtasks (as do most {@code
2754N/A * ForkJoinTask}s). When setting <em>asyncMode</em> to true in
2754N/A * constructors, {@code ForkJoinPool}s may also be appropriate for use
2754N/A * with event-style tasks that are never joined.
1771N/A *
1771N/A * <p>A {@code ForkJoinPool} is constructed with a given target
1771N/A * parallelism level; by default, equal to the number of available
2754N/A * processors. The pool attempts to maintain enough active (or
2754N/A * available) threads by dynamically adding, suspending, or resuming
2754N/A * internal worker threads, even if some tasks are stalled waiting to
2754N/A * join others. However, no such adjustments are guaranteed in the
2754N/A * face of blocked IO or other unmanaged synchronization. The nested
2754N/A * {@link ManagedBlocker} interface enables extension of the kinds of
2754N/A * synchronization accommodated.
1771N/A *
1771N/A * <p>In addition to execution and lifecycle control methods, this
1771N/A * class provides status check methods (for example
1771N/A * {@link #getStealCount}) that are intended to aid in developing,
1771N/A * tuning, and monitoring fork/join applications. Also, method
1771N/A * {@link #toString} returns indications of pool state in a
1771N/A * convenient form for informal monitoring.
1771N/A *
2754N/A * <p> As is the case with other ExecutorServices, there are three
2754N/A * main task execution methods summarized in the following
2754N/A * table. These are designed to be used by clients not already engaged
2754N/A * in fork/join computations in the current pool. The main forms of
2754N/A * these methods accept instances of {@code ForkJoinTask}, but
2754N/A * overloaded forms also allow mixed execution of plain {@code
2754N/A * Runnable}- or {@code Callable}- based activities as well. However,
2754N/A * tasks that are already executing in a pool should normally
2754N/A * <em>NOT</em> use these pool execution methods, but instead use the
2754N/A * within-computation forms listed in the table.
2754N/A *
2754N/A * <table BORDER CELLPADDING=3 CELLSPACING=1>
2754N/A * <tr>
2754N/A * <td></td>
2754N/A * <td ALIGN=CENTER> <b>Call from non-fork/join clients</b></td>
2754N/A * <td ALIGN=CENTER> <b>Call from within fork/join computations</b></td>
2754N/A * </tr>
2754N/A * <tr>
2754N/A * <td> <b>Arrange async execution</td>
2754N/A * <td> {@link #execute(ForkJoinTask)}</td>
2754N/A * <td> {@link ForkJoinTask#fork}</td>
2754N/A * </tr>
2754N/A * <tr>
2754N/A * <td> <b>Await and obtain result</td>
2754N/A * <td> {@link #invoke(ForkJoinTask)}</td>
2754N/A * <td> {@link ForkJoinTask#invoke}</td>
2754N/A * </tr>
2754N/A * <tr>
2754N/A * <td> <b>Arrange exec and obtain Future</td>
2754N/A * <td> {@link #submit(ForkJoinTask)}</td>
2754N/A * <td> {@link ForkJoinTask#fork} (ForkJoinTasks <em>are</em> Futures)</td>
2754N/A * </tr>
2754N/A * </table>
2754N/A *
1771N/A * <p><b>Sample Usage.</b> Normally a single {@code ForkJoinPool} is
1771N/A * used for all parallel task execution in a program or subsystem.
1771N/A * Otherwise, use would not usually outweigh the construction and
1771N/A * bookkeeping overhead of creating a large set of threads. For
1771N/A * example, a common pool could be used for the {@code SortTasks}
1771N/A * illustrated in {@link RecursiveAction}. Because {@code
1771N/A * ForkJoinPool} uses threads in {@linkplain java.lang.Thread#isDaemon
1771N/A * daemon} mode, there is typically no need to explicitly {@link
1771N/A * #shutdown} such a pool upon program exit.
1771N/A *
1771N/A * <pre>
1771N/A * static final ForkJoinPool mainPool = new ForkJoinPool();
1771N/A * ...
1771N/A * public void sort(long[] array) {
1771N/A * mainPool.invoke(new SortTask(array, 0, array.length));
1771N/A * }
1771N/A * </pre>
1771N/A *
1771N/A * <p><b>Implementation notes</b>: This implementation restricts the
1771N/A * maximum number of running threads to 32767. Attempts to create
1771N/A * pools with greater than the maximum number result in
1771N/A * {@code IllegalArgumentException}.
1771N/A *
1771N/A * <p>This implementation rejects submitted tasks (that is, by throwing
2754N/A * {@link RejectedExecutionException}) only when the pool is shut down
2754N/A * or internal resources have been exhausted.
1771N/A *
1771N/A * @since 1.7
1771N/A * @author Doug Lea
1771N/A */
1771N/Apublic class ForkJoinPool extends AbstractExecutorService {
1771N/A
1771N/A /*
2754N/A * Implementation Overview
2754N/A *
2754N/A * This class provides the central bookkeeping and control for a
2754N/A * set of worker threads: Submissions from non-FJ threads enter
2754N/A * into a submission queue. Workers take these tasks and typically
2754N/A * split them into subtasks that may be stolen by other workers.
3736N/A * Preference rules give first priority to processing tasks from
3736N/A * their own queues (LIFO or FIFO, depending on mode), then to
3736N/A * randomized FIFO steals of tasks in other worker queues, and
3736N/A * lastly to new submissions.
3736N/A *
3736N/A * The main throughput advantages of work-stealing stem from
3736N/A * decentralized control -- workers mostly take tasks from
3736N/A * themselves or each other. We cannot negate this in the
3736N/A * implementation of other management responsibilities. The main
3736N/A * tactic for avoiding bottlenecks is packing nearly all
3736N/A * essentially atomic control state into a single 64bit volatile
3736N/A * variable ("ctl"). This variable is read on the order of 10-100
3736N/A * times as often as it is modified (always via CAS). (There is
3736N/A * some additional control state, for example variable "shutdown"
3736N/A * for which we can cope with uncoordinated updates.) This
3736N/A * streamlines synchronization and control at the expense of messy
3736N/A * constructions needed to repack status bits upon updates.
3736N/A * Updates tend not to contend with each other except during
3736N/A * bursts while submitted tasks begin or end. In some cases when
3736N/A * they do contend, threads can instead do something else
3736N/A * (usually, scan for tasks) until contention subsides.
3736N/A *
3736N/A * To enable packing, we restrict maximum parallelism to (1<<15)-1
3736N/A * (which is far in excess of normal operating range) to allow
3736N/A * ids, counts, and their negations (used for thresholding) to fit
3736N/A * into 16bit fields.
3736N/A *
3736N/A * Recording Workers. Workers are recorded in the "workers" array
3736N/A * that is created upon pool construction and expanded if (rarely)
3736N/A * necessary. This is an array as opposed to some other data
3736N/A * structure to support index-based random steals by workers.
3736N/A * Updates to the array recording new workers and unrecording
3736N/A * terminated ones are protected from each other by a seqLock
3736N/A * (scanGuard) but the array is otherwise concurrently readable,
3736N/A * and accessed directly by workers. To simplify index-based
3736N/A * operations, the array size is always a power of two, and all
3736N/A * readers must tolerate null slots. To avoid flailing during
3736N/A * start-up, the array is presized to hold twice #parallelism
3736N/A * workers (which is unlikely to need further resizing during
3736N/A * execution). But to avoid dealing with so many null slots,
3736N/A * variable scanGuard includes a mask for the nearest power of two
3736N/A * that contains all current workers. All worker thread creation
3736N/A * is on-demand, triggered by task submissions, replacement of
3736N/A * terminated workers, and/or compensation for blocked
3736N/A * workers. However, all other support code is set up to work with
3736N/A * other policies. To ensure that we do not hold on to worker
3736N/A * references that would prevent GC, ALL accesses to workers are
3736N/A * via indices into the workers array (which is one source of some
3736N/A * of the messy code constructions here). In essence, the workers
3736N/A * array serves as a weak reference mechanism. Thus for example
3736N/A * the wait queue field of ctl stores worker indices, not worker
3736N/A * references. Access to the workers in associated methods (for
3736N/A * example signalWork) must both index-check and null-check the
3736N/A * IDs. All such accesses ignore bad IDs by returning out early
3736N/A * from what they are doing, since this can only be associated
3736N/A * with termination, in which case it is OK to give up.
2754N/A *
3736N/A * All uses of the workers array, as well as queue arrays, check
3736N/A * that the array is non-null (even if previously non-null). This
3736N/A * allows nulling during termination, which is currently not
3736N/A * necessary, but remains an option for resource-revocation-based
3736N/A * shutdown schemes.
3736N/A *
3736N/A * Wait Queuing. Unlike HPC work-stealing frameworks, we cannot
3736N/A * let workers spin indefinitely scanning for tasks when none can
3736N/A * be found immediately, and we cannot start/resume workers unless
3736N/A * there appear to be tasks available. On the other hand, we must
3736N/A * quickly prod them into action when new tasks are submitted or
3736N/A * generated. We park/unpark workers after placing in an event
3736N/A * wait queue when they cannot find work. This "queue" is actually
3736N/A * a simple Treiber stack, headed by the "id" field of ctl, plus a
3736N/A * 15bit counter value to both wake up waiters (by advancing their
3736N/A * count) and avoid ABA effects. Successors are held in worker
3736N/A * field "nextWait". Queuing deals with several intrinsic races,
3736N/A * mainly that a task-producing thread can miss seeing (and
3736N/A * signalling) another thread that gave up looking for work but
3736N/A * has not yet entered the wait queue. We solve this by requiring
3736N/A * a full sweep of all workers both before (in scan()) and after
3736N/A * (in tryAwaitWork()) a newly waiting worker is added to the wait
3736N/A * queue. During a rescan, the worker might release some other
3736N/A * queued worker rather than itself, which has the same net
3736N/A * effect. Because enqueued workers may actually be rescanning
3736N/A * rather than waiting, we set and clear the "parked" field of
3736N/A * ForkJoinWorkerThread to reduce unnecessary calls to unpark.
3736N/A * (Use of the parked field requires a secondary recheck to avoid
3736N/A * missed signals.)
3736N/A *
3736N/A * Signalling. We create or wake up workers only when there
3736N/A * appears to be at least one task they might be able to find and
3736N/A * execute. When a submission is added or another worker adds a
3736N/A * task to a queue that previously had two or fewer tasks, they
3736N/A * signal waiting workers (or trigger creation of new ones if
3736N/A * fewer than the given parallelism level -- see signalWork).
3736N/A * These primary signals are buttressed by signals during rescans
3736N/A * as well as those performed when a worker steals a task and
3736N/A * notices that there are more tasks too; together these cover the
3736N/A * signals needed in cases when more than two tasks are pushed
3736N/A * but untaken.
3736N/A *
3736N/A * Trimming workers. To release resources after periods of lack of
3736N/A * use, a worker starting to wait when the pool is quiescent will
3736N/A * time out and terminate if the pool has remained quiescent for
3736N/A * SHRINK_RATE nanosecs. This will slowly propagate, eventually
3736N/A * terminating all workers after long periods of non-use.
3736N/A *
3736N/A * Submissions. External submissions are maintained in an
3736N/A * array-based queue that is structured identically to
3736N/A * ForkJoinWorkerThread queues except for the use of
3736N/A * submissionLock in method addSubmission. Unlike the case for
3736N/A * worker queues, multiple external threads can add new
3736N/A * submissions, so adding requires a lock.
3736N/A *
3736N/A * Compensation. Beyond work-stealing support and lifecycle
3736N/A * control, the main responsibility of this framework is to take
3736N/A * actions when one worker is waiting to join a task stolen (or
3736N/A * always held by) another. Because we are multiplexing many
3736N/A * tasks on to a pool of workers, we can't just let them block (as
3736N/A * in Thread.join). We also cannot just reassign the joiner's
3736N/A * run-time stack with another and replace it later, which would
3736N/A * be a form of "continuation", that even if possible is not
3736N/A * necessarily a good idea since we sometimes need both an
3736N/A * unblocked task and its continuation to progress. Instead we
2754N/A * combine two tactics:
2754N/A *
2754N/A * Helping: Arranging for the joiner to execute some task that it
2754N/A * would be running if the steal had not occurred. Method
3736N/A * ForkJoinWorkerThread.joinTask tracks joining->stealing
2754N/A * links to try to find such a task.
2754N/A *
2754N/A * Compensating: Unless there are already enough live threads,
3736N/A * method tryPreBlock() may create or re-activate a spare
3736N/A * thread to compensate for blocked joiners until they
3736N/A * unblock.
2754N/A *
2754N/A * The ManagedBlocker extension API can't use helping so relies
2754N/A * only on compensation in method awaitBlocker.
2754N/A *
3736N/A * It is impossible to keep exactly the target parallelism number
3736N/A * of threads running at any given time. Determining the
3736N/A * existence of conservatively safe helping targets, the
3736N/A * availability of already-created spares, and the apparent need
3736N/A * to create new spares are all racy and require heuristic
3736N/A * guidance, so we rely on multiple retries of each. Currently,
3736N/A * in keeping with on-demand signalling policy, we compensate only
3736N/A * if blocking would leave less than one active (non-waiting,
3736N/A * non-blocked) worker. Additionally, to avoid some false alarms
3736N/A * due to GC, lagging counters, system activity, etc, compensated
3736N/A * blocking for joins is only attempted after rechecks stabilize
3736N/A * (retries are interspersed with Thread.yield, for good
3736N/A * citizenship). The variable blockedCount, incremented before
3736N/A * blocking and decremented after, is sometimes needed to
3736N/A * distinguish cases of waiting for work vs blocking on joins or
3736N/A * other managed sync. Both cases are equivalent for most pool
3736N/A * control, so we can update non-atomically. (Additionally,
3736N/A * contention on blockedCount alleviates some contention on ctl).
2754N/A *
3736N/A * Shutdown and Termination. A call to shutdownNow atomically sets
3736N/A * the ctl stop bit and then (non-atomically) sets each workers
3736N/A * "terminate" status, cancels all unprocessed tasks, and wakes up
3736N/A * all waiting workers. Detecting whether termination should
3736N/A * commence after a non-abrupt shutdown() call requires more work
3736N/A * and bookkeeping. We need consensus about quiesence (i.e., that
3736N/A * there is no more work) which is reflected in active counts so
3736N/A * long as there are no current blockers, as well as possible
3736N/A * re-evaluations during independent changes in blocking or
3736N/A * quiescing workers.
2754N/A *
3736N/A * Style notes: There is a lot of representation-level coupling
2754N/A * among classes ForkJoinPool, ForkJoinWorkerThread, and
3736N/A * ForkJoinTask. Most fields of ForkJoinWorkerThread maintain
3736N/A * data structures managed by ForkJoinPool, so are directly
3736N/A * accessed. Conversely we allow access to "workers" array by
2754N/A * workers, and direct access to ForkJoinTask.status by both
2754N/A * ForkJoinPool and ForkJoinWorkerThread. There is little point
2754N/A * trying to reduce this, since any associated future changes in
2754N/A * representations will need to be accompanied by algorithmic
3736N/A * changes anyway. All together, these low-level implementation
3736N/A * choices produce as much as a factor of 4 performance
3736N/A * improvement compared to naive implementations, and enable the
3736N/A * processing of billions of tasks per second, at the expense of
3736N/A * some ugliness.
2754N/A *
3736N/A * Methods signalWork() and scan() are the main bottlenecks so are
3736N/A * especially heavily micro-optimized/mangled. There are lots of
3736N/A * inline assignments (of form "while ((local = field) != 0)")
3736N/A * which are usually the simplest way to ensure the required read
3736N/A * orderings (which are sometimes critical). This leads to a
3736N/A * "C"-like style of listing declarations of these locals at the
3736N/A * heads of methods or blocks. There are several occurrences of
3736N/A * the unusual "do {} while (!cas...)" which is the simplest way
3736N/A * to force an update of a CAS'ed variable. There are also other
3736N/A * coding oddities that help some methods perform reasonably even
3736N/A * when interpreted (not compiled).
2754N/A *
3736N/A * The order of declarations in this file is: (1) declarations of
3736N/A * statics (2) fields (along with constants used when unpacking
3736N/A * some of them), listed in an order that tends to reduce
3736N/A * contention among them a bit under most JVMs. (3) internal
3736N/A * control methods (4) callbacks and other support for
3736N/A * ForkJoinTask and ForkJoinWorkerThread classes, (5) exported
3736N/A * methods (plus a few little helpers). (6) static block
3736N/A * initializing all statics in a minimally dependent order.
1771N/A */
1771N/A
1771N/A /**
1771N/A * Factory for creating new {@link ForkJoinWorkerThread}s.
1771N/A * A {@code ForkJoinWorkerThreadFactory} must be defined and used
1771N/A * for {@code ForkJoinWorkerThread} subclasses that extend base
1771N/A * functionality or initialize threads with different contexts.
1771N/A */
1771N/A public static interface ForkJoinWorkerThreadFactory {
1771N/A /**
1771N/A * Returns a new worker thread operating in the given pool.
1771N/A *
1771N/A * @param pool the pool this thread works in
1771N/A * @throws NullPointerException if the pool is null
1771N/A */
1771N/A public ForkJoinWorkerThread newThread(ForkJoinPool pool);
1771N/A }
1771N/A
1771N/A /**
1771N/A * Default ForkJoinWorkerThreadFactory implementation; creates a
1771N/A * new ForkJoinWorkerThread.
1771N/A */
2754N/A static class DefaultForkJoinWorkerThreadFactory
1771N/A implements ForkJoinWorkerThreadFactory {
1771N/A public ForkJoinWorkerThread newThread(ForkJoinPool pool) {
2754N/A return new ForkJoinWorkerThread(pool);
1771N/A }
1771N/A }
1771N/A
1771N/A /**
1771N/A * Creates a new ForkJoinWorkerThread. This factory is used unless
1771N/A * overridden in ForkJoinPool constructors.
1771N/A */
1771N/A public static final ForkJoinWorkerThreadFactory
3736N/A defaultForkJoinWorkerThreadFactory;
1771N/A
1771N/A /**
1771N/A * Permission required for callers of methods that may start or
1771N/A * kill threads.
1771N/A */
3736N/A private static final RuntimePermission modifyThreadPermission;
1771N/A
1771N/A /**
1771N/A * If there is a security manager, makes sure caller has
1771N/A * permission to modify threads.
1771N/A */
1771N/A private static void checkPermission() {
1771N/A SecurityManager security = System.getSecurityManager();
1771N/A if (security != null)
1771N/A security.checkPermission(modifyThreadPermission);
1771N/A }
1771N/A
1771N/A /**
1771N/A * Generator for assigning sequence numbers as pool names.
1771N/A */
3736N/A private static final AtomicInteger poolNumberGenerator;
1771N/A
1771N/A /**
3736N/A * Generator for initial random seeds for worker victim
3736N/A * selection. This is used only to create initial seeds. Random
3736N/A * steals use a cheaper xorshift generator per steal attempt. We
3736N/A * don't expect much contention on seedGenerator, so just use a
3736N/A * plain Random.
1771N/A */
3736N/A static final Random workerSeedGenerator;
1771N/A
1771N/A /**
3736N/A * Array holding all worker threads in the pool. Initialized upon
3736N/A * construction. Array size must be a power of two. Updates and
3736N/A * replacements are protected by scanGuard, but the array is
3736N/A * always kept in a consistent enough state to be randomly
3736N/A * accessed without locking by workers performing work-stealing,
3736N/A * as well as other traversal-based methods in this class, so long
3736N/A * as reads memory-acquire by first reading ctl. All readers must
3736N/A * tolerate that some array slots may be null.
1771N/A */
3736N/A ForkJoinWorkerThread[] workers;
1771N/A
1771N/A /**
3736N/A * Initial size for submission queue array. Must be a power of
3736N/A * two. In many applications, these always stay small so we use a
3736N/A * small initial cap.
1771N/A */
3736N/A private static final int INITIAL_QUEUE_CAPACITY = 8;
3736N/A
3736N/A /**
3736N/A * Maximum size for submission queue array. Must be a power of two
3736N/A * less than or equal to 1 << (31 - width of array entry) to
3736N/A * ensure lack of index wraparound, but is capped at a lower
3736N/A * value to help users trap runaway computations.
3736N/A */
3736N/A private static final int MAXIMUM_QUEUE_CAPACITY = 1 << 24; // 16M
1771N/A
1771N/A /**
3736N/A * Array serving as submission queue. Initialized upon construction.
1771N/A */
3736N/A private ForkJoinTask<?>[] submissionQueue;
1771N/A
1771N/A /**
3736N/A * Lock protecting submissions array for addSubmission
1771N/A */
3736N/A private final ReentrantLock submissionLock;
1771N/A
1771N/A /**
3736N/A * Condition for awaitTermination, using submissionLock for
3736N/A * convenience.
2754N/A */
3736N/A private final Condition termination;
2754N/A
2754N/A /**
2754N/A * Creation factory for worker threads.
2754N/A */
2754N/A private final ForkJoinWorkerThreadFactory factory;
2754N/A
2754N/A /**
3736N/A * The uncaught exception handler used when any worker abruptly
3736N/A * terminates.
3736N/A */
3736N/A final Thread.UncaughtExceptionHandler ueh;
3736N/A
3736N/A /**
3736N/A * Prefix for assigning names to worker threads
3736N/A */
3736N/A private final String workerNamePrefix;
3736N/A
3736N/A /**
2754N/A * Sum of per-thread steal counts, updated only when threads are
2754N/A * idle or terminating.
1771N/A */
2754N/A private volatile long stealCount;
2754N/A
2754N/A /**
3736N/A * Main pool control -- a long packed with:
3736N/A * AC: Number of active running workers minus target parallelism (16 bits)
3736N/A * TC: Number of total workers minus target parallelism (16bits)
3736N/A * ST: true if pool is terminating (1 bit)
3736N/A * EC: the wait count of top waiting thread (15 bits)
3736N/A * ID: ~poolIndex of top of Treiber stack of waiting threads (16 bits)
3736N/A *
3736N/A * When convenient, we can extract the upper 32 bits of counts and
3736N/A * the lower 32 bits of queue state, u = (int)(ctl >>> 32) and e =
3736N/A * (int)ctl. The ec field is never accessed alone, but always
3736N/A * together with id and st. The offsets of counts by the target
3736N/A * parallelism and the positionings of fields makes it possible to
3736N/A * perform the most common checks via sign tests of fields: When
3736N/A * ac is negative, there are not enough active workers, when tc is
3736N/A * negative, there are not enough total workers, when id is
3736N/A * negative, there is at least one waiting worker, and when e is
3736N/A * negative, the pool is terminating. To deal with these possibly
3736N/A * negative fields, we use casts in and out of "short" and/or
3736N/A * signed shifts to maintain signedness.
2754N/A */
3736N/A volatile long ctl;
1771N/A
3736N/A // bit positions/shifts for fields
3736N/A private static final int AC_SHIFT = 48;
3736N/A private static final int TC_SHIFT = 32;
3736N/A private static final int ST_SHIFT = 31;
3736N/A private static final int EC_SHIFT = 16;
3736N/A
3736N/A // bounds
3736N/A private static final int MAX_ID = 0x7fff; // max poolIndex
3736N/A private static final int SMASK = 0xffff; // mask short bits
3736N/A private static final int SHORT_SIGN = 1 << 15;
3736N/A private static final int INT_SIGN = 1 << 31;
2754N/A
3736N/A // masks
3736N/A private static final long STOP_BIT = 0x0001L << ST_SHIFT;
3736N/A private static final long AC_MASK = ((long)SMASK) << AC_SHIFT;
3736N/A private static final long TC_MASK = ((long)SMASK) << TC_SHIFT;
3736N/A
3736N/A // units for incrementing and decrementing
3736N/A private static final long TC_UNIT = 1L << TC_SHIFT;
3736N/A private static final long AC_UNIT = 1L << AC_SHIFT;
2754N/A
3736N/A // masks and units for dealing with u = (int)(ctl >>> 32)
3736N/A private static final int UAC_SHIFT = AC_SHIFT - 32;
3736N/A private static final int UTC_SHIFT = TC_SHIFT - 32;
3736N/A private static final int UAC_MASK = SMASK << UAC_SHIFT;
3736N/A private static final int UTC_MASK = SMASK << UTC_SHIFT;
3736N/A private static final int UAC_UNIT = 1 << UAC_SHIFT;
3736N/A private static final int UTC_UNIT = 1 << UTC_SHIFT;
2754N/A
3736N/A // masks and units for dealing with e = (int)ctl
3736N/A private static final int E_MASK = 0x7fffffff; // no STOP_BIT
3736N/A private static final int EC_UNIT = 1 << EC_SHIFT;
2754N/A
2754N/A /**
2754N/A * The target parallelism level.
2754N/A */
2754N/A final int parallelism;
2754N/A
2754N/A /**
3736N/A * Index (mod submission queue length) of next element to take
3736N/A * from submission queue. Usage is identical to that for
3736N/A * per-worker queues -- see ForkJoinWorkerThread internal
3736N/A * documentation.
3736N/A */
3736N/A volatile int queueBase;
3736N/A
3736N/A /**
3736N/A * Index (mod submission queue length) of next element to add
3736N/A * in submission queue. Usage is identical to that for
3736N/A * per-worker queues -- see ForkJoinWorkerThread internal
3736N/A * documentation.
3736N/A */
3736N/A int queueTop;
3736N/A
3736N/A /**
3736N/A * True when shutdown() has been called.
3736N/A */
3736N/A volatile boolean shutdown;
3736N/A
3736N/A /**
2754N/A * True if use local fifo, not default lifo, for local polling
2754N/A * Read by, and replicated by ForkJoinWorkerThreads
2754N/A */
2754N/A final boolean locallyFifo;
2754N/A
2754N/A /**
3736N/A * The number of threads in ForkJoinWorkerThreads.helpQuiescePool.
3736N/A * When non-zero, suppresses automatic shutdown when active
3736N/A * counts become zero.
3736N/A */
3736N/A volatile int quiescerCount;
3736N/A
3736N/A /**
3736N/A * The number of threads blocked in join.
3736N/A */
3736N/A volatile int blockedCount;
3736N/A
3736N/A /**
3736N/A * Counter for worker Thread names (unrelated to their poolIndex)
3736N/A */
3736N/A private volatile int nextWorkerNumber;
3736N/A
3736N/A /**
3736N/A * The index for the next created worker. Accessed under scanGuard.
2754N/A */
3736N/A private int nextWorkerIndex;
3736N/A
3736N/A /**
3736N/A * SeqLock and index masking for updates to workers array. Locked
3736N/A * when SG_UNIT is set. Unlocking clears bit by adding
3736N/A * SG_UNIT. Staleness of read-only operations can be checked by
3736N/A * comparing scanGuard to value before the reads. The low 16 bits
3736N/A * (i.e, anding with SMASK) hold (the smallest power of two
3736N/A * covering all worker indices, minus one, and is used to avoid
3736N/A * dealing with large numbers of null slots when the workers array
3736N/A * is overallocated.
3736N/A */
3736N/A volatile int scanGuard;
3736N/A
3736N/A private static final int SG_UNIT = 1 << 16;
3736N/A
3736N/A /**
3736N/A * The wakeup interval (in nanoseconds) for a worker waiting for a
3736N/A * task when the pool is quiescent to instead try to shrink the
3736N/A * number of workers. The exact value does not matter too
3736N/A * much. It must be short enough to release resources during
3736N/A * sustained periods of idleness, but not so short that threads
3736N/A * are continually re-created.
3736N/A */
3736N/A private static final long SHRINK_RATE =
3736N/A 4L * 1000L * 1000L * 1000L; // 4 seconds
1771N/A
1771N/A /**
3736N/A * Top-level loop for worker threads: On each step: if the
3736N/A * previous step swept through all queues and found no tasks, or
3736N/A * there are excess threads, then possibly blocks. Otherwise,
3736N/A * scans for and, if found, executes a task. Returns when pool
3736N/A * and/or worker terminate.
3736N/A *
3736N/A * @param w the worker
1771N/A */
3736N/A final void work(ForkJoinWorkerThread w) {
3736N/A boolean swept = false; // true on empty scans
3736N/A long c;
3736N/A while (!w.terminate && (int)(c = ctl) >= 0) {
3736N/A int a; // active count
3736N/A if (!swept && (a = (int)(c >> AC_SHIFT)) <= 0)
3736N/A swept = scan(w, a);
3736N/A else if (tryAwaitWork(w, c))
3736N/A swept = false;
3736N/A }
3736N/A }
1771N/A
3736N/A // Signalling
1771N/A
1771N/A /**
3736N/A * Wakes up or creates a worker.
1771N/A */
3736N/A final void signalWork() {
3736N/A /*
3736N/A * The while condition is true if: (there is are too few total
3736N/A * workers OR there is at least one waiter) AND (there are too
3736N/A * few active workers OR the pool is terminating). The value
3736N/A * of e distinguishes the remaining cases: zero (no waiters)
3736N/A * for create, negative if terminating (in which case do
3736N/A * nothing), else release a waiter. The secondary checks for
3736N/A * release (non-null array etc) can fail if the pool begins
3736N/A * terminating after the test, and don't impose any added cost
3736N/A * because JVMs must perform null and bounds checks anyway.
3736N/A */
3736N/A long c; int e, u;
3736N/A while ((((e = (int)(c = ctl)) | (u = (int)(c >>> 32))) &
3736N/A (INT_SIGN|SHORT_SIGN)) == (INT_SIGN|SHORT_SIGN) && e >= 0) {
3736N/A if (e > 0) { // release a waiting worker
3736N/A int i; ForkJoinWorkerThread w; ForkJoinWorkerThread[] ws;
3736N/A if ((ws = workers) == null ||
3736N/A (i = ~e & SMASK) >= ws.length ||
3736N/A (w = ws[i]) == null)
3736N/A break;
3736N/A long nc = (((long)(w.nextWait & E_MASK)) |
3736N/A ((long)(u + UAC_UNIT) << 32));
3736N/A if (w.eventCount == e &&
3736N/A UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc)) {
3736N/A w.eventCount = (e + EC_UNIT) & E_MASK;
3736N/A if (w.parked)
3736N/A UNSAFE.unpark(w);
3736N/A break;
3736N/A }
3736N/A }
3736N/A else if (UNSAFE.compareAndSwapLong
3736N/A (this, ctlOffset, c,
3736N/A (long)(((u + UTC_UNIT) & UTC_MASK) |
3736N/A ((u + UAC_UNIT) & UAC_MASK)) << 32)) {
3736N/A addWorker();
3736N/A break;
3736N/A }
3736N/A }
1771N/A }
1771N/A
1771N/A /**
3736N/A * Variant of signalWork to help release waiters on rescans.
3736N/A * Tries once to release a waiter if active count < 0.
3736N/A *
3736N/A * @return false if failed due to contention, else true
3736N/A */
3736N/A private boolean tryReleaseWaiter() {
3736N/A long c; int e, i; ForkJoinWorkerThread w; ForkJoinWorkerThread[] ws;
3736N/A if ((e = (int)(c = ctl)) > 0 &&
3736N/A (int)(c >> AC_SHIFT) < 0 &&
3736N/A (ws = workers) != null &&
3736N/A (i = ~e & SMASK) < ws.length &&
3736N/A (w = ws[i]) != null) {
3736N/A long nc = ((long)(w.nextWait & E_MASK) |
3736N/A ((c + AC_UNIT) & (AC_MASK|TC_MASK)));
3736N/A if (w.eventCount != e ||
3736N/A !UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc))
3736N/A return false;
3736N/A w.eventCount = (e + EC_UNIT) & E_MASK;
3736N/A if (w.parked)
3736N/A UNSAFE.unpark(w);
3736N/A }
3736N/A return true;
3736N/A }
3736N/A
3736N/A // Scanning for tasks
3736N/A
3736N/A /**
3736N/A * Scans for and, if found, executes one task. Scans start at a
3736N/A * random index of workers array, and randomly select the first
3736N/A * (2*#workers)-1 probes, and then, if all empty, resort to 2
3736N/A * circular sweeps, which is necessary to check quiescence. and
3736N/A * taking a submission only if no stealable tasks were found. The
3736N/A * steal code inside the loop is a specialized form of
3736N/A * ForkJoinWorkerThread.deqTask, followed bookkeeping to support
3736N/A * helpJoinTask and signal propagation. The code for submission
3736N/A * queues is almost identical. On each steal, the worker completes
3736N/A * not only the task, but also all local tasks that this task may
3736N/A * have generated. On detecting staleness or contention when
3736N/A * trying to take a task, this method returns without finishing
3736N/A * sweep, which allows global state rechecks before retry.
3736N/A *
3736N/A * @param w the worker
3736N/A * @param a the number of active workers
3736N/A * @return true if swept all queues without finding a task
3387N/A */
3736N/A private boolean scan(ForkJoinWorkerThread w, int a) {
3736N/A int g = scanGuard; // mask 0 avoids useless scans if only one active
3736N/A int m = (parallelism == 1 - a && blockedCount == 0) ? 0 : g & SMASK;
3736N/A ForkJoinWorkerThread[] ws = workers;
3736N/A if (ws == null || ws.length <= m) // staleness check
3736N/A return false;
3736N/A for (int r = w.seed, k = r, j = -(m + m); j <= m + m; ++j) {
3736N/A ForkJoinTask<?> t; ForkJoinTask<?>[] q; int b, i;
3736N/A ForkJoinWorkerThread v = ws[k & m];
3736N/A if (v != null && (b = v.queueBase) != v.queueTop &&
3736N/A (q = v.queue) != null && (i = (q.length - 1) & b) >= 0) {
3736N/A long u = (i << ASHIFT) + ABASE;
3736N/A if ((t = q[i]) != null && v.queueBase == b &&
3736N/A UNSAFE.compareAndSwapObject(q, u, t, null)) {
3736N/A int d = (v.queueBase = b + 1) - v.queueTop;
3736N/A v.stealHint = w.poolIndex;
3736N/A if (d != 0)
3736N/A signalWork(); // propagate if nonempty
3736N/A w.execTask(t);
3736N/A }
3736N/A r ^= r << 13; r ^= r >>> 17; w.seed = r ^ (r << 5);
3736N/A return false; // store next seed
3736N/A }
3736N/A else if (j < 0) { // xorshift
3736N/A r ^= r << 13; r ^= r >>> 17; k = r ^= r << 5;
3736N/A }
3736N/A else
3736N/A ++k;
3736N/A }
3736N/A if (scanGuard != g) // staleness check
3736N/A return false;
3736N/A else { // try to take submission
3736N/A ForkJoinTask<?> t; ForkJoinTask<?>[] q; int b, i;
3736N/A if ((b = queueBase) != queueTop &&
3736N/A (q = submissionQueue) != null &&
3736N/A (i = (q.length - 1) & b) >= 0) {
3736N/A long u = (i << ASHIFT) + ABASE;
3736N/A if ((t = q[i]) != null && queueBase == b &&
3736N/A UNSAFE.compareAndSwapObject(q, u, t, null)) {
3736N/A queueBase = b + 1;
3736N/A w.execTask(t);
3736N/A }
3736N/A return false;
3736N/A }
3736N/A return true; // all queues empty
3736N/A }
3387N/A }
3387N/A
3387N/A /**
3736N/A * Tries to enqueue worker w in wait queue and await change in
3989N/A * worker's eventCount. If the pool is quiescent and there is
3989N/A * more than one worker, possibly terminates worker upon exit.
3989N/A * Otherwise, before blocking, rescans queues to avoid missed
3989N/A * signals. Upon finding work, releases at least one worker
3989N/A * (which may be the current worker). Rescans restart upon
3989N/A * detected staleness or failure to release due to
3989N/A * contention. Note the unusual conventions about Thread.interrupt
3989N/A * here and elsewhere: Because interrupts are used solely to alert
3989N/A * threads to check termination, which is checked here anyway, we
3989N/A * clear status (using Thread.interrupted) before any call to
3989N/A * park, so that park does not immediately return due to status
3989N/A * being set via some other unrelated call to interrupt in user
3989N/A * code.
2754N/A *
3736N/A * @param w the calling worker
3736N/A * @param c the ctl value on entry
3736N/A * @return true if waited or another thread was released upon enq
1771N/A */
3736N/A private boolean tryAwaitWork(ForkJoinWorkerThread w, long c) {
3736N/A int v = w.eventCount;
3736N/A w.nextWait = (int)c; // w's successor record
3736N/A long nc = (long)(v & E_MASK) | ((c - AC_UNIT) & (AC_MASK|TC_MASK));
3736N/A if (ctl != c || !UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc)) {
3736N/A long d = ctl; // return true if lost to a deq, to force scan
3736N/A return (int)d != (int)c && ((d - c) & AC_MASK) >= 0L;
3736N/A }
3736N/A for (int sc = w.stealCount; sc != 0;) { // accumulate stealCount
3736N/A long s = stealCount;
3736N/A if (UNSAFE.compareAndSwapLong(this, stealCountOffset, s, s + sc))
3736N/A sc = w.stealCount = 0;
3736N/A else if (w.eventCount != v)
3736N/A return true; // update next time
3736N/A }
4020N/A if ((!shutdown || !tryTerminate(false)) &&
4020N/A (int)c != 0 && parallelism + (int)(nc >> AC_SHIFT) == 0 &&
3736N/A blockedCount == 0 && quiescerCount == 0)
3736N/A idleAwaitWork(w, nc, c, v); // quiescent
3736N/A for (boolean rescanned = false;;) {
3736N/A if (w.eventCount != v)
3736N/A return true;
3736N/A if (!rescanned) {
3736N/A int g = scanGuard, m = g & SMASK;
3736N/A ForkJoinWorkerThread[] ws = workers;
3736N/A if (ws != null && m < ws.length) {
3736N/A rescanned = true;
3736N/A for (int i = 0; i <= m; ++i) {
3736N/A ForkJoinWorkerThread u = ws[i];
3736N/A if (u != null) {
3736N/A if (u.queueBase != u.queueTop &&
3736N/A !tryReleaseWaiter())
3736N/A rescanned = false; // contended
3736N/A if (w.eventCount != v)
3736N/A return true;
3736N/A }
3736N/A }
3736N/A }
3736N/A if (scanGuard != g || // stale
3736N/A (queueBase != queueTop && !tryReleaseWaiter()))
3736N/A rescanned = false;
3736N/A if (!rescanned)
3736N/A Thread.yield(); // reduce contention
3736N/A else
3736N/A Thread.interrupted(); // clear before park
2754N/A }
3736N/A else {
3736N/A w.parked = true; // must recheck
3736N/A if (w.eventCount != v) {
3736N/A w.parked = false;
3736N/A return true;
3736N/A }
3736N/A LockSupport.park(this);
3736N/A rescanned = w.parked = false;
3736N/A }
2754N/A }
1771N/A }
1771N/A
1771N/A /**
3736N/A * If inactivating worker w has caused pool to become
3736N/A * quiescent, check for pool termination, and wait for event
3736N/A * for up to SHRINK_RATE nanosecs (rescans are unnecessary in
3736N/A * this case because quiescence reflects consensus about lack
3736N/A * of work). On timeout, if ctl has not changed, terminate the
3736N/A * worker. Upon its termination (see deregisterWorker), it may
3736N/A * wake up another worker to possibly repeat this process.
3736N/A *
3736N/A * @param w the calling worker
3736N/A * @param currentCtl the ctl value after enqueuing w
3736N/A * @param prevCtl the ctl value if w terminated
3736N/A * @param v the eventCount w awaits change
1771N/A */
3736N/A private void idleAwaitWork(ForkJoinWorkerThread w, long currentCtl,
3736N/A long prevCtl, int v) {
3736N/A if (w.eventCount == v) {
3736N/A if (shutdown)
3736N/A tryTerminate(false);
3736N/A ForkJoinTask.helpExpungeStaleExceptions(); // help clean weak refs
3736N/A while (ctl == currentCtl) {
3736N/A long startTime = System.nanoTime();
3736N/A w.parked = true;
3736N/A if (w.eventCount == v) // must recheck
3736N/A LockSupport.parkNanos(this, SHRINK_RATE);
3736N/A w.parked = false;
3736N/A if (w.eventCount != v)
3736N/A break;
3989N/A else if (System.nanoTime() - startTime <
3989N/A SHRINK_RATE - (SHRINK_RATE / 10)) // timing slop
3736N/A Thread.interrupted(); // spurious wakeup
3736N/A else if (UNSAFE.compareAndSwapLong(this, ctlOffset,
3736N/A currentCtl, prevCtl)) {
3736N/A w.terminate = true; // restore previous
3736N/A w.eventCount = ((int)currentCtl + EC_UNIT) & E_MASK;
3736N/A break;
3736N/A }
3736N/A }
3736N/A }
2754N/A }
2754N/A
3736N/A // Submissions
3736N/A
2754N/A /**
3736N/A * Enqueues the given task in the submissionQueue. Same idea as
3736N/A * ForkJoinWorkerThread.pushTask except for use of submissionLock.
3736N/A *
3736N/A * @param t the task
2754N/A */
3736N/A private void addSubmission(ForkJoinTask<?> t) {
3736N/A final ReentrantLock lock = this.submissionLock;
3736N/A lock.lock();
3736N/A try {
3736N/A ForkJoinTask<?>[] q; int s, m;
3736N/A if ((q = submissionQueue) != null) { // ignore if queue removed
3736N/A long u = (((s = queueTop) & (m = q.length-1)) << ASHIFT)+ABASE;
3736N/A UNSAFE.putOrderedObject(q, u, t);
3736N/A queueTop = s + 1;
3736N/A if (s - queueBase == m)
3736N/A growSubmissionQueue();
3736N/A }
3736N/A } finally {
3736N/A lock.unlock();
3736N/A }
3736N/A signalWork();
3736N/A }
3736N/A
3736N/A // (pollSubmission is defined below with exported methods)
3736N/A
3736N/A /**
3736N/A * Creates or doubles submissionQueue array.
3736N/A * Basically identical to ForkJoinWorkerThread version.
3736N/A */
3736N/A private void growSubmissionQueue() {
3736N/A ForkJoinTask<?>[] oldQ = submissionQueue;
3736N/A int size = oldQ != null ? oldQ.length << 1 : INITIAL_QUEUE_CAPACITY;
3736N/A if (size > MAXIMUM_QUEUE_CAPACITY)
3736N/A throw new RejectedExecutionException("Queue capacity exceeded");
3736N/A if (size < INITIAL_QUEUE_CAPACITY)
3736N/A size = INITIAL_QUEUE_CAPACITY;
3736N/A ForkJoinTask<?>[] q = submissionQueue = new ForkJoinTask<?>[size];
3736N/A int mask = size - 1;
3736N/A int top = queueTop;
3736N/A int oldMask;
3736N/A if (oldQ != null && (oldMask = oldQ.length - 1) >= 0) {
3736N/A for (int b = queueBase; b != top; ++b) {
3736N/A long u = ((b & oldMask) << ASHIFT) + ABASE;
3736N/A Object x = UNSAFE.getObjectVolatile(oldQ, u);
3736N/A if (x != null && UNSAFE.compareAndSwapObject(oldQ, u, x, null))
3736N/A UNSAFE.putObjectVolatile
3736N/A (q, ((b & mask) << ASHIFT) + ABASE, x);
3736N/A }
2754N/A }
2754N/A }
2754N/A
3736N/A // Blocking support
2754N/A
2754N/A /**
3736N/A * Tries to increment blockedCount, decrement active count
3736N/A * (sometimes implicitly) and possibly release or create a
3736N/A * compensating worker in preparation for blocking. Fails
3736N/A * on contention or termination.
3736N/A *
3736N/A * @return true if the caller can block, else should recheck and retry
2754N/A */
3736N/A private boolean tryPreBlock() {
3736N/A int b = blockedCount;
3736N/A if (UNSAFE.compareAndSwapInt(this, blockedCountOffset, b, b + 1)) {
3736N/A int pc = parallelism;
3736N/A do {
3736N/A ForkJoinWorkerThread[] ws; ForkJoinWorkerThread w;
3736N/A int e, ac, tc, rc, i;
3736N/A long c = ctl;
3736N/A int u = (int)(c >>> 32);
3736N/A if ((e = (int)c) < 0) {
3736N/A // skip -- terminating
3736N/A }
3736N/A else if ((ac = (u >> UAC_SHIFT)) <= 0 && e != 0 &&
3736N/A (ws = workers) != null &&
3736N/A (i = ~e & SMASK) < ws.length &&
3736N/A (w = ws[i]) != null) {
3736N/A long nc = ((long)(w.nextWait & E_MASK) |
3736N/A (c & (AC_MASK|TC_MASK)));
3736N/A if (w.eventCount == e &&
3736N/A UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc)) {
3736N/A w.eventCount = (e + EC_UNIT) & E_MASK;
3736N/A if (w.parked)
3736N/A UNSAFE.unpark(w);
3736N/A return true; // release an idle worker
3736N/A }
3736N/A }
3736N/A else if ((tc = (short)(u >>> UTC_SHIFT)) >= 0 && ac + pc > 1) {
3736N/A long nc = ((c - AC_UNIT) & AC_MASK) | (c & ~AC_MASK);
3736N/A if (UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc))
3736N/A return true; // no compensation needed
3736N/A }
3736N/A else if (tc + pc < MAX_ID) {
3736N/A long nc = ((c + TC_UNIT) & TC_MASK) | (c & ~TC_MASK);
3736N/A if (UNSAFE.compareAndSwapLong(this, ctlOffset, c, nc)) {
3736N/A addWorker();
3736N/A return true; // create a replacement
3736N/A }
3736N/A }
3736N/A // try to back out on any failure and let caller retry
3736N/A } while (!UNSAFE.compareAndSwapInt(this, blockedCountOffset,
3736N/A b = blockedCount, b - 1));
3736N/A }
3736N/A return false;
3736N/A }
3736N/A
3736N/A /**
3736N/A * Decrements blockedCount and increments active count
3736N/A */
3736N/A private void postBlock() {
3736N/A long c;
3736N/A do {} while (!UNSAFE.compareAndSwapLong(this, ctlOffset, // no mask
3736N/A c = ctl, c + AC_UNIT));
3736N/A int b;
4020N/A do {} while (!UNSAFE.compareAndSwapInt(this, blockedCountOffset,
4020N/A b = blockedCount, b - 1));
3736N/A }
3736N/A
3736N/A /**
3736N/A * Possibly blocks waiting for the given task to complete, or
3736N/A * cancels the task if terminating. Fails to wait if contended.
3736N/A *
3736N/A * @param joinMe the task
3736N/A */
3736N/A final void tryAwaitJoin(ForkJoinTask<?> joinMe) {
3736N/A int s;
3736N/A Thread.interrupted(); // clear interrupts before checking termination
3736N/A if (joinMe.status >= 0) {
3736N/A if (tryPreBlock()) {
3736N/A joinMe.tryAwaitDone(0L);
3736N/A postBlock();
2754N/A }
3736N/A else if ((ctl & STOP_BIT) != 0L)
3736N/A joinMe.cancelIgnoringExceptions();
2754N/A }
2754N/A }
2754N/A
2754N/A /**
3736N/A * Possibly blocks the given worker waiting for joinMe to
3736N/A * complete or timeout
3736N/A *
3736N/A * @param joinMe the task
3736N/A * @param millis the wait time for underlying Object.wait
3736N/A */
3736N/A final void timedAwaitJoin(ForkJoinTask<?> joinMe, long nanos) {
3736N/A while (joinMe.status >= 0) {
3736N/A Thread.interrupted();
3736N/A if ((ctl & STOP_BIT) != 0L) {
3736N/A joinMe.cancelIgnoringExceptions();
3736N/A break;
3736N/A }
3736N/A if (tryPreBlock()) {
3736N/A long last = System.nanoTime();
3736N/A while (joinMe.status >= 0) {
3736N/A long millis = TimeUnit.NANOSECONDS.toMillis(nanos);
3736N/A if (millis <= 0)
3736N/A break;
3736N/A joinMe.tryAwaitDone(millis);
3736N/A if (joinMe.status < 0)
3736N/A break;
3736N/A if ((ctl & STOP_BIT) != 0L) {
3736N/A joinMe.cancelIgnoringExceptions();
3736N/A break;
3736N/A }
3736N/A long now = System.nanoTime();
3736N/A nanos -= now - last;
3736N/A last = now;
3736N/A }
3736N/A postBlock();
3736N/A break;
3736N/A }
3736N/A }
3736N/A }
3736N/A
3736N/A /**
3736N/A * If necessary, compensates for blocker, and blocks
3736N/A */
3736N/A private void awaitBlocker(ManagedBlocker blocker)
3736N/A throws InterruptedException {
3736N/A while (!blocker.isReleasable()) {
3736N/A if (tryPreBlock()) {
3736N/A try {
3736N/A do {} while (!blocker.isReleasable() && !blocker.block());
3736N/A } finally {
3736N/A postBlock();
3736N/A }
3736N/A break;
3736N/A }
3736N/A }
3736N/A }
3736N/A
3736N/A // Creating, registering and deregistring workers
3736N/A
3736N/A /**
3736N/A * Tries to create and start a worker; minimally rolls back counts
3736N/A * on failure.
2754N/A */
3736N/A private void addWorker() {
3736N/A Throwable ex = null;
3736N/A ForkJoinWorkerThread t = null;
2754N/A try {
3736N/A t = factory.newThread(this);
3736N/A } catch (Throwable e) {
3736N/A ex = e;
3736N/A }
3736N/A if (t == null) { // null or exceptional factory return
3736N/A long c; // adjust counts
3736N/A do {} while (!UNSAFE.compareAndSwapLong
3736N/A (this, ctlOffset, c = ctl,
3736N/A (((c - AC_UNIT) & AC_MASK) |
3736N/A ((c - TC_UNIT) & TC_MASK) |
3736N/A (c & ~(AC_MASK|TC_MASK)))));
3736N/A // Propagate exception if originating from an external caller
3736N/A if (!tryTerminate(false) && ex != null &&
3736N/A !(Thread.currentThread() instanceof ForkJoinWorkerThread))
3736N/A UNSAFE.throwException(ex);
3736N/A }
3736N/A else
3736N/A t.start();
3736N/A }
3736N/A
3736N/A /**
3736N/A * Callback from ForkJoinWorkerThread constructor to assign a
3736N/A * public name
3736N/A */
3736N/A final String nextWorkerName() {
3736N/A for (int n;;) {
3736N/A if (UNSAFE.compareAndSwapInt(this, nextWorkerNumberOffset,
3736N/A n = nextWorkerNumber, ++n))
3736N/A return workerNamePrefix + n;
3736N/A }
3736N/A }
3736N/A
3736N/A /**
3736N/A * Callback from ForkJoinWorkerThread constructor to
3736N/A * determine its poolIndex and record in workers array.
3736N/A *
3736N/A * @param w the worker
3736N/A * @return the worker's pool index
3736N/A */
3736N/A final int registerWorker(ForkJoinWorkerThread w) {
3736N/A /*
3736N/A * In the typical case, a new worker acquires the lock, uses
3736N/A * next available index and returns quickly. Since we should
3736N/A * not block callers (ultimately from signalWork or
3736N/A * tryPreBlock) waiting for the lock needed to do this, we
3736N/A * instead help release other workers while waiting for the
3736N/A * lock.
3736N/A */
3736N/A for (int g;;) {
3736N/A ForkJoinWorkerThread[] ws;
3736N/A if (((g = scanGuard) & SG_UNIT) == 0 &&
3736N/A UNSAFE.compareAndSwapInt(this, scanGuardOffset,
3736N/A g, g | SG_UNIT)) {
3736N/A int k = nextWorkerIndex;
3736N/A try {
3736N/A if ((ws = workers) != null) { // ignore on shutdown
3736N/A int n = ws.length;
3736N/A if (k < 0 || k >= n || ws[k] != null) {
3736N/A for (k = 0; k < n && ws[k] != null; ++k)
3736N/A ;
3736N/A if (k == n)
3736N/A ws = workers = Arrays.copyOf(ws, n << 1);
3736N/A }
3736N/A ws[k] = w;
3736N/A nextWorkerIndex = k + 1;
3736N/A int m = g & SMASK;
4020N/A g = (k > m) ? ((m << 1) + 1) & SMASK : g + (SG_UNIT<<1);
3736N/A }
3736N/A } finally {
3736N/A scanGuard = g;
3736N/A }
3736N/A return k;
3736N/A }
3736N/A else if ((ws = workers) != null) { // help release others
3736N/A for (ForkJoinWorkerThread u : ws) {
3736N/A if (u != null && u.queueBase != u.queueTop) {
3736N/A if (tryReleaseWaiter())
3736N/A break;
3736N/A }
3736N/A }
3736N/A }
2754N/A }
2754N/A }
2754N/A
2754N/A /**
2754N/A * Final callback from terminating worker. Removes record of
2754N/A * worker from array, and adjusts counts. If pool is shutting
2754N/A * down, tries to complete termination.
2754N/A *
2754N/A * @param w the worker
2754N/A */
3736N/A final void deregisterWorker(ForkJoinWorkerThread w, Throwable ex) {
3736N/A int idx = w.poolIndex;
3736N/A int sc = w.stealCount;
3736N/A int steps = 0;
3736N/A // Remove from array, adjust worker counts and collect steal count.
3736N/A // We can intermix failed removes or adjusts with steal updates
3736N/A do {
3736N/A long s, c;
3736N/A int g;
3736N/A if (steps == 0 && ((g = scanGuard) & SG_UNIT) == 0 &&
3736N/A UNSAFE.compareAndSwapInt(this, scanGuardOffset,
3736N/A g, g |= SG_UNIT)) {
3736N/A ForkJoinWorkerThread[] ws = workers;
3736N/A if (ws != null && idx >= 0 &&
3736N/A idx < ws.length && ws[idx] == w)
3736N/A ws[idx] = null; // verify
3736N/A nextWorkerIndex = idx;
3736N/A scanGuard = g + SG_UNIT;
3736N/A steps = 1;
2754N/A }
3736N/A if (steps == 1 &&
3736N/A UNSAFE.compareAndSwapLong(this, ctlOffset, c = ctl,
3736N/A (((c - AC_UNIT) & AC_MASK) |
3736N/A ((c - TC_UNIT) & TC_MASK) |
3736N/A (c & ~(AC_MASK|TC_MASK)))))
3736N/A steps = 2;
3736N/A if (sc != 0 &&
3736N/A UNSAFE.compareAndSwapLong(this, stealCountOffset,
3736N/A s = stealCount, s + sc))
3736N/A sc = 0;
3736N/A } while (steps != 2 || sc != 0);
3736N/A if (!tryTerminate(false)) {
3736N/A if (ex != null) // possibly replace if died abnormally
3736N/A signalWork();
3736N/A else
3736N/A tryReleaseWaiter();
2754N/A }
2754N/A }
2754N/A
3736N/A // Shutdown and termination
2754N/A
2754N/A /**
2754N/A * Possibly initiates and/or completes termination.
2754N/A *
2754N/A * @param now if true, unconditionally terminate, else only
2754N/A * if shutdown and empty queue and no active workers
2754N/A * @return true if now terminating or terminated
2754N/A */
2754N/A private boolean tryTerminate(boolean now) {
3736N/A long c;
3736N/A while (((c = ctl) & STOP_BIT) == 0) {
3736N/A if (!now) {
3736N/A if ((int)(c >> AC_SHIFT) != -parallelism)
3736N/A return false;
3736N/A if (!shutdown || blockedCount != 0 || quiescerCount != 0 ||
3736N/A queueBase != queueTop) {
3736N/A if (ctl == c) // staleness check
3736N/A return false;
3736N/A continue;
3736N/A }
3736N/A }
3736N/A if (UNSAFE.compareAndSwapLong(this, ctlOffset, c, c | STOP_BIT))
3736N/A startTerminating();
3736N/A }
3736N/A if ((short)(c >>> TC_SHIFT) == -parallelism) { // signal when 0 workers
3736N/A final ReentrantLock lock = this.submissionLock;
3736N/A lock.lock();
3736N/A try {
3736N/A termination.signalAll();
3736N/A } finally {
3736N/A lock.unlock();
3736N/A }
2754N/A }
1771N/A return true;
1771N/A }
1771N/A
1771N/A /**
3736N/A * Runs up to three passes through workers: (0) Setting
3736N/A * termination status for each worker, followed by wakeups up to
3736N/A * queued workers; (1) helping cancel tasks; (2) interrupting
3736N/A * lagging threads (likely in external tasks, but possibly also
3736N/A * blocked in joins). Each pass repeats previous steps because of
3736N/A * potential lagging thread creation.
1771N/A */
2754N/A private void startTerminating() {
2754N/A cancelSubmissions();
3736N/A for (int pass = 0; pass < 3; ++pass) {
3736N/A ForkJoinWorkerThread[] ws = workers;
3736N/A if (ws != null) {
3736N/A for (ForkJoinWorkerThread w : ws) {
3736N/A if (w != null) {
3736N/A w.terminate = true;
3736N/A if (pass > 0) {
3736N/A w.cancelTasks();
3736N/A if (pass > 1 && !w.isInterrupted()) {
3736N/A try {
3736N/A w.interrupt();
3736N/A } catch (SecurityException ignore) {
3736N/A }
2754N/A }
2754N/A }
2754N/A }
2754N/A }
3736N/A terminateWaiters();
3736N/A }
3736N/A }
3736N/A }
3736N/A
3736N/A /**
3736N/A * Polls and cancels all submissions. Called only during termination.
3736N/A */
3736N/A private void cancelSubmissions() {
3736N/A while (queueBase != queueTop) {
3736N/A ForkJoinTask<?> task = pollSubmission();
3736N/A if (task != null) {
3736N/A try {
3736N/A task.cancel(false);
3736N/A } catch (Throwable ignore) {
3736N/A }
2754N/A }
1771N/A }
1771N/A }
1771N/A
1771N/A /**
3736N/A * Tries to set the termination status of waiting workers, and
3736N/A * then wakes them up (after which they will terminate).
2754N/A */
3736N/A private void terminateWaiters() {
3736N/A ForkJoinWorkerThread[] ws = workers;
3736N/A if (ws != null) {
3736N/A ForkJoinWorkerThread w; long c; int i, e;
3736N/A int n = ws.length;
3736N/A while ((i = ~(e = (int)(c = ctl)) & SMASK) < n &&
3736N/A (w = ws[i]) != null && w.eventCount == (e & E_MASK)) {
3736N/A if (UNSAFE.compareAndSwapLong(this, ctlOffset, c,
3736N/A (long)(w.nextWait & E_MASK) |
3736N/A ((c + AC_UNIT) & AC_MASK) |
3736N/A (c & (TC_MASK|STOP_BIT)))) {
3736N/A w.terminate = true;
3736N/A w.eventCount = e + EC_UNIT;
3736N/A if (w.parked)
3736N/A UNSAFE.unpark(w);
3736N/A }
2754N/A }
2754N/A }
2754N/A }
2754N/A
3736N/A // misc ForkJoinWorkerThread support
2754N/A
2754N/A /**
3736N/A * Increment or decrement quiescerCount. Needed only to prevent
3736N/A * triggering shutdown if a worker is transiently inactive while
3736N/A * checking quiescence.
3736N/A *
3736N/A * @param delta 1 for increment, -1 for decrement
2754N/A */
3736N/A final void addQuiescerCount(int delta) {
3736N/A int c;
4020N/A do {} while (!UNSAFE.compareAndSwapInt(this, quiescerCountOffset,
4020N/A c = quiescerCount, c + delta));
2754N/A }
2754N/A
2754N/A /**
3736N/A * Directly increment or decrement active count without
3736N/A * queuing. This method is used to transiently assert inactivation
3736N/A * while checking quiescence.
2754N/A *
3736N/A * @param delta 1 for increment, -1 for decrement
1771N/A */
3736N/A final void addActiveCount(int delta) {
3736N/A long d = delta < 0 ? -AC_UNIT : AC_UNIT;
3736N/A long c;
3736N/A do {} while (!UNSAFE.compareAndSwapLong(this, ctlOffset, c = ctl,
3736N/A ((c + d) & AC_MASK) |
3736N/A (c & ~AC_MASK)));
2754N/A }
2754N/A
2754N/A /**
2754N/A * Returns the approximate (non-atomic) number of idle threads per
2754N/A * active thread.
2754N/A */
2754N/A final int idlePerActive() {
3736N/A // Approximate at powers of two for small values, saturate past 4
3736N/A int p = parallelism;
3736N/A int a = p + (int)(ctl >> AC_SHIFT);
3736N/A return (a > (p >>>= 1) ? 0 :
3736N/A a > (p >>>= 1) ? 1 :
3736N/A a > (p >>>= 1) ? 2 :
3736N/A a > (p >>>= 1) ? 4 :
3736N/A 8);
2754N/A }
2754N/A
3736N/A // Exported methods
1771N/A
1771N/A // Constructors
1771N/A
1771N/A /**
1771N/A * Creates a {@code ForkJoinPool} with parallelism equal to {@link
2754N/A * java.lang.Runtime#availableProcessors}, using the {@linkplain
2754N/A * #defaultForkJoinWorkerThreadFactory default thread factory},
2754N/A * no UncaughtExceptionHandler, and non-async LIFO processing mode.
1771N/A *
1771N/A * @throws SecurityException if a security manager exists and
1771N/A * the caller is not permitted to modify threads
1771N/A * because it does not hold {@link
1771N/A * java.lang.RuntimePermission}{@code ("modifyThread")}
1771N/A */
1771N/A public ForkJoinPool() {
1771N/A this(Runtime.getRuntime().availableProcessors(),
2754N/A defaultForkJoinWorkerThreadFactory, null, false);
1771N/A }
1771N/A
1771N/A /**
1771N/A * Creates a {@code ForkJoinPool} with the indicated parallelism
2754N/A * level, the {@linkplain
2754N/A * #defaultForkJoinWorkerThreadFactory default thread factory},
2754N/A * no UncaughtExceptionHandler, and non-async LIFO processing mode.
1771N/A *
1771N/A * @param parallelism the parallelism level
1771N/A * @throws IllegalArgumentException if parallelism less than or
1771N/A * equal to zero, or greater than implementation limit
1771N/A * @throws SecurityException if a security manager exists and
1771N/A * the caller is not permitted to modify threads
1771N/A * because it does not hold {@link
1771N/A * java.lang.RuntimePermission}{@code ("modifyThread")}
1771N/A */
1771N/A public ForkJoinPool(int parallelism) {
2754N/A this(parallelism, defaultForkJoinWorkerThreadFactory, null, false);
1771N/A }
1771N/A
1771N/A /**
2754N/A * Creates a {@code ForkJoinPool} with the given parameters.
1771N/A *
2754N/A * @param parallelism the parallelism level. For default value,
2754N/A * use {@link java.lang.Runtime#availableProcessors}.
2754N/A * @param factory the factory for creating new threads. For default value,
2754N/A * use {@link #defaultForkJoinWorkerThreadFactory}.
2754N/A * @param handler the handler for internal worker threads that
2754N/A * terminate due to unrecoverable errors encountered while executing
2754N/A * tasks. For default value, use {@code null}.
2754N/A * @param asyncMode if true,
2754N/A * establishes local first-in-first-out scheduling mode for forked
2754N/A * tasks that are never joined. This mode may be more appropriate
2754N/A * than default locally stack-based mode in applications in which
2754N/A * worker threads only process event-style asynchronous tasks.
2754N/A * For default value, use {@code false}.
1771N/A * @throws IllegalArgumentException if parallelism less than or
1771N/A * equal to zero, or greater than implementation limit
1771N/A * @throws NullPointerException if the factory is null
1771N/A * @throws SecurityException if a security manager exists and
1771N/A * the caller is not permitted to modify threads
1771N/A * because it does not hold {@link
1771N/A * java.lang.RuntimePermission}{@code ("modifyThread")}
1771N/A */
2754N/A public ForkJoinPool(int parallelism,
2754N/A ForkJoinWorkerThreadFactory factory,
2754N/A Thread.UncaughtExceptionHandler handler,
2754N/A boolean asyncMode) {
2754N/A checkPermission();
1771N/A if (factory == null)
1771N/A throw new NullPointerException();
3736N/A if (parallelism <= 0 || parallelism > MAX_ID)
2754N/A throw new IllegalArgumentException();
1771N/A this.parallelism = parallelism;
2754N/A this.factory = factory;
2754N/A this.ueh = handler;
2754N/A this.locallyFifo = asyncMode;
3736N/A long np = (long)(-parallelism); // offset ctl counts
3736N/A this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
3736N/A this.submissionQueue = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY];
3736N/A // initialize workers array with room for 2*parallelism if possible
3736N/A int n = parallelism << 1;
3736N/A if (n >= MAX_ID)
3736N/A n = MAX_ID;
3736N/A else { // See Hackers Delight, sec 3.2, where n < (1 << 16)
3736N/A n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8;
3736N/A }
3736N/A workers = new ForkJoinWorkerThread[n + 1];
3736N/A this.submissionLock = new ReentrantLock();
3736N/A this.termination = submissionLock.newCondition();
3736N/A StringBuilder sb = new StringBuilder("ForkJoinPool-");
3736N/A sb.append(poolNumberGenerator.incrementAndGet());
3736N/A sb.append("-worker-");
3736N/A this.workerNamePrefix = sb.toString();
1771N/A }
1771N/A
1771N/A // Execution methods
1771N/A
1771N/A /**
1771N/A * Performs the given task, returning its result upon completion.
3736N/A * If the computation encounters an unchecked Exception or Error,
3736N/A * it is rethrown as the outcome of this invocation. Rethrown
3736N/A * exceptions behave in the same way as regular exceptions, but,
3736N/A * when possible, contain stack traces (as displayed for example
3736N/A * using {@code ex.printStackTrace()}) of both the current thread
3736N/A * as well as the thread actually encountering the exception;
3736N/A * minimally only the latter.
1771N/A *
1771N/A * @param task the task
1771N/A * @return the task's result
1771N/A * @throws NullPointerException if the task is null
1771N/A * @throws RejectedExecutionException if the task cannot be
1771N/A * scheduled for execution
1771N/A */
1771N/A public <T> T invoke(ForkJoinTask<T> task) {
3736N/A Thread t = Thread.currentThread();
3387N/A if (task == null)
3387N/A throw new NullPointerException();
3736N/A if (shutdown)
3387N/A throw new RejectedExecutionException();
3387N/A if ((t instanceof ForkJoinWorkerThread) &&
3387N/A ((ForkJoinWorkerThread)t).pool == this)
3387N/A return task.invoke(); // bypass submit if in same pool
3387N/A else {
3736N/A addSubmission(task);
3387N/A return task.join();
3387N/A }
3387N/A }
3387N/A
3387N/A /**
3387N/A * Unless terminating, forks task if within an ongoing FJ
3387N/A * computation in the current pool, else submits as external task.
3387N/A */
3387N/A private <T> void forkOrSubmit(ForkJoinTask<T> task) {
3736N/A ForkJoinWorkerThread w;
3736N/A Thread t = Thread.currentThread();
3736N/A if (shutdown)
3387N/A throw new RejectedExecutionException();
3387N/A if ((t instanceof ForkJoinWorkerThread) &&
3736N/A (w = (ForkJoinWorkerThread)t).pool == this)
3736N/A w.pushTask(task);
3387N/A else
3736N/A addSubmission(task);
1771N/A }
1771N/A
1771N/A /**
1771N/A * Arranges for (asynchronous) execution of the given task.
1771N/A *
1771N/A * @param task the task
1771N/A * @throws NullPointerException if the task is null
1771N/A * @throws RejectedExecutionException if the task cannot be
1771N/A * scheduled for execution
1771N/A */
1771N/A public void execute(ForkJoinTask<?> task) {
3387N/A if (task == null)
3387N/A throw new NullPointerException();
3387N/A forkOrSubmit(task);
1771N/A }
1771N/A
1771N/A // AbstractExecutorService methods
1771N/A
1771N/A /**
1771N/A * @throws NullPointerException if the task is null
1771N/A * @throws RejectedExecutionException if the task cannot be
1771N/A * scheduled for execution
1771N/A */
1771N/A public void execute(Runnable task) {
3387N/A if (task == null)
3387N/A throw new NullPointerException();
1771N/A ForkJoinTask<?> job;
1771N/A if (task instanceof ForkJoinTask<?>) // avoid re-wrap
1771N/A job = (ForkJoinTask<?>) task;
1771N/A else
1771N/A job = ForkJoinTask.adapt(task, null);
3387N/A forkOrSubmit(job);
1771N/A }
1771N/A
1771N/A /**
2754N/A * Submits a ForkJoinTask for execution.
2754N/A *
2754N/A * @param task the task to submit
2754N/A * @return the task
2754N/A * @throws NullPointerException if the task is null
2754N/A * @throws RejectedExecutionException if the task cannot be
2754N/A * scheduled for execution
2754N/A */
2754N/A public <T> ForkJoinTask<T> submit(ForkJoinTask<T> task) {
3387N/A if (task == null)
3387N/A throw new NullPointerException();
3387N/A forkOrSubmit(task);
2754N/A return task;
2754N/A }
2754N/A
2754N/A /**
1771N/A * @throws NullPointerException if the task is null
1771N/A * @throws RejectedExecutionException if the task cannot be
1771N/A * scheduled for execution
1771N/A */
1771N/A public <T> ForkJoinTask<T> submit(Callable<T> task) {
3387N/A if (task == null)
3387N/A throw new NullPointerException();
1771N/A ForkJoinTask<T> job = ForkJoinTask.adapt(task);
3387N/A forkOrSubmit(job);
1771N/A return job;
1771N/A }
1771N/A
1771N/A /**
1771N/A * @throws NullPointerException if the task is null
1771N/A * @throws RejectedExecutionException if the task cannot be
1771N/A * scheduled for execution
1771N/A */
1771N/A public <T> ForkJoinTask<T> submit(Runnable task, T result) {
3387N/A if (task == null)
3387N/A throw new NullPointerException();
1771N/A ForkJoinTask<T> job = ForkJoinTask.adapt(task, result);
3387N/A forkOrSubmit(job);
1771N/A return job;
1771N/A }
1771N/A
1771N/A /**
1771N/A * @throws NullPointerException if the task is null
1771N/A * @throws RejectedExecutionException if the task cannot be
1771N/A * scheduled for execution
1771N/A */
1771N/A public ForkJoinTask<?> submit(Runnable task) {
3387N/A if (task == null)
3387N/A throw new NullPointerException();
1771N/A ForkJoinTask<?> job;
1771N/A if (task instanceof ForkJoinTask<?>) // avoid re-wrap
1771N/A job = (ForkJoinTask<?>) task;
1771N/A else
1771N/A job = ForkJoinTask.adapt(task, null);
3387N/A forkOrSubmit(job);
1771N/A return job;
1771N/A }
1771N/A
1771N/A /**
1771N/A * @throws NullPointerException {@inheritDoc}
1771N/A * @throws RejectedExecutionException {@inheritDoc}
1771N/A */
1771N/A public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
1771N/A ArrayList<ForkJoinTask<T>> forkJoinTasks =
1771N/A new ArrayList<ForkJoinTask<T>>(tasks.size());
1771N/A for (Callable<T> task : tasks)
1771N/A forkJoinTasks.add(ForkJoinTask.adapt(task));
1771N/A invoke(new InvokeAll<T>(forkJoinTasks));
1771N/A
1771N/A @SuppressWarnings({"unchecked", "rawtypes"})
2754N/A List<Future<T>> futures = (List<Future<T>>) (List) forkJoinTasks;
1771N/A return futures;
1771N/A }
1771N/A
1771N/A static final class InvokeAll<T> extends RecursiveAction {
1771N/A final ArrayList<ForkJoinTask<T>> tasks;
1771N/A InvokeAll(ArrayList<ForkJoinTask<T>> tasks) { this.tasks = tasks; }
1771N/A public void compute() {
1771N/A try { invokeAll(tasks); }
1771N/A catch (Exception ignore) {}
1771N/A }
1771N/A private static final long serialVersionUID = -7914297376763021607L;
1771N/A }
1771N/A
1771N/A /**
1771N/A * Returns the factory used for constructing new workers.
1771N/A *
1771N/A * @return the factory used for constructing new workers
1771N/A */
1771N/A public ForkJoinWorkerThreadFactory getFactory() {
1771N/A return factory;
1771N/A }
1771N/A
1771N/A /**
1771N/A * Returns the handler for internal worker threads that terminate
1771N/A * due to unrecoverable errors encountered while executing tasks.
1771N/A *
1771N/A * @return the handler, or {@code null} if none
1771N/A */
1771N/A public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() {
2754N/A return ueh;
1771N/A }
1771N/A
1771N/A /**
1771N/A * Returns the targeted parallelism level of this pool.
1771N/A *
1771N/A * @return the targeted parallelism level of this pool
1771N/A */
1771N/A public int getParallelism() {
1771N/A return parallelism;
1771N/A }
1771N/A
1771N/A /**
1771N/A * Returns the number of worker threads that have started but not
2754N/A * yet terminated. The result returned by this method may differ
1771N/A * from {@link #getParallelism} when threads are created to
1771N/A * maintain parallelism when others are cooperatively blocked.
1771N/A *
1771N/A * @return the number of worker threads
1771N/A */
1771N/A public int getPoolSize() {
3736N/A return parallelism + (short)(ctl >>> TC_SHIFT);
1771N/A }
1771N/A
1771N/A /**
1771N/A * Returns {@code true} if this pool uses local first-in-first-out
1771N/A * scheduling mode for forked tasks that are never joined.
1771N/A *
1771N/A * @return {@code true} if this pool uses async mode
1771N/A */
1771N/A public boolean getAsyncMode() {
1771N/A return locallyFifo;
1771N/A }
1771N/A
1771N/A /**
1771N/A * Returns an estimate of the number of worker threads that are
1771N/A * not blocked waiting to join tasks or for other managed
2754N/A * synchronization. This method may overestimate the
2754N/A * number of running threads.
1771N/A *
1771N/A * @return the number of worker threads
1771N/A */
1771N/A public int getRunningThreadCount() {
3736N/A int r = parallelism + (int)(ctl >> AC_SHIFT);
4020N/A return (r <= 0) ? 0 : r; // suppress momentarily negative values
1771N/A }
1771N/A
1771N/A /**
1771N/A * Returns an estimate of the number of threads that are currently
1771N/A * stealing or executing tasks. This method may overestimate the
1771N/A * number of active threads.
1771N/A *
1771N/A * @return the number of active threads
1771N/A */
1771N/A public int getActiveThreadCount() {
3736N/A int r = parallelism + (int)(ctl >> AC_SHIFT) + blockedCount;
4020N/A return (r <= 0) ? 0 : r; // suppress momentarily negative values
1771N/A }
1771N/A
1771N/A /**
1771N/A * Returns {@code true} if all worker threads are currently idle.
1771N/A * An idle worker is one that cannot obtain a task to execute
1771N/A * because none are available to steal from other threads, and
1771N/A * there are no pending submissions to the pool. This method is
1771N/A * conservative; it might not return {@code true} immediately upon
1771N/A * idleness of all threads, but will eventually become true if
1771N/A * threads remain inactive.
1771N/A *
1771N/A * @return {@code true} if all threads are currently idle
1771N/A */
1771N/A public boolean isQuiescent() {
3736N/A return parallelism + (int)(ctl >> AC_SHIFT) + blockedCount == 0;
1771N/A }
1771N/A
1771N/A /**
1771N/A * Returns an estimate of the total number of tasks stolen from
1771N/A * one thread's work queue by another. The reported value
1771N/A * underestimates the actual total number of steals when the pool
1771N/A * is not quiescent. This value may be useful for monitoring and
1771N/A * tuning fork/join programs: in general, steal counts should be
1771N/A * high enough to keep threads busy, but low enough to avoid
1771N/A * overhead and contention across threads.
1771N/A *
1771N/A * @return the number of steals
1771N/A */
1771N/A public long getStealCount() {
2754N/A return stealCount;
1771N/A }
1771N/A
1771N/A /**
1771N/A * Returns an estimate of the total number of tasks currently held
1771N/A * in queues by worker threads (but not including tasks submitted
1771N/A * to the pool that have not begun executing). This value is only
1771N/A * an approximation, obtained by iterating across all threads in
1771N/A * the pool. This method may be useful for tuning task
1771N/A * granularities.
1771N/A *
1771N/A * @return the number of queued tasks
1771N/A */
1771N/A public long getQueuedTaskCount() {
1771N/A long count = 0;
3736N/A ForkJoinWorkerThread[] ws;
3736N/A if ((short)(ctl >>> TC_SHIFT) > -parallelism &&
3736N/A (ws = workers) != null) {
3736N/A for (ForkJoinWorkerThread w : ws)
3736N/A if (w != null)
3736N/A count -= w.queueBase - w.queueTop; // must read base first
3736N/A }
1771N/A return count;
1771N/A }
1771N/A
1771N/A /**
1771N/A * Returns an estimate of the number of tasks submitted to this
3736N/A * pool that have not yet begun executing. This method may take
3736N/A * time proportional to the number of submissions.
1771N/A *
1771N/A * @return the number of queued submissions
1771N/A */
1771N/A public int getQueuedSubmissionCount() {
3736N/A return -queueBase + queueTop;
1771N/A }
1771N/A
1771N/A /**
1771N/A * Returns {@code true} if there are any tasks submitted to this
1771N/A * pool that have not yet begun executing.
1771N/A *
1771N/A * @return {@code true} if there are any queued submissions
1771N/A */
1771N/A public boolean hasQueuedSubmissions() {
3736N/A return queueBase != queueTop;
1771N/A }
1771N/A
1771N/A /**
1771N/A * Removes and returns the next unexecuted submission if one is
1771N/A * available. This method may be useful in extensions to this
1771N/A * class that re-assign work in systems with multiple pools.
1771N/A *
1771N/A * @return the next submission, or {@code null} if none
1771N/A */
1771N/A protected ForkJoinTask<?> pollSubmission() {
3736N/A ForkJoinTask<?> t; ForkJoinTask<?>[] q; int b, i;
3736N/A while ((b = queueBase) != queueTop &&
3736N/A (q = submissionQueue) != null &&
3736N/A (i = (q.length - 1) & b) >= 0) {
3736N/A long u = (i << ASHIFT) + ABASE;
3736N/A if ((t = q[i]) != null &&
3736N/A queueBase == b &&
3736N/A UNSAFE.compareAndSwapObject(q, u, t, null)) {
3736N/A queueBase = b + 1;
3736N/A return t;
3736N/A }
3736N/A }
3736N/A return null;
1771N/A }
1771N/A
1771N/A /**
1771N/A * Removes all available unexecuted submitted and forked tasks
1771N/A * from scheduling queues and adds them to the given collection,
1771N/A * without altering their execution status. These may include
1771N/A * artificially generated or wrapped tasks. This method is
1771N/A * designed to be invoked only when the pool is known to be
1771N/A * quiescent. Invocations at other times may not remove all
1771N/A * tasks. A failure encountered while attempting to add elements
1771N/A * to collection {@code c} may result in elements being in
1771N/A * neither, either or both collections when the associated
1771N/A * exception is thrown. The behavior of this operation is
1771N/A * undefined if the specified collection is modified while the
1771N/A * operation is in progress.
1771N/A *
1771N/A * @param c the collection to transfer elements into
1771N/A * @return the number of elements transferred
1771N/A */
1771N/A protected int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
3736N/A int count = 0;
3736N/A while (queueBase != queueTop) {
3736N/A ForkJoinTask<?> t = pollSubmission();
3736N/A if (t != null) {
3736N/A c.add(t);
3736N/A ++count;
3736N/A }
3736N/A }
3736N/A ForkJoinWorkerThread[] ws;
3736N/A if ((short)(ctl >>> TC_SHIFT) > -parallelism &&
3736N/A (ws = workers) != null) {
3736N/A for (ForkJoinWorkerThread w : ws)
3736N/A if (w != null)
3736N/A count += w.drainTasksTo(c);
3736N/A }
2754N/A return count;
1771N/A }
1771N/A
1771N/A /**
1771N/A * Returns a string identifying this pool, as well as its state,
1771N/A * including indications of run state, parallelism level, and
1771N/A * worker and task counts.
1771N/A *
1771N/A * @return a string identifying this pool, as well as its state
1771N/A */
1771N/A public String toString() {
1771N/A long st = getStealCount();
1771N/A long qt = getQueuedTaskCount();
1771N/A long qs = getQueuedSubmissionCount();
2754N/A int pc = parallelism;
3736N/A long c = ctl;
3736N/A int tc = pc + (short)(c >>> TC_SHIFT);
3736N/A int rc = pc + (int)(c >> AC_SHIFT);
3736N/A if (rc < 0) // ignore transient negative
3736N/A rc = 0;
3736N/A int ac = rc + blockedCount;
3736N/A String level;
3736N/A if ((c & STOP_BIT) != 0)
4020N/A level = (tc == 0) ? "Terminated" : "Terminating";
3736N/A else
4020N/A level = shutdown ? "Shutting down" : "Running";
1771N/A return super.toString() +
3736N/A "[" + level +
2754N/A ", parallelism = " + pc +
2754N/A ", size = " + tc +
2754N/A ", active = " + ac +
2754N/A ", running = " + rc +
1771N/A ", steals = " + st +
1771N/A ", tasks = " + qt +
1771N/A ", submissions = " + qs +
1771N/A "]";
1771N/A }
1771N/A
1771N/A /**
1771N/A * Initiates an orderly shutdown in which previously submitted
1771N/A * tasks are executed, but no new tasks will be accepted.
1771N/A * Invocation has no additional effect if already shut down.
1771N/A * Tasks that are in the process of being submitted concurrently
1771N/A * during the course of this method may or may not be rejected.
1771N/A *
1771N/A * @throws SecurityException if a security manager exists and
1771N/A * the caller is not permitted to modify threads
1771N/A * because it does not hold {@link
1771N/A * java.lang.RuntimePermission}{@code ("modifyThread")}
1771N/A */
1771N/A public void shutdown() {
1771N/A checkPermission();
3736N/A shutdown = true;
2754N/A tryTerminate(false);
1771N/A }
1771N/A
1771N/A /**
1771N/A * Attempts to cancel and/or stop all tasks, and reject all
1771N/A * subsequently submitted tasks. Tasks that are in the process of
1771N/A * being submitted or executed concurrently during the course of
1771N/A * this method may or may not be rejected. This method cancels
1771N/A * both existing and unexecuted tasks, in order to permit
1771N/A * termination in the presence of task dependencies. So the method
1771N/A * always returns an empty list (unlike the case for some other
1771N/A * Executors).
1771N/A *
1771N/A * @return an empty list
1771N/A * @throws SecurityException if a security manager exists and
1771N/A * the caller is not permitted to modify threads
1771N/A * because it does not hold {@link
1771N/A * java.lang.RuntimePermission}{@code ("modifyThread")}
1771N/A */
1771N/A public List<Runnable> shutdownNow() {
1771N/A checkPermission();
3736N/A shutdown = true;
2754N/A tryTerminate(true);
1771N/A return Collections.emptyList();
1771N/A }
1771N/A
1771N/A /**
1771N/A * Returns {@code true} if all tasks have completed following shut down.
1771N/A *
1771N/A * @return {@code true} if all tasks have completed following shut down
1771N/A */
1771N/A public boolean isTerminated() {
3736N/A long c = ctl;
3736N/A return ((c & STOP_BIT) != 0L &&
3736N/A (short)(c >>> TC_SHIFT) == -parallelism);
1771N/A }
1771N/A
1771N/A /**
1771N/A * Returns {@code true} if the process of termination has
1771N/A * commenced but not yet completed. This method may be useful for
1771N/A * debugging. A return of {@code true} reported a sufficient
1771N/A * period after shutdown may indicate that submitted tasks have
3387N/A * ignored or suppressed interruption, or are waiting for IO,
3387N/A * causing this executor not to properly terminate. (See the
3387N/A * advisory notes for class {@link ForkJoinTask} stating that
3387N/A * tasks should not normally entail blocking operations. But if
3387N/A * they do, they must abort them on interrupt.)
1771N/A *
1771N/A * @return {@code true} if terminating but not yet terminated
1771N/A */
1771N/A public boolean isTerminating() {
3736N/A long c = ctl;
3736N/A return ((c & STOP_BIT) != 0L &&
3736N/A (short)(c >>> TC_SHIFT) != -parallelism);
1771N/A }
1771N/A
1771N/A /**
2805N/A * Returns true if terminating or terminated. Used by ForkJoinWorkerThread.
2805N/A */
2805N/A final boolean isAtLeastTerminating() {
3736N/A return (ctl & STOP_BIT) != 0L;
2805N/A }
2805N/A
2805N/A /**
1771N/A * Returns {@code true} if this pool has been shut down.
1771N/A *
1771N/A * @return {@code true} if this pool has been shut down
1771N/A */
1771N/A public boolean isShutdown() {
3736N/A return shutdown;
1771N/A }
1771N/A
1771N/A /**
1771N/A * Blocks until all tasks have completed execution after a shutdown
1771N/A * request, or the timeout occurs, or the current thread is
1771N/A * interrupted, whichever happens first.
1771N/A *
1771N/A * @param timeout the maximum time to wait
1771N/A * @param unit the time unit of the timeout argument
1771N/A * @return {@code true} if this executor terminated and
1771N/A * {@code false} if the timeout elapsed before termination
1771N/A * @throws InterruptedException if interrupted while waiting
1771N/A */
1771N/A public boolean awaitTermination(long timeout, TimeUnit unit)
1771N/A throws InterruptedException {
3736N/A long nanos = unit.toNanos(timeout);
3736N/A final ReentrantLock lock = this.submissionLock;
3736N/A lock.lock();
1771N/A try {
3736N/A for (;;) {
3736N/A if (isTerminated())
3736N/A return true;
3736N/A if (nanos <= 0)
3736N/A return false;
3736N/A nanos = termination.awaitNanos(nanos);
3736N/A }
3736N/A } finally {
3736N/A lock.unlock();
1771N/A }
1771N/A }
1771N/A
1771N/A /**
1771N/A * Interface for extending managed parallelism for tasks running
1771N/A * in {@link ForkJoinPool}s.
1771N/A *
2754N/A * <p>A {@code ManagedBlocker} provides two methods. Method
2754N/A * {@code isReleasable} must return {@code true} if blocking is
2754N/A * not necessary. Method {@code block} blocks the current thread
2754N/A * if necessary (perhaps internally invoking {@code isReleasable}
3736N/A * before actually blocking). These actions are performed by any
3736N/A * thread invoking {@link ForkJoinPool#managedBlock}. The
3736N/A * unusual methods in this API accommodate synchronizers that may,
3736N/A * but don't usually, block for long periods. Similarly, they
3736N/A * allow more efficient internal handling of cases in which
3736N/A * additional workers may be, but usually are not, needed to
3736N/A * ensure sufficient parallelism. Toward this end,
3736N/A * implementations of method {@code isReleasable} must be amenable
3736N/A * to repeated invocation.
1771N/A *
1771N/A * <p>For example, here is a ManagedBlocker based on a
1771N/A * ReentrantLock:
1771N/A * <pre> {@code
1771N/A * class ManagedLocker implements ManagedBlocker {
1771N/A * final ReentrantLock lock;
1771N/A * boolean hasLock = false;
1771N/A * ManagedLocker(ReentrantLock lock) { this.lock = lock; }
1771N/A * public boolean block() {
1771N/A * if (!hasLock)
1771N/A * lock.lock();
1771N/A * return true;
1771N/A * }
1771N/A * public boolean isReleasable() {
1771N/A * return hasLock || (hasLock = lock.tryLock());
1771N/A * }
1771N/A * }}</pre>
2754N/A *
2754N/A * <p>Here is a class that possibly blocks waiting for an
2754N/A * item on a given queue:
2754N/A * <pre> {@code
2754N/A * class QueueTaker<E> implements ManagedBlocker {
2754N/A * final BlockingQueue<E> queue;
2754N/A * volatile E item = null;
2754N/A * QueueTaker(BlockingQueue<E> q) { this.queue = q; }
2754N/A * public boolean block() throws InterruptedException {
2754N/A * if (item == null)
2754N/A * item = queue.take();
2754N/A * return true;
2754N/A * }
2754N/A * public boolean isReleasable() {
2754N/A * return item != null || (item = queue.poll()) != null;
2754N/A * }
2754N/A * public E getItem() { // call after pool.managedBlock completes
2754N/A * return item;
2754N/A * }
2754N/A * }}</pre>
1771N/A */
1771N/A public static interface ManagedBlocker {
1771N/A /**
1771N/A * Possibly blocks the current thread, for example waiting for
1771N/A * a lock or condition.
1771N/A *
1771N/A * @return {@code true} if no additional blocking is necessary
1771N/A * (i.e., if isReleasable would return true)
1771N/A * @throws InterruptedException if interrupted while waiting
1771N/A * (the method is not required to do so, but is allowed to)
1771N/A */
1771N/A boolean block() throws InterruptedException;
1771N/A
1771N/A /**
1771N/A * Returns {@code true} if blocking is unnecessary.
1771N/A */
1771N/A boolean isReleasable();
1771N/A }
1771N/A
1771N/A /**
1771N/A * Blocks in accord with the given blocker. If the current thread
1771N/A * is a {@link ForkJoinWorkerThread}, this method possibly
1771N/A * arranges for a spare thread to be activated if necessary to
2754N/A * ensure sufficient parallelism while the current thread is blocked.
1771N/A *
1771N/A * <p>If the caller is not a {@link ForkJoinTask}, this method is
1771N/A * behaviorally equivalent to
1771N/A * <pre> {@code
1771N/A * while (!blocker.isReleasable())
1771N/A * if (blocker.block())
1771N/A * return;
1771N/A * }</pre>
1771N/A *
1771N/A * If the caller is a {@code ForkJoinTask}, then the pool may
1771N/A * first be expanded to ensure parallelism, and later adjusted.
1771N/A *
1771N/A * @param blocker the blocker
1771N/A * @throws InterruptedException if blocker.block did so
1771N/A */
2754N/A public static void managedBlock(ManagedBlocker blocker)
1771N/A throws InterruptedException {
1771N/A Thread t = Thread.currentThread();
2754N/A if (t instanceof ForkJoinWorkerThread) {
2754N/A ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
2754N/A w.pool.awaitBlocker(blocker);
1771N/A }
2754N/A else {
2754N/A do {} while (!blocker.isReleasable() && !blocker.block());
2754N/A }
1771N/A }
1771N/A
1771N/A // AbstractExecutorService overrides. These rely on undocumented
1771N/A // fact that ForkJoinTask.adapt returns ForkJoinTasks that also
1771N/A // implement RunnableFuture.
1771N/A
1771N/A protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
1771N/A return (RunnableFuture<T>) ForkJoinTask.adapt(runnable, value);
1771N/A }
1771N/A
1771N/A protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
1771N/A return (RunnableFuture<T>) ForkJoinTask.adapt(callable);
1771N/A }
1771N/A
1771N/A // Unsafe mechanics
3736N/A private static final sun.misc.Unsafe UNSAFE;
3736N/A private static final long ctlOffset;
3736N/A private static final long stealCountOffset;
3736N/A private static final long blockedCountOffset;
3736N/A private static final long quiescerCountOffset;
3736N/A private static final long scanGuardOffset;
3736N/A private static final long nextWorkerNumberOffset;
3736N/A private static final long ABASE;
3736N/A private static final int ASHIFT;
1771N/A
3736N/A static {
3736N/A poolNumberGenerator = new AtomicInteger();
3736N/A workerSeedGenerator = new Random();
3736N/A modifyThreadPermission = new RuntimePermission("modifyThread");
3736N/A defaultForkJoinWorkerThreadFactory =
3736N/A new DefaultForkJoinWorkerThreadFactory();
3736N/A int s;
3736N/A try {
3736N/A UNSAFE = sun.misc.Unsafe.getUnsafe();
3736N/A Class k = ForkJoinPool.class;
3736N/A ctlOffset = UNSAFE.objectFieldOffset
3736N/A (k.getDeclaredField("ctl"));
3736N/A stealCountOffset = UNSAFE.objectFieldOffset
3736N/A (k.getDeclaredField("stealCount"));
3736N/A blockedCountOffset = UNSAFE.objectFieldOffset
3736N/A (k.getDeclaredField("blockedCount"));
3736N/A quiescerCountOffset = UNSAFE.objectFieldOffset
3736N/A (k.getDeclaredField("quiescerCount"));
3736N/A scanGuardOffset = UNSAFE.objectFieldOffset
3736N/A (k.getDeclaredField("scanGuard"));
3736N/A nextWorkerNumberOffset = UNSAFE.objectFieldOffset
3736N/A (k.getDeclaredField("nextWorkerNumber"));
3736N/A Class a = ForkJoinTask[].class;
3736N/A ABASE = UNSAFE.arrayBaseOffset(a);
3736N/A s = UNSAFE.arrayIndexScale(a);
3736N/A } catch (Exception e) {
3736N/A throw new Error(e);
3736N/A }
3736N/A if ((s & (s-1)) != 0)
3736N/A throw new Error("data type scale not a power of two");
3736N/A ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
3736N/A }
1771N/A
1771N/A}