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: * jaroslav@1890: * jaroslav@1890: * jaroslav@1890: * jaroslav@1890: * jaroslav@1890: * jaroslav@1890: * jaroslav@1890: * jaroslav@1890: * jaroslav@1890: * jaroslav@1890: * jaroslav@1890: * jaroslav@1890: * jaroslav@1890: * jaroslav@1890: * jaroslav@1890: * jaroslav@1890: * jaroslav@1890: * jaroslav@1890: * jaroslav@1890: * jaroslav@1890: *
Call from non-fork/join clients Call from within fork/join computations
Arrange async execution {@link #execute(ForkJoinTask)} {@link ForkJoinTask#fork}
Await and obtain result {@link #invoke(ForkJoinTask)} {@link ForkJoinTask#invoke}
Arrange exec and obtain Future {@link #submit(ForkJoinTask)} {@link ForkJoinTask#fork} (ForkJoinTasks are Futures)
jaroslav@1890: * 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 T invoke(ForkJoinTask task) { jaroslav@1890: Thread t = Thread.currentThread(); jaroslav@1890: if (task == null) jaroslav@1890: throw new NullPointerException(); jaroslav@1890: if (shutdown) jaroslav@1890: throw new RejectedExecutionException(); jaroslav@1890: if ((t instanceof ForkJoinWorkerThread) && jaroslav@1890: ((ForkJoinWorkerThread)t).pool == this) jaroslav@1890: return task.invoke(); // bypass submit if in same pool jaroslav@1890: else { jaroslav@1890: addSubmission(task); jaroslav@1890: return task.join(); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Unless terminating, forks task if within an ongoing FJ jaroslav@1890: * computation in the current pool, else submits as external task. jaroslav@1890: */ jaroslav@1890: private void forkOrSubmit(ForkJoinTask task) { jaroslav@1890: ForkJoinWorkerThread w; jaroslav@1890: Thread t = Thread.currentThread(); jaroslav@1890: if (shutdown) jaroslav@1890: throw new RejectedExecutionException(); jaroslav@1890: if ((t instanceof ForkJoinWorkerThread) && jaroslav@1890: (w = (ForkJoinWorkerThread)t).pool == this) jaroslav@1890: w.pushTask(task); jaroslav@1890: else jaroslav@1890: addSubmission(task); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Arranges for (asynchronous) execution of the given task. jaroslav@1890: * jaroslav@1890: * @param task the task 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 void execute(ForkJoinTask task) { jaroslav@1890: if (task == null) jaroslav@1890: throw new NullPointerException(); jaroslav@1890: forkOrSubmit(task); jaroslav@1890: } jaroslav@1890: jaroslav@1890: // AbstractExecutorService methods jaroslav@1890: jaroslav@1890: /** 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 void execute(Runnable task) { jaroslav@1890: if (task == null) jaroslav@1890: throw new NullPointerException(); jaroslav@1890: ForkJoinTask job; jaroslav@1890: if (task instanceof ForkJoinTask) // avoid re-wrap jaroslav@1890: job = (ForkJoinTask) task; jaroslav@1890: else jaroslav@1890: job = ForkJoinTask.adapt(task, null); jaroslav@1890: forkOrSubmit(job); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Submits a ForkJoinTask for execution. jaroslav@1890: * jaroslav@1890: * @param task the task to submit jaroslav@1890: * @return the task 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 ForkJoinTask submit(ForkJoinTask task) { jaroslav@1890: if (task == null) jaroslav@1890: throw new NullPointerException(); jaroslav@1890: forkOrSubmit(task); jaroslav@1890: return task; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** 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 ForkJoinTask submit(Callable task) { jaroslav@1890: if (task == null) jaroslav@1890: throw new NullPointerException(); jaroslav@1890: ForkJoinTask job = ForkJoinTask.adapt(task); jaroslav@1890: forkOrSubmit(job); jaroslav@1890: return job; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** 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 ForkJoinTask submit(Runnable task, T result) { jaroslav@1890: if (task == null) jaroslav@1890: throw new NullPointerException(); jaroslav@1890: ForkJoinTask job = ForkJoinTask.adapt(task, result); jaroslav@1890: forkOrSubmit(job); jaroslav@1890: return job; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** 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 ForkJoinTask submit(Runnable task) { jaroslav@1890: if (task == null) jaroslav@1890: throw new NullPointerException(); jaroslav@1890: ForkJoinTask job; jaroslav@1890: if (task instanceof ForkJoinTask) // avoid re-wrap jaroslav@1890: job = (ForkJoinTask) task; jaroslav@1890: else jaroslav@1890: job = ForkJoinTask.adapt(task, null); jaroslav@1890: forkOrSubmit(job); jaroslav@1890: return job; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * @throws NullPointerException {@inheritDoc} jaroslav@1890: * @throws RejectedExecutionException {@inheritDoc} jaroslav@1890: */ jaroslav@1890: public List> invokeAll(Collection> tasks) { jaroslav@1890: ArrayList> forkJoinTasks = jaroslav@1890: new ArrayList>(tasks.size()); jaroslav@1890: for (Callable task : tasks) jaroslav@1890: forkJoinTasks.add(ForkJoinTask.adapt(task)); jaroslav@1890: invoke(new InvokeAll(forkJoinTasks)); jaroslav@1890: jaroslav@1890: @SuppressWarnings({"unchecked", "rawtypes"}) jaroslav@1890: List> futures = (List>) (List) forkJoinTasks; jaroslav@1890: return futures; jaroslav@1890: } jaroslav@1890: jaroslav@1890: static final class InvokeAll extends RecursiveAction { jaroslav@1890: final ArrayList> tasks; jaroslav@1890: InvokeAll(ArrayList> tasks) { this.tasks = tasks; } jaroslav@1890: public void compute() { jaroslav@1890: try { invokeAll(tasks); } jaroslav@1890: catch (Exception ignore) {} jaroslav@1890: } jaroslav@1890: private static final long serialVersionUID = -7914297376763021607L; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns the factory used for constructing new workers. jaroslav@1890: * jaroslav@1890: * @return the factory used for constructing new workers jaroslav@1890: */ jaroslav@1890: public ForkJoinWorkerThreadFactory getFactory() { jaroslav@1890: return factory; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns the handler for internal worker threads that terminate jaroslav@1890: * due to unrecoverable errors encountered while executing tasks. jaroslav@1890: * jaroslav@1890: * @return the handler, or {@code null} if none jaroslav@1890: */ jaroslav@1890: public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() { jaroslav@1890: return ueh; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns the targeted parallelism level of this pool. jaroslav@1890: * jaroslav@1890: * @return the targeted parallelism level of this pool jaroslav@1890: */ jaroslav@1890: public int getParallelism() { jaroslav@1890: return parallelism; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns the number of worker threads that have started but not jaroslav@1890: * yet terminated. The result returned by this method may differ jaroslav@1890: * from {@link #getParallelism} when threads are created to jaroslav@1890: * maintain parallelism when others are cooperatively blocked. jaroslav@1890: * jaroslav@1890: * @return the number of worker threads jaroslav@1890: */ jaroslav@1890: public int getPoolSize() { jaroslav@1890: return parallelism + (short)(ctl >>> TC_SHIFT); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns {@code true} if this pool uses local first-in-first-out jaroslav@1890: * scheduling mode for forked tasks that are never joined. jaroslav@1890: * jaroslav@1890: * @return {@code true} if this pool uses async mode jaroslav@1890: */ jaroslav@1890: public boolean getAsyncMode() { jaroslav@1890: return locallyFifo; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns an estimate of the number of worker threads that are jaroslav@1890: * not blocked waiting to join tasks or for other managed jaroslav@1890: * synchronization. This method may overestimate the jaroslav@1890: * number of running threads. jaroslav@1890: * jaroslav@1890: * @return the number of worker threads jaroslav@1890: */ jaroslav@1890: public int getRunningThreadCount() { jaroslav@1890: int r = parallelism + (int)(ctl >> AC_SHIFT); jaroslav@1890: return (r <= 0) ? 0 : r; // suppress momentarily negative values jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns an estimate of the number of threads that are currently jaroslav@1890: * stealing or executing tasks. This method may overestimate the jaroslav@1890: * number of active threads. jaroslav@1890: * jaroslav@1890: * @return the number of active threads jaroslav@1890: */ jaroslav@1890: public int getActiveThreadCount() { jaroslav@1890: int r = parallelism + (int)(ctl >> AC_SHIFT) + blockedCount; jaroslav@1890: return (r <= 0) ? 0 : r; // suppress momentarily negative values jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns {@code true} if all worker threads are currently idle. jaroslav@1890: * An idle worker is one that cannot obtain a task to execute jaroslav@1890: * because none are available to steal from other threads, and jaroslav@1890: * there are no pending submissions to the pool. This method is jaroslav@1890: * conservative; it might not return {@code true} immediately upon jaroslav@1890: * idleness of all threads, but will eventually become true if jaroslav@1890: * threads remain inactive. jaroslav@1890: * jaroslav@1890: * @return {@code true} if all threads are currently idle jaroslav@1890: */ jaroslav@1890: public boolean isQuiescent() { jaroslav@1890: return parallelism + (int)(ctl >> AC_SHIFT) + blockedCount == 0; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns an estimate of the total number of tasks stolen from jaroslav@1890: * one thread's work queue by another. The reported value jaroslav@1890: * underestimates the actual total number of steals when the pool jaroslav@1890: * is not quiescent. This value may be useful for monitoring and jaroslav@1890: * tuning fork/join programs: in general, steal counts should be jaroslav@1890: * high enough to keep threads busy, but low enough to avoid jaroslav@1890: * overhead and contention across threads. jaroslav@1890: * jaroslav@1890: * @return the number of steals jaroslav@1890: */ jaroslav@1890: public long getStealCount() { jaroslav@1890: return stealCount; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns an estimate of the total number of tasks currently held jaroslav@1890: * in queues by worker threads (but not including tasks submitted jaroslav@1890: * to the pool that have not begun executing). This value is only jaroslav@1890: * an approximation, obtained by iterating across all threads in jaroslav@1890: * the pool. This method may be useful for tuning task jaroslav@1890: * granularities. jaroslav@1890: * jaroslav@1890: * @return the number of queued tasks jaroslav@1890: */ jaroslav@1890: public long getQueuedTaskCount() { jaroslav@1890: long count = 0; jaroslav@1890: ForkJoinWorkerThread[] ws; jaroslav@1890: if ((short)(ctl >>> TC_SHIFT) > -parallelism && jaroslav@1890: (ws = workers) != null) { jaroslav@1890: for (ForkJoinWorkerThread w : ws) jaroslav@1890: if (w != null) jaroslav@1890: count -= w.queueBase - w.queueTop; // must read base first jaroslav@1890: } jaroslav@1890: return count; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns an estimate of the number of tasks submitted to this jaroslav@1890: * pool that have not yet begun executing. This method may take jaroslav@1890: * time proportional to the number of submissions. jaroslav@1890: * jaroslav@1890: * @return the number of queued submissions jaroslav@1890: */ jaroslav@1890: public int getQueuedSubmissionCount() { jaroslav@1890: return -queueBase + queueTop; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns {@code true} if there are any tasks submitted to this jaroslav@1890: * pool that have not yet begun executing. jaroslav@1890: * jaroslav@1890: * @return {@code true} if there are any queued submissions jaroslav@1890: */ jaroslav@1890: public boolean hasQueuedSubmissions() { jaroslav@1890: return queueBase != queueTop; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Removes and returns the next unexecuted submission if one is jaroslav@1890: * available. This method may be useful in extensions to this jaroslav@1890: * class that re-assign work in systems with multiple pools. jaroslav@1890: * jaroslav@1890: * @return the next submission, or {@code null} if none jaroslav@1890: */ jaroslav@1890: protected ForkJoinTask pollSubmission() { jaroslav@1890: ForkJoinTask t; ForkJoinTask[] q; int b, i; jaroslav@1890: while ((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 && jaroslav@1890: queueBase == b && jaroslav@1890: UNSAFE.compareAndSwapObject(q, u, t, null)) { jaroslav@1890: queueBase = b + 1; jaroslav@1890: return t; jaroslav@1890: } jaroslav@1890: } jaroslav@1890: return null; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Removes all available unexecuted submitted and forked tasks jaroslav@1890: * from scheduling queues and adds them to the given collection, jaroslav@1890: * without altering their execution status. These may include jaroslav@1890: * artificially generated or wrapped tasks. This method is jaroslav@1890: * designed to be invoked only when the pool is known to be jaroslav@1890: * quiescent. Invocations at other times may not remove all jaroslav@1890: * tasks. A failure encountered while attempting to add elements jaroslav@1890: * to collection {@code c} may result in elements being in jaroslav@1890: * neither, either or both collections when the associated jaroslav@1890: * exception is thrown. The behavior of this operation is jaroslav@1890: * undefined if the specified collection is modified while the jaroslav@1890: * operation is in progress. jaroslav@1890: * jaroslav@1890: * @param c the collection to transfer elements into jaroslav@1890: * @return the number of elements transferred jaroslav@1890: */ jaroslav@1890: protected int drainTasksTo(Collection> c) { jaroslav@1890: int count = 0; jaroslav@1890: while (queueBase != queueTop) { jaroslav@1890: ForkJoinTask t = pollSubmission(); jaroslav@1890: if (t != null) { jaroslav@1890: c.add(t); jaroslav@1890: ++count; jaroslav@1890: } jaroslav@1890: } jaroslav@1890: ForkJoinWorkerThread[] ws; jaroslav@1890: if ((short)(ctl >>> TC_SHIFT) > -parallelism && jaroslav@1890: (ws = workers) != null) { jaroslav@1890: for (ForkJoinWorkerThread w : ws) jaroslav@1890: if (w != null) jaroslav@1890: count += w.drainTasksTo(c); jaroslav@1890: } jaroslav@1890: return count; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns a string identifying this pool, as well as its state, jaroslav@1890: * including indications of run state, parallelism level, and jaroslav@1890: * worker and task counts. jaroslav@1890: * jaroslav@1890: * @return a string identifying this pool, as well as its state jaroslav@1890: */ jaroslav@1890: public String toString() { jaroslav@1890: long st = getStealCount(); jaroslav@1890: long qt = getQueuedTaskCount(); jaroslav@1890: long qs = getQueuedSubmissionCount(); jaroslav@1890: int pc = parallelism; jaroslav@1890: long c = ctl; jaroslav@1890: int tc = pc + (short)(c >>> TC_SHIFT); jaroslav@1890: int rc = pc + (int)(c >> AC_SHIFT); jaroslav@1890: if (rc < 0) // ignore transient negative jaroslav@1890: rc = 0; jaroslav@1890: int ac = rc + blockedCount; jaroslav@1890: String level; jaroslav@1890: if ((c & STOP_BIT) != 0) jaroslav@1890: level = (tc == 0) ? "Terminated" : "Terminating"; jaroslav@1890: else jaroslav@1890: level = shutdown ? "Shutting down" : "Running"; jaroslav@1890: return super.toString() + jaroslav@1890: "[" + level + jaroslav@1890: ", parallelism = " + pc + jaroslav@1890: ", size = " + tc + jaroslav@1890: ", active = " + ac + jaroslav@1890: ", running = " + rc + jaroslav@1890: ", steals = " + st + jaroslav@1890: ", tasks = " + qt + jaroslav@1890: ", submissions = " + qs + jaroslav@1890: "]"; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Initiates an orderly shutdown in which previously submitted jaroslav@1890: * tasks are executed, but no new tasks will be accepted. jaroslav@1890: * Invocation has no additional effect if already shut down. jaroslav@1890: * Tasks that are in the process of being submitted concurrently jaroslav@1890: * during the course of this method may or may not be rejected. 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 void shutdown() { jaroslav@1890: checkPermission(); jaroslav@1890: shutdown = true; jaroslav@1890: tryTerminate(false); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Attempts to cancel and/or stop all tasks, and reject all jaroslav@1890: * subsequently submitted tasks. Tasks that are in the process of jaroslav@1890: * being submitted or executed concurrently during the course of jaroslav@1890: * this method may or may not be rejected. This method cancels jaroslav@1890: * both existing and unexecuted tasks, in order to permit jaroslav@1890: * termination in the presence of task dependencies. So the method jaroslav@1890: * always returns an empty list (unlike the case for some other jaroslav@1890: * Executors). jaroslav@1890: * jaroslav@1890: * @return an empty list 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 List shutdownNow() { jaroslav@1890: checkPermission(); jaroslav@1890: shutdown = true; jaroslav@1890: tryTerminate(true); jaroslav@1890: return Collections.emptyList(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns {@code true} if all tasks have completed following shut down. jaroslav@1890: * jaroslav@1890: * @return {@code true} if all tasks have completed following shut down jaroslav@1890: */ jaroslav@1890: public boolean isTerminated() { jaroslav@1890: long c = ctl; jaroslav@1890: return ((c & STOP_BIT) != 0L && jaroslav@1890: (short)(c >>> TC_SHIFT) == -parallelism); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns {@code true} if the process of termination has jaroslav@1890: * commenced but not yet completed. This method may be useful for jaroslav@1890: * debugging. A return of {@code true} reported a sufficient jaroslav@1890: * period after shutdown may indicate that submitted tasks have jaroslav@1890: * ignored or suppressed interruption, or are waiting for IO, jaroslav@1890: * causing this executor not to properly terminate. (See the jaroslav@1890: * advisory notes for class {@link ForkJoinTask} stating that jaroslav@1890: * tasks should not normally entail blocking operations. But if jaroslav@1890: * they do, they must abort them on interrupt.) jaroslav@1890: * jaroslav@1890: * @return {@code true} if terminating but not yet terminated jaroslav@1890: */ jaroslav@1890: public boolean isTerminating() { jaroslav@1890: long c = ctl; jaroslav@1890: return ((c & STOP_BIT) != 0L && jaroslav@1890: (short)(c >>> TC_SHIFT) != -parallelism); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns true if terminating or terminated. Used by ForkJoinWorkerThread. jaroslav@1890: */ jaroslav@1890: final boolean isAtLeastTerminating() { jaroslav@1890: return (ctl & STOP_BIT) != 0L; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns {@code true} if this pool has been shut down. jaroslav@1890: * jaroslav@1890: * @return {@code true} if this pool has been shut down jaroslav@1890: */ jaroslav@1890: public boolean isShutdown() { jaroslav@1890: return shutdown; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Blocks until all tasks have completed execution after a shutdown jaroslav@1890: * request, or the timeout occurs, or the current thread is jaroslav@1890: * interrupted, whichever happens first. jaroslav@1890: * jaroslav@1890: * @param timeout the maximum time to wait jaroslav@1890: * @param unit the time unit of the timeout argument jaroslav@1890: * @return {@code true} if this executor terminated and jaroslav@1890: * {@code false} if the timeout elapsed before termination jaroslav@1890: * @throws InterruptedException if interrupted while waiting jaroslav@1890: */ jaroslav@1890: public boolean awaitTermination(long timeout, TimeUnit unit) jaroslav@1890: throws InterruptedException { jaroslav@1890: long nanos = unit.toNanos(timeout); jaroslav@1890: final ReentrantLock lock = this.submissionLock; jaroslav@1890: lock.lock(); jaroslav@1890: try { jaroslav@1890: for (;;) { jaroslav@1890: if (isTerminated()) jaroslav@1890: return true; jaroslav@1890: if (nanos <= 0) jaroslav@1890: return false; jaroslav@1890: nanos = termination.awaitNanos(nanos); jaroslav@1890: } jaroslav@1890: } finally { jaroslav@1890: lock.unlock(); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Interface for extending managed parallelism for tasks running jaroslav@1890: * in {@link ForkJoinPool}s. jaroslav@1890: * jaroslav@1890: *

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: *

 {@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: *

Here is a class that possibly blocks waiting for an jaroslav@1890: * item on a given queue: jaroslav@1890: *

 {@code
jaroslav@1890:      * class QueueTaker implements ManagedBlocker {
jaroslav@1890:      *   final BlockingQueue queue;
jaroslav@1890:      *   volatile E item = null;
jaroslav@1890:      *   QueueTaker(BlockingQueue q) { this.queue = q; }
jaroslav@1890:      *   public boolean block() throws InterruptedException {
jaroslav@1890:      *     if (item == null)
jaroslav@1890:      *       item = queue.take();
jaroslav@1890:      *     return true;
jaroslav@1890:      *   }
jaroslav@1890:      *   public boolean isReleasable() {
jaroslav@1890:      *     return item != null || (item = queue.poll()) != null;
jaroslav@1890:      *   }
jaroslav@1890:      *   public E getItem() { // call after pool.managedBlock completes
jaroslav@1890:      *     return item;
jaroslav@1890:      *   }
jaroslav@1890:      * }}
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: *

If the caller is not a {@link ForkJoinTask}, this method is jaroslav@1890: * behaviorally equivalent to 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 RunnableFuture newTaskFor(Runnable runnable, T value) { jaroslav@1890: return (RunnableFuture) ForkJoinTask.adapt(runnable, value); jaroslav@1890: } jaroslav@1890: jaroslav@1890: protected RunnableFuture newTaskFor(Callable callable) { jaroslav@1890: return (RunnableFuture) ForkJoinTask.adapt(callable); jaroslav@1890: } jaroslav@1890: jaroslav@1890: // Unsafe mechanics jaroslav@1890: private static final sun.misc.Unsafe UNSAFE; jaroslav@1890: private static final long ctlOffset; jaroslav@1890: private static final long stealCountOffset; jaroslav@1890: private static final long blockedCountOffset; jaroslav@1890: private static final long quiescerCountOffset; jaroslav@1890: private static final long scanGuardOffset; jaroslav@1890: private static final long nextWorkerNumberOffset; jaroslav@1890: private static final long ABASE; jaroslav@1890: private static final int ASHIFT; jaroslav@1890: jaroslav@1890: static { jaroslav@1890: poolNumberGenerator = new AtomicInteger(); jaroslav@1890: workerSeedGenerator = new Random(); jaroslav@1890: modifyThreadPermission = new RuntimePermission("modifyThread"); jaroslav@1890: defaultForkJoinWorkerThreadFactory = jaroslav@1890: new DefaultForkJoinWorkerThreadFactory(); jaroslav@1890: int s; jaroslav@1890: try { jaroslav@1890: UNSAFE = sun.misc.Unsafe.getUnsafe(); jaroslav@1890: Class k = ForkJoinPool.class; jaroslav@1890: ctlOffset = UNSAFE.objectFieldOffset jaroslav@1890: (k.getDeclaredField("ctl")); jaroslav@1890: stealCountOffset = UNSAFE.objectFieldOffset jaroslav@1890: (k.getDeclaredField("stealCount")); jaroslav@1890: blockedCountOffset = UNSAFE.objectFieldOffset jaroslav@1890: (k.getDeclaredField("blockedCount")); jaroslav@1890: quiescerCountOffset = UNSAFE.objectFieldOffset jaroslav@1890: (k.getDeclaredField("quiescerCount")); jaroslav@1890: scanGuardOffset = UNSAFE.objectFieldOffset jaroslav@1890: (k.getDeclaredField("scanGuard")); jaroslav@1890: nextWorkerNumberOffset = UNSAFE.objectFieldOffset jaroslav@1890: (k.getDeclaredField("nextWorkerNumber")); jaroslav@1890: Class a = ForkJoinTask[].class; jaroslav@1890: ABASE = UNSAFE.arrayBaseOffset(a); jaroslav@1890: s = UNSAFE.arrayIndexScale(a); jaroslav@1890: } catch (Exception e) { jaroslav@1890: throw new Error(e); jaroslav@1890: } jaroslav@1890: if ((s & (s-1)) != 0) jaroslav@1890: throw new Error("data type scale not a power of two"); jaroslav@1890: ASHIFT = 31 - Integer.numberOfLeadingZeros(s); jaroslav@1890: } jaroslav@1890: jaroslav@1890: }