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