ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/ForkJoinWorkerThread.java
(Generate patch)

Comparing jsr166/src/jsr166y/ForkJoinWorkerThread.java (file contents):
Revision 1.1 by dl, Tue Jan 6 14:30:31 2009 UTC vs.
Revision 1.64 by jsr166, Tue Mar 15 19:47:02 2011 UTC

# Line 1 | Line 1
1   /*
2   * Written by Doug Lea with assistance from members of JCP JSR-166
3   * Expert Group and released to the public domain, as explained at
4 < * http://creativecommons.org/licenses/publicdomain
4 > * http://creativecommons.org/publicdomain/zero/1.0/
5   */
6  
7   package jsr166y;
8 < import java.util.*;
9 < import java.util.concurrent.*;
10 < import java.util.concurrent.atomic.*;
11 < import java.util.concurrent.locks.*;
12 < import sun.misc.Unsafe;
13 < import java.lang.reflect.*;
8 >
9 > import java.util.Collection;
10 > import java.util.concurrent.RejectedExecutionException;
11  
12   /**
13 < * A thread that is internally managed by a ForkJoinPool to execute
14 < * ForkJoinTasks. This class additionally provides public
15 < * <tt>static</tt> methods accessing some basic scheduling and
19 < * execution mechanics for the <em>current</em>
20 < * ForkJoinWorkerThread. These methods may be invoked only from within
21 < * other ForkJoinTask computations. Attempts to invoke in other
22 < * contexts result in exceptions or errors including
23 < * ClassCastException.  These methods enable construction of
24 < * special-purpose task classes, as well as specialized idioms
25 < * occasionally useful in ForkJoinTask processing.
26 < *
27 < * <p>The form of supported static methods reflects the fact that
28 < * worker threads may access and process tasks obtained in any of
29 < * three ways. In preference order: <em>Local</em> tasks are processed
30 < * in LIFO (newest first) order. <em>Stolen</em> tasks are obtained
31 < * from other threads in FIFO (oldest first) order, only if there are
32 < * no local tasks to run.  <em>Submissions</em> form a FIFO queue
33 < * common to the entire pool, and are started only if no other
34 < * work is available.
35 < *
36 < * <p> This class is subclassable solely for the sake of adding
13 > * A thread managed by a {@link ForkJoinPool}, which executes
14 > * {@link ForkJoinTask}s.
15 > * This class is subclassable solely for the sake of adding
16   * functionality -- there are no overridable methods dealing with
17 < * scheduling or execution. However, you can override initialization
18 < * and termination cleanup methods surrounding the main task
19 < * processing loop.  If you do create such a subclass, you will also
20 < * need to supply a custom ForkJoinWorkerThreadFactory to use it in a
21 < * ForkJoinPool.
17 > * scheduling or execution.  However, you can override initialization
18 > * and termination methods surrounding the main task processing loop.
19 > * If you do create such a subclass, you will also need to supply a
20 > * custom {@link ForkJoinPool.ForkJoinWorkerThreadFactory} to use it
21 > * in a {@code ForkJoinPool}.
22 > *
23 > * @since 1.7
24 > * @author Doug Lea
25   */
26   public class ForkJoinWorkerThread extends Thread {
27      /*
28 <     * Algorithm overview:
28 >     * Overview:
29 >     *
30 >     * ForkJoinWorkerThreads are managed by ForkJoinPools and perform
31 >     * ForkJoinTasks. This class includes bookkeeping in support of
32 >     * worker activation, suspension, and lifecycle control described
33 >     * in more detail in the internal documentation of class
34 >     * ForkJoinPool. And as described further below, this class also
35 >     * includes special-cased support for some ForkJoinTask
36 >     * methods. But the main mechanics involve work-stealing:
37       *
38 <     * 1. Work-Stealing: Work-stealing queues are special forms of
39 <     * Deques that support only three of the four possible
40 <     * end-operations -- push, pop, and deq (aka steal), and only do
41 <     * so under the constraints that push and pop are called only from
42 <     * the owning thread, while deq may be called from other threads.
43 <     * (If you are unfamiliar with them, you probably want to read
44 <     * Herlihy and Shavit's book "The Art of Multiprocessor
45 <     * programming", chapter 16 describing these in more detail before
46 <     * proceeding.)  The main work-stealing queue design is roughly
47 <     * similar to "Dynamic Circular Work-Stealing Deque" by David
48 <     * Chase and Yossi Lev, SPAA 2005
49 <     * (http://research.sun.com/scalable/pubs/index.html).  The main
50 <     * difference ultimately stems from gc requirements that we null
51 <     * out taken slots as soon as we can, to maintain as small a
52 <     * footprint as possible even in programs generating huge numbers
53 <     * of tasks. To accomplish this, we shift the CAS arbitrating pop
54 <     * vs deq (steal) from being on the indices ("base" and "sp") to
55 <     * the slots themselves (mainly via method "casSlotNull()"). So,
56 <     * both a successful pop and deq mainly entail CAS'ing a nonnull
57 <     * slot to null.  Because we rely on CASes of references, we do
58 <     * not need tag bits on base or sp.  They are simple ints as used
59 <     * in any circular array-based queue (see for example ArrayDeque).
38 >     * Work-stealing queues are special forms of Deques that support
39 >     * only three of the four possible end-operations -- push, pop,
40 >     * and deq (aka steal), under the further constraints that push
41 >     * and pop are called only from the owning thread, while deq may
42 >     * be called from other threads.  (If you are unfamiliar with
43 >     * them, you probably want to read Herlihy and Shavit's book "The
44 >     * Art of Multiprocessor programming", chapter 16 describing these
45 >     * in more detail before proceeding.)  The main work-stealing
46 >     * queue design is roughly similar to those in the papers "Dynamic
47 >     * Circular Work-Stealing Deque" by Chase and Lev, SPAA 2005
48 >     * (http://research.sun.com/scalable/pubs/index.html) and
49 >     * "Idempotent work stealing" by Michael, Saraswat, and Vechev,
50 >     * PPoPP 2009 (http://portal.acm.org/citation.cfm?id=1504186).
51 >     * The main differences ultimately stem from gc requirements that
52 >     * we null out taken slots as soon as we can, to maintain as small
53 >     * a footprint as possible even in programs generating huge
54 >     * numbers of tasks. To accomplish this, we shift the CAS
55 >     * arbitrating pop vs deq (steal) from being on the indices
56 >     * ("queueBase" and "queueTop") to the slots themselves (mainly
57 >     * via method "casSlotNull()"). So, both a successful pop and deq
58 >     * mainly entail a CAS of a slot from non-null to null.  Because
59 >     * we rely on CASes of references, we do not need tag bits on
60 >     * queueBase or queueTop.  They are simple ints as used in any
61 >     * circular array-based queue (see for example ArrayDeque).
62       * Updates to the indices must still be ordered in a way that
63 <     * guarantees that (sp - base) > 0 means the queue is empty, but
64 <     * otherwise may err on the side of possibly making the queue
63 >     * guarantees that queueTop == queueBase means the queue is empty,
64 >     * but otherwise may err on the side of possibly making the queue
65       * appear nonempty when a push, pop, or deq have not fully
66       * committed. Note that this means that the deq operation,
67       * considered individually, is not wait-free. One thief cannot
68       * successfully continue until another in-progress one (or, if
69       * previously empty, a push) completes.  However, in the
70 <     * aggregate, we ensure at least probablistic non-blockingness. If
71 <     * an attempted steal fails, a thief always chooses a different
70 >     * aggregate, we ensure at least probabilistic non-blockingness.
71 >     * If an attempted steal fails, a thief always chooses a different
72       * random victim target to try next. So, in order for one thief to
73       * progress, it suffices for any in-progress deq or new push on
74 <     * any empty queue to complete. One reason this works well here is
75 <     * that apparently-nonempty often means soon-to-be-stealable,
76 <     * which gives threads a chance to activate if necessary before
77 <     * stealing (see below).
78 <     *
79 <     * Efficient implementation of this approach currently relies on
80 <     * an uncomfortable amount of "Unsafe" mechanics. To maintain
81 <     * correct orderings, reads and writes of variable base require
82 <     * volatile ordering.  Variable sp does not require volatile write
83 <     * but needs cheaper store-ordering on writes.  Because they are
84 <     * protected by volatile base reads, reads of the queue array and
85 <     * its slots do not need volatile load semantics, but writes (in
86 <     * push) require store order and CASes (in pop and deq) require
87 <     * (volatile) CAS semantics. Since these combinations aren't
88 <     * supported using ordinary volatiles, the only way to accomplish
89 <     * these effciently is to use direct Unsafe calls. (Using external
74 >     * any empty queue to complete.
75 >     *
76 >     * This approach also enables support for "async mode" where local
77 >     * task processing is in FIFO, not LIFO order; simply by using a
78 >     * version of deq rather than pop when locallyFifo is true (as set
79 >     * by the ForkJoinPool).  This allows use in message-passing
80 >     * frameworks in which tasks are never joined.  However neither
81 >     * mode considers affinities, loads, cache localities, etc, so
82 >     * rarely provide the best possible performance on a given
83 >     * machine, but portably provide good throughput by averaging over
84 >     * these factors.  (Further, even if we did try to use such
85 >     * information, we do not usually have a basis for exploiting
86 >     * it. For example, some sets of tasks profit from cache
87 >     * affinities, but others are harmed by cache pollution effects.)
88 >     *
89 >     * When a worker would otherwise be blocked waiting to join a
90 >     * task, it first tries a form of linear helping: Each worker
91 >     * records (in field currentSteal) the most recent task it stole
92 >     * from some other worker. Plus, it records (in field currentJoin)
93 >     * the task it is currently actively joining. Method joinTask uses
94 >     * these markers to try to find a worker to help (i.e., steal back
95 >     * a task from and execute it) that could hasten completion of the
96 >     * actively joined task. In essence, the joiner executes a task
97 >     * that would be on its own local deque had the to-be-joined task
98 >     * not been stolen. This may be seen as a conservative variant of
99 >     * the approach in Wagner & Calder "Leapfrogging: a portable
100 >     * technique for implementing efficient futures" SIGPLAN Notices,
101 >     * 1993 (http://portal.acm.org/citation.cfm?id=155354). It differs
102 >     * in that: (1) We only maintain dependency links across workers
103 >     * upon steals, rather than use per-task bookkeeping.  This may
104 >     * require a linear scan of workers array to locate stealers, but
105 >     * usually doesn't because stealers leave hints (that may become
106 >     * stale/wrong) of where to locate them. This isolates cost to
107 >     * when it is needed, rather than adding to per-task overhead.
108 >     * (2) It is "shallow", ignoring nesting and potentially cyclic
109 >     * mutual steals.  (3) It is intentionally racy: field currentJoin
110 >     * is updated only while actively joining, which means that we
111 >     * miss links in the chain during long-lived tasks, GC stalls etc
112 >     * (which is OK since blocking in such cases is usually a good
113 >     * idea).  (4) We bound the number of attempts to find work (see
114 >     * MAX_HELP) and fall back to suspending the worker and if
115 >     * necessary replacing it with another.
116 >     *
117 >     * Efficient implementation of these algorithms currently relies
118 >     * on an uncomfortable amount of "Unsafe" mechanics. To maintain
119 >     * correct orderings, reads and writes of variable queueBase
120 >     * require volatile ordering.  Variable queueTop need not be
121 >     * volatile because non-local reads always follow those of
122 >     * queueBase.  Similarly, because they are protected by volatile
123 >     * queueBase reads, reads of the queue array and its slots by
124 >     * other threads do not need volatile load semantics, but writes
125 >     * (in push) require store order and CASes (in pop and deq)
126 >     * require (volatile) CAS semantics.  (Michael, Saraswat, and
127 >     * Vechev's algorithm has similar properties, but without support
128 >     * for nulling slots.)  Since these combinations aren't supported
129 >     * using ordinary volatiles, the only way to accomplish these
130 >     * efficiently is to use direct Unsafe calls. (Using external
131       * AtomicIntegers and AtomicReferenceArrays for the indices and
132       * array is significantly slower because of memory locality and
133 <     * indirection effects.) Further, performance on most platforms is
134 <     * very sensitive to placement and sizing of the (resizable) queue
135 <     * array.  Even though these queues don't usually become all that
136 <     * big, the initial size must be large enough to counteract cache
133 >     * indirection effects.)
134 >     *
135 >     * Further, performance on most platforms is very sensitive to
136 >     * placement and sizing of the (resizable) queue array.  Even
137 >     * though these queues don't usually become all that big, the
138 >     * initial size must be large enough to counteract cache
139       * contention effects across multiple queues (especially in the
140       * presence of GC cardmarking). Also, to improve thread-locality,
141 <     * queues are currently initialized immediately after the thread
107 <     * gets the initial signal to start processing tasks.  However,
108 <     * all queue-related methods except pushTask are written in a way
109 <     * that allows them to instead be lazily allocated and/or disposed
110 <     * of when empty. All together, these low-level implementation
111 <     * choices produce as much as a factor of 4 performance
112 <     * improvement compared to naive implementations, and enable the
113 <     * processing of billions of tasks per second, sometimes at the
114 <     * expense of ugliness.
115 <     *
116 <     * 2. Run control: The primary run control is based on a global
117 <     * counter (activeCount) held by the pool. It uses an algorithm
118 <     * similar to that in Herlihy and Shavit section 17.6 to cause
119 <     * threads to eventually block when all threads declare they are
120 <     * inactive. (See variable "scans".)  For this to work, threads
121 <     * must be declared active when executing tasks, and before
122 <     * stealing a task. They must be inactive before blocking on the
123 <     * Pool Barrier (awaiting a new submission or other Pool
124 <     * event). In between, there is some free play which we take
125 <     * advantage of to avoid contention and rapid flickering of the
126 <     * global activeCount: If inactive, we activate only if a victim
127 <     * queue appears to be nonempty (see above).  Similarly, a thread
128 <     * tries to inactivate only after a full scan of other threads.
129 <     * The net effect is that contention on activeCount is rarely a
130 <     * measurable performance issue. (There are also a few other cases
131 <     * where we scan for work rather than retry/block upon
132 <     * contention.)
133 <     *
134 <     * 3. Selection control. We maintain policy of always choosing to
135 <     * run local tasks rather than stealing, and always trying to
136 <     * steal tasks before trying to run a new submission. All steals
137 <     * are currently performed in randomly-chosen deq-order. It may be
138 <     * worthwhile to bias these with locality / anti-locality
139 <     * information, but doing this well probably requires more
140 <     * lower-level information from JVMs than currently provided.
141 >     * queues are initialized after starting.
142       */
143  
144      /**
145 +     * Mask for pool indices encoded as shorts
146 +     */
147 +    private static final int  SMASK  = 0xffff;
148 +
149 +    /**
150       * Capacity of work-stealing queue array upon initialization.
151 <     * Must be a power of two. Initial size must be at least 2, but is
151 >     * Must be a power of two. Initial size must be at least 4, but is
152       * padded to minimize cache effects.
153       */
154      private static final int INITIAL_QUEUE_CAPACITY = 1 << 13;
155  
156      /**
157 <     * Maximum work-stealing queue array size.  Must be less than or
158 <     * equal to 1 << 30 to ensure lack of index wraparound.
157 >     * Maximum size for queue array. Must be a power of two
158 >     * less than or equal to 1 << (31 - width of array entry) to
159 >     * ensure lack of index wraparound, but is capped at a lower
160 >     * value to help users trap runaway computations.
161       */
162 <    private static final int MAXIMUM_QUEUE_CAPACITY = 1 << 30;
162 >    private static final int MAXIMUM_QUEUE_CAPACITY = 1 << 24; // 16M
163  
164      /**
165 <     * Generator of seeds for per-thread random numbers.
165 >     * The work-stealing queue array. Size must be a power of two.
166 >     * Initialized when started (as oposed to when constructed), to
167 >     * improve memory locality.
168       */
169 <    private static final Random randomSeedGenerator = new Random();
169 >    ForkJoinTask<?>[] queue;
170  
171      /**
172 <     * The work-stealing queue array. Size must be a power of two.
172 >     * The pool this thread works in. Accessed directly by ForkJoinTask.
173       */
174 <    private ForkJoinTask<?>[] queue;
174 >    final ForkJoinPool pool;
175  
176      /**
177       * Index (mod queue.length) of next queue slot to push to or pop
178 <     * from. It is written only by owner thread, via ordered store.
179 <     * Both sp and base are allowed to wrap around on overflow, but
180 <     * (sp - base) still estimates size.
178 >     * from. It is written only by owner thread, and accessed by other
179 >     * threads only after reading (volatile) queueBase.  Both queueTop
180 >     * and queueBase are allowed to wrap around on overflow, but
181 >     * (queueTop - queueBase) still estimates size.
182       */
183 <    private volatile int sp;
183 >    int queueTop;
184  
185      /**
186       * Index (mod queue.length) of least valid queue slot, which is
187       * always the next position to steal from if nonempty.
188       */
189 <    private volatile int base;
189 >    volatile int queueBase;
190  
191      /**
192 <     * The pool this thread works in.
192 >     * The index of most recent stealer, used as a hint to avoid
193 >     * traversal in method helpJoinTask. This is only a hint because a
194 >     * worker might have had multiple steals and this only holds one
195 >     * of them (usually the most current). Declared non-volatile,
196 >     * relying on other prevailing sync to keep reasonably current.
197       */
198 <    final ForkJoinPool pool;
198 >    int stealHint;
199  
200      /**
201       * Index of this worker in pool array. Set once by pool before
202 <     * running, and accessed directly by pool during cleanup etc
203 <     */
189 <    int poolIndex;
190 <
191 <    /**
192 <     * Run state of this worker. Supports simple versions of the usual
193 <     * shutdown/shutdownNow control.
202 >     * running, and accessed directly by pool to locate this worker in
203 >     * its workers array.
204       */
205 <    private volatile int runState;
196 <
197 <    // Runstate values. Order matters
198 <    private static final int RUNNING     = 0;
199 <    private static final int SHUTDOWN    = 1;
200 <    private static final int TERMINATING = 2;
201 <    private static final int TERMINATED  = 3;
205 >    final int poolIndex;
206  
207      /**
208 <     * Activity status. When true, this worker is considered active.
209 <     * Must be false upon construction. It must be true when executing
206 <     * tasks, and BEFORE stealing a task. It must be false before
207 <     * blocking on the Pool Barrier.
208 >     * Encoded record for pool task waits. Usages are always
209 >     * surrounded by volatile reads/writes
210       */
211 <    private boolean active;
211 >    int nextWait;
212  
213      /**
214 <     * Number of steals, transferred to pool when idle
214 >     * Complement of poolIndex, offset by count of entries of task
215 >     * waits. Accessed by ForkJoinPool to manage event waiters.
216       */
217 <    private int stealCount;
217 >    volatile int eventCount;
218  
219      /**
220 <     * Seed for random number generator for choosing steal victims
220 >     * Seed for random number generator for choosing steal victims.
221 >     * Uses Marsaglia xorshift. Must be initialized as nonzero.
222       */
223 <    private int randomVictimSeed;
223 >    int seed;
224  
225      /**
226 <     * Seed for embedded Jurandom
226 >     * Number of steals. Directly accessed (and reset) by pool when
227 >     * idle.
228       */
229 <    private long juRandomSeed;
229 >    int stealCount;
230  
231      /**
232 <     * The last barrier event waited for
228 <     */
229 <    private long eventCount;
230 <
231 <    /**
232 <     * Creates a ForkJoinWorkerThread operating in the given pool.
233 <     * @param pool the pool this thread works in
234 <     * @throws NullPointerException if pool is null
232 >     * True if this worker should or did terminate
233       */
234 <    protected ForkJoinWorkerThread(ForkJoinPool pool) {
237 <        if (pool == null) throw new NullPointerException();
238 <        this.pool = pool;
239 <        // remaining initialization deferred to onStart
240 <    }
241 <
242 <    //  Access methods used by Pool
243 <
244 <    /**
245 <     * Get and clear steal count for accumulation by pool.  Called
246 <     * only when known to be idle (in pool.sync and termination).
247 <     */
248 <    final int getAndClearStealCount() {
249 <        int sc = stealCount;
250 <        stealCount = 0;
251 <        return sc;
252 <    }
253 <
254 <    /**
255 <     * Returns estimate of the number of tasks in the queue, without
256 <     * correcting for transient negative values
257 <     */
258 <    final int getRawQueueSize() {
259 <        return sp - base;
260 <    }
261 <
262 <    // Intrinsics-based support for queue operations.
263 <    // Currently these three (setSp, setSlot, casSlotNull) are
264 <    // usually manually inlined to improve performance
234 >    volatile boolean terminate;
235  
236      /**
237 <     * Sets sp in store-order.
237 >     * Set to true before LockSupport.park; false on return
238       */
239 <    private void setSp(int s) {
270 <        _unsafe.putOrderedInt(this, spOffset, s);
271 <    }
239 >    volatile boolean parked;
240  
241      /**
242 <     * Add in store-order the given task at given slot of q to
243 <     * null. Caller must ensure q is nonnull and index is in range.
242 >     * True if use local fifo, not default lifo, for local polling.
243 >     * Shadows value from ForkJoinPool.
244       */
245 <    private static void setSlot(ForkJoinTask<?>[] q, int i,
278 <                                ForkJoinTask<?> t){
279 <        _unsafe.putOrderedObject(q, (i << qShift) + qBase, t);
280 <    }
245 >    final boolean locallyFifo;
246  
247      /**
248 <     * CAS given slot of q to null. Caller must ensure q is nonnull
249 <     * and index is in range.
248 >     * The task most recently stolen from another worker (or
249 >     * submission queue).  All uses are surrounded by enough volatile
250 >     * reads/writes to maintain as non-volatile.
251       */
252 <    private static boolean casSlotNull(ForkJoinTask<?>[] q, int i,
287 <                                       ForkJoinTask<?> t) {
288 <        return _unsafe.compareAndSwapObject(q, (i << qShift) + qBase, t, null);
289 <    }
290 <
291 <    // Main queue methods
252 >    ForkJoinTask<?> currentSteal;
253  
254      /**
255 <     * Pushes a task. Called only by current thread.
256 <     * @param t the task. Caller must ensure nonnull
255 >     * The task currently being joined, set only when actively trying
256 >     * to help other stealers in helpJoinTask. All uses are surrounded
257 >     * by enough volatile reads/writes to maintain as non-volatile.
258       */
259 <    final void pushTask(ForkJoinTask<?> t) {
298 <        ForkJoinTask<?>[] q = queue;
299 <        int mask = q.length - 1;
300 <        int s = sp;
301 <        _unsafe.putOrderedObject(q, ((s & mask) << qShift) + qBase, t);
302 <        _unsafe.putOrderedInt(this, spOffset, ++s);
303 <        if ((s -= base) == 1)
304 <            pool.signalNonEmptyWorkerQueue();
305 <        else if (s >= mask)
306 <            growQueue();
307 <    }
259 >    ForkJoinTask<?> currentJoin;
260  
261      /**
262 <     * Tries to take a task from the base of the queue, failing if
263 <     * either empty or contended.
264 <     * @return a task, or null if none or contended.
262 >     * Creates a ForkJoinWorkerThread operating in the given pool.
263 >     *
264 >     * @param pool the pool this thread works in
265 >     * @throws NullPointerException if pool is null
266       */
267 <    private ForkJoinTask<?> deqTask() {
268 <        ForkJoinTask<?>[] q;
269 <        ForkJoinTask<?> t;
270 <        int i;
271 <        int b;
272 <        if (sp != (b = base) &&
273 <            (q = queue) != null && // must read q after b
274 <            (t = q[i = (q.length - 1) & b]) != null &&
275 <            _unsafe.compareAndSwapObject(q, (i << qShift) + qBase, t, null)) {
276 <            base = b + 1;
277 <            return t;
325 <        }
326 <        return null;
267 >    protected ForkJoinWorkerThread(ForkJoinPool pool) {
268 >        super(pool.nextWorkerName());
269 >        this.pool = pool;
270 >        int k = pool.registerWorker(this);
271 >        poolIndex = k;
272 >        eventCount = ~k & SMASK; // clear wait count
273 >        locallyFifo = pool.locallyFifo;
274 >        Thread.UncaughtExceptionHandler ueh = pool.ueh;
275 >        if (ueh != null)
276 >            setUncaughtExceptionHandler(ueh);
277 >        setDaemon(true);
278      }
279  
280 <    /**
330 <     * Returns a popped task, or null if empty.  Called only by
331 <     * current thread.
332 <     */
333 <    final ForkJoinTask<?> popTask() {
334 <        ForkJoinTask<?> t;
335 <        int i;
336 <        ForkJoinTask<?>[] q = queue;
337 <        int mask = q.length - 1;
338 <        int s = sp;
339 <        if (s != base &&
340 <            (t = q[i = (s - 1) & mask]) != null &&
341 <            _unsafe.compareAndSwapObject(q, (i << qShift) + qBase, t, null)) {
342 <            _unsafe.putOrderedInt(this, spOffset, s - 1);
343 <            return t;
344 <        }
345 <        return null;
346 <    }
280 >    // Public methods
281  
282      /**
283 <     * Specialized version of popTask to pop only if
284 <     * topmost element is the given task. Called only
285 <     * by current thread.
352 <     * @param t the task. Caller must ensure nonnull
283 >     * Returns the pool hosting this thread.
284 >     *
285 >     * @return the pool
286       */
287 <    final boolean unpushTask(ForkJoinTask<?> t) {
288 <        ForkJoinTask<?>[] q = queue;
356 <        int mask = q.length - 1;
357 <        int s = sp - 1;
358 <        if (_unsafe.compareAndSwapObject(q, ((s & mask) << qShift) + qBase,
359 <                                         t, null)) {
360 <            _unsafe.putOrderedInt(this, spOffset, s);
361 <            return true;
362 <        }
363 <        return false;
287 >    public ForkJoinPool getPool() {
288 >        return pool;
289      }
290  
291      /**
292 <     * Returns next task to pop.
293 <     */
294 <    private ForkJoinTask<?> peekTask() {
295 <        ForkJoinTask<?>[] q = queue;
296 <        return q == null? null : q[(sp - 1) & (q.length - 1)];
297 <    }
298 <
374 <    /**
375 <     * Doubles queue array size. Transfers elements by emulating
376 <     * steals (deqs) from old array and placing, oldest first, into
377 <     * new array.
378 <     */
379 <    private void growQueue() {
380 <        ForkJoinTask<?>[] oldQ = queue;
381 <        int oldSize = oldQ.length;
382 <        int newSize = oldSize << 1;
383 <        if (newSize > MAXIMUM_QUEUE_CAPACITY)
384 <            throw new RejectedExecutionException("Queue capacity exceeded");
385 <        ForkJoinTask<?>[] newQ = queue = new ForkJoinTask<?>[newSize];
386 <
387 <        int b = base;
388 <        int bf = b + oldSize;
389 <        int oldMask = oldSize - 1;
390 <        int newMask = newSize - 1;
391 <        do {
392 <            int oldIndex = b & oldMask;
393 <            ForkJoinTask<?> t = oldQ[oldIndex];
394 <            if (t != null && !casSlotNull(oldQ, oldIndex, t))
395 <                t = null;
396 <            setSlot(newQ, b & newMask, t);
397 <        } while (++b != bf);
398 <        pool.signalIdleWorkers(false);
399 <    }
400 <
401 <    // Runstate management
402 <
403 <    final boolean isShutdown()    { return runState >= SHUTDOWN;  }
404 <    final boolean isTerminating() { return runState >= TERMINATING;  }
405 <    final boolean isTerminated()  { return runState == TERMINATED; }
406 <    final boolean shutdown()      { return transitionRunStateTo(SHUTDOWN); }
407 <    final boolean shutdownNow()   { return transitionRunStateTo(TERMINATING); }
408 <
409 <    /**
410 <     * Transition to at least the given state. Return true if not
411 <     * already at least given state.
292 >     * Returns the index number of this thread in its pool.  The
293 >     * returned value ranges from zero to the maximum number of
294 >     * threads (minus one) that have ever been created in the pool.
295 >     * This method may be useful for applications that track status or
296 >     * collect results per-worker rather than per-task.
297 >     *
298 >     * @return the index number
299       */
300 <    private boolean transitionRunStateTo(int state) {
301 <        for (;;) {
415 <            int s = runState;
416 <            if (s >= state)
417 <                return false;
418 <            if (_unsafe.compareAndSwapInt(this, runStateOffset, s, state))
419 <                return true;
420 <        }
300 >    public int getPoolIndex() {
301 >        return poolIndex;
302      }
303  
304 <    /**
424 <     * Ensure status is active and if necessary adjust pool active count
425 <     */
426 <    final void activate() {
427 <        if (!active) {
428 <            active = true;
429 <            pool.incrementActiveCount();
430 <        }
431 <    }
304 >    // Randomization
305  
306      /**
307 <     * Ensure status is inactive and if necessary adjust pool active count
307 >     * Computes next value for random victim probes and backoffs.
308 >     * Scans don't require a very high quality generator, but also not
309 >     * a crummy one.  Marsaglia xor-shift is cheap and works well
310 >     * enough.  Note: This is manually inlined in FJP.scan() to avoid
311 >     * writes inside busy loops.
312       */
313 <    final void inactivate() {
314 <        if (active) {
315 <            active = false;
316 <            pool.decrementActiveCount();
317 <        }
313 >    private int nextSeed() {
314 >        int r = seed;
315 >        r ^= r << 13;
316 >        r ^= r >>> 17;
317 >        r ^= r << 5;
318 >        return seed = r;
319      }
320  
321 <    // Lifecycle methods
321 >    // Run State management
322  
323      /**
324       * Initializes internal state after construction but before
325       * processing any tasks. If you override this method, you must
326 <     * invoke super.onStart() at the beginning of the method.
326 >     * invoke {@code super.onStart()} at the beginning of the method.
327       * Initialization requires care: Most fields must have legal
328       * default values, to ensure that attempted accesses from other
329       * threads work correctly even before this thread starts
330       * processing tasks.
331       */
332      protected void onStart() {
333 <        juRandomSeed = randomSeedGenerator.nextLong();
334 <        do;while((randomVictimSeed = nextRandomInt()) == 0); // must be nonzero
335 <        if (queue == null)
458 <            queue = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY];
459 <
460 <        // Heuristically allow one initial thread to warm up; others wait
461 <        if (poolIndex < pool.getParallelism() - 1) {
462 <            eventCount = pool.sync(this, 0);
463 <            activate();
464 <        }
333 >        queue = new ForkJoinTask<?>[INITIAL_QUEUE_CAPACITY];
334 >        int r = pool.workerSeedGenerator.nextInt();
335 >        seed = (r == 0)? 1 : r; //  must be nonzero
336      }
337  
338      /**
339 <     * Perform cleanup associated with termination of this worker
339 >     * Performs cleanup associated with termination of this worker
340       * thread.  If you override this method, you must invoke
341 <     * super.onTermination at the end of the overridden method.
341 >     * {@code super.onTermination} at the end of the overridden method.
342       *
343       * @param exception the exception causing this thread to abort due
344 <     * to an unrecoverable error, or null if completed normally.
344 >     * to an unrecoverable error, or {@code null} if completed normally
345       */
346      protected void onTermination(Throwable exception) {
347          try {
348 <            clearLocalTasks();
478 <            inactivate();
348 >            terminate = true;
349              cancelTasks();
350 +            pool.deregisterWorker(this, exception);
351 +        } catch (Throwable ex) {        // Shouldn't ever happen
352 +            if (exception == null)      // but if so, at least rethrown
353 +                exception = ex;
354          } finally {
355 <            terminate(exception);
355 >            if (exception != null)
356 >                UNSAFE.throwException(exception);
357          }
358      }
359  
360      /**
361 <     * Notify pool of termination and, if exception is nonnull,
362 <     * rethrow it to trigger this thread's uncaughtExceptionHandler
361 >     * This method is required to be public, but should never be
362 >     * called explicitly. It performs the main run loop to execute
363 >     * {@link ForkJoinTask}s.
364       */
365 <    private void terminate(Throwable exception) {
366 <        transitionRunStateTo(TERMINATED);
365 >    public void run() {
366 >        Throwable exception = null;
367          try {
368 <            pool.workerTerminated(this);
368 >            onStart();
369 >            pool.work(this);
370 >        } catch (Throwable ex) {
371 >            exception = ex;
372          } finally {
373 <            if (exception != null)
495 <                ForkJoinTask.rethrowException(exception);
373 >            onTermination(exception);
374          }
375      }
376  
377 +    /*
378 +     * Intrinsics-based atomic writes for queue slots. These are
379 +     * basically the same as methods in AtomicReferenceArray, but
380 +     * specialized for (1) ForkJoinTask elements (2) requirement that
381 +     * nullness and bounds checks have already been performed by
382 +     * callers and (3) effective offsets are known not to overflow
383 +     * from int to long (because of MAXIMUM_QUEUE_CAPACITY). We don't
384 +     * need corresponding version for reads: plain array reads are OK
385 +     * because they are protected by other volatile reads and are
386 +     * confirmed by CASes.
387 +     *
388 +     * Most uses don't actually call these methods, but instead
389 +     * contain inlined forms that enable more predictable
390 +     * optimization.  We don't define the version of write used in
391 +     * pushTask at all, but instead inline there a store-fenced array
392 +     * slot write.
393 +     *
394 +     * Also in most methods, as a performance (not correctness) issue,
395 +     * we'd like to encourage compilers not to arbitrarily postpone
396 +     * setting queueTop after writing slot.  Currently there is no
397 +     * intrinsic for arranging this, but using Unsafe putOrderedInt
398 +     * may be a preferable strategy on some compilers even though its
399 +     * main effect is a pre-, not post- fence. To simplify possible
400 +     * changes, the option is left in comments next to the associated
401 +     * assignments.
402 +     */
403 +
404      /**
405 <     * Run local tasks on exit from main.
405 >     * CASes slot i of array q from t to null. Caller must ensure q is
406 >     * non-null and index is in range.
407       */
408 <    private void clearLocalTasks() {
409 <        while (base != sp && !pool.isTerminating()) {
410 <            ForkJoinTask<?> t = popTask();
505 <            if (t != null) {
506 <                activate(); // ensure active status
507 <                t.quietlyExec();
508 <            }
509 <        }
408 >    private static final boolean casSlotNull(ForkJoinTask<?>[] q, int i,
409 >                                             ForkJoinTask<?> t) {
410 >        return UNSAFE.compareAndSwapObject(q, (i << ASHIFT) + ABASE, t, null);
411      }
412  
413      /**
414 <     * Removes and cancels all tasks in queue.  Can be called from any
415 <     * thread.
414 >     * Performs a volatile write of the given task at given slot of
415 >     * array q.  Caller must ensure q is non-null and index is in
416 >     * range. This method is used only during resets and backouts.
417       */
418 <    final void cancelTasks() {
419 <        while (base != sp) {
420 <            ForkJoinTask<?> t = deqTask();
519 <            if (t != null)
520 <                t.cancelIgnoreExceptions();
521 <        }
418 >    private static final void writeSlot(ForkJoinTask<?>[] q, int i,
419 >                                        ForkJoinTask<?> t) {
420 >        UNSAFE.putObjectVolatile(q, (i << ASHIFT) + ABASE, t);
421      }
422  
423 +    // queue methods
424 +
425      /**
426 <     * This method is required to be public, but should never be
427 <     * called explicitly. It performs the main run loop to execute
428 <     * ForkJoinTasks.
426 >     * Pushes a task. Call only from this thread.
427 >     *
428 >     * @param t the task. Caller must ensure non-null.
429       */
430 <    public void run() {
431 <        Throwable exception = null;
432 <        try {
433 <            onStart();
434 <            while (!isShutdown())
435 <                step();
436 <        } catch (Throwable ex) {
437 <            exception = ex;
438 <        } finally {
439 <            onTermination(exception);
430 >    final void pushTask(ForkJoinTask<?> t) {
431 >        ForkJoinTask<?>[] q; int s, m;
432 >        if ((q = queue) != null) {    // ignore if queue removed
433 >            long u = (((s = queueTop) & (m = q.length - 1)) << ASHIFT) + ABASE;
434 >            UNSAFE.putOrderedObject(q, u, t);
435 >            queueTop = s + 1;         // or use putOrderedInt
436 >            if ((s -= queueBase) <= 2)
437 >                pool.signalWork();
438 >            else if (s == m)
439 >                growQueue();
440          }
441      }
442  
443      /**
444 <     * Main top-level action.
444 >     * Creates or doubles queue array.  Transfers elements by
445 >     * emulating steals (deqs) from old array and placing, oldest
446 >     * first, into new array.
447       */
448 <    private void step() {
449 <        ForkJoinTask<?> t = sp != base? popTask() : null;
450 <        if (t != null || (t = scan(null, true)) != null) {
451 <            activate();
452 <            t.quietlyExec();
453 <        }
454 <        else {
455 <            inactivate();
456 <            eventCount = pool.sync(this, eventCount);
448 >    private void growQueue() {
449 >        ForkJoinTask<?>[] oldQ = queue;
450 >        int size = oldQ != null ? oldQ.length << 1 : INITIAL_QUEUE_CAPACITY;
451 >        if (size > MAXIMUM_QUEUE_CAPACITY)
452 >            throw new RejectedExecutionException("Queue capacity exceeded");
453 >        if (size < INITIAL_QUEUE_CAPACITY)
454 >            size = INITIAL_QUEUE_CAPACITY;
455 >        ForkJoinTask<?>[] q = queue = new ForkJoinTask<?>[size];
456 >        int mask = size - 1;
457 >        int top = queueTop;
458 >        int oldMask;
459 >        if (oldQ != null && (oldMask = oldQ.length - 1) >= 0) {
460 >            for (int b = queueBase; b != top; ++b) {
461 >                long u = ((b & oldMask) << ASHIFT) + ABASE;
462 >                Object x = UNSAFE.getObjectVolatile(oldQ, u);
463 >                if (x != null && UNSAFE.compareAndSwapObject(oldQ, u, x, null))
464 >                    UNSAFE.putObjectVolatile
465 >                        (q, ((b & mask) << ASHIFT) + ABASE, x);
466 >            }
467          }
468      }
469  
557    // scanning for and stealing tasks
558
470      /**
471 <     * Computes next value for random victim probe. Scans don't
472 <     * require a very high quality generator, but also not a crummy
473 <     * one. Marsaglia xor-shift is cheap and works well.
471 >     * Tries to take a task from the base of the queue, failing if
472 >     * empty or contended. Note: Specializations of this code appear
473 >     * in locallyDeqTask and elsewhere.
474       *
475 <     * This is currently unused, and manually inlined
475 >     * @return a task, or null if none or contended
476       */
477 <    private static int xorShift(int r) {
478 <        r ^= r << 1;
479 <        r ^= r >>> 3;
480 <        r ^= r << 10;
481 <        return r;
477 >    final ForkJoinTask<?> deqTask() {
478 >        ForkJoinTask<?> t; ForkJoinTask<?>[] q; int b, i;
479 >        if (queueTop != (b = queueBase) &&
480 >            (q = queue) != null && // must read q after b
481 >            (i = (q.length - 1) & b) >= 0 &&
482 >            (t = q[i]) != null && queueBase == b &&
483 >            UNSAFE.compareAndSwapObject(q, (i << ASHIFT) + ABASE, t, null)) {
484 >            queueBase = b + 1;
485 >            return t;
486 >        }
487 >        return null;
488      }
489  
490      /**
491 <     * Tries to steal a task from another worker and/or, if enabled,
492 <     * submission queue. Starts at a random index of workers array,
576 <     * and probes workers until finding one with non-empty queue or
577 <     * finding that all are empty.  It randomly selects the first n-1
578 <     * probes. If these are empty, it resorts to full circular
579 <     * traversal, which is necessary to accurately set active status
580 <     * by caller. Also restarts if pool barrier has tripped since last
581 <     * scan, which forces refresh of workers array, in case barrier
582 <     * was associated with resize.
583 <     *
584 <     * This method must be both fast and quiet -- usually avoiding
585 <     * memory accesses that could disrupt cache sharing etc other than
586 <     * those needed to check for and take tasks. This accounts for,
587 <     * among other things, updating random seed in place without
588 <     * storing it until exit. (Note that we only need to store it if
589 <     * we found a task; otherwise it doesn't matter if we start at the
590 <     * same place next time.)
491 >     * Tries to take a task from the base of own queue.  Called only
492 >     * by this thread.
493       *
494 <     * @param joinMe if non null; exit early if done
593 <     * @param checkSubmissions true if OK to take submissions
594 <     * @return a task, or null if none found
494 >     * @return a task, or null if none
495       */
496 <    private ForkJoinTask<?> scan(ForkJoinTask<?> joinMe,
497 <                                 boolean checkSubmissions) {
498 <        ForkJoinPool p = pool;
499 <        if (p == null)                    // Never null, but avoids
500 <            return null;                  //   implicit nullchecks below
501 <        int r = randomVictimSeed;         // extract once to keep scan quiet
502 <        restart:                          // outer loop refreshes ws array
503 <        while (joinMe == null || joinMe.status >= 0) {
504 <            int mask;
505 <            ForkJoinWorkerThread[] ws = p.workers;
606 <            if (ws != null && (mask = ws.length - 1) > 0) {
607 <                int probes = -mask;       // use random index while negative
608 <                int idx = r;
609 <                for (;;) {
610 <                    ForkJoinWorkerThread v;
611 <                    // inlined xorshift to update seed
612 <                    r ^= r << 1;  r ^= r >>> 3; r ^= r << 10;
613 <                    if ((v = ws[mask & idx]) != null && v.sp != v.base) {
614 <                        ForkJoinTask<?> t;
615 <                        activate();
616 <                        if ((joinMe == null || joinMe.status >= 0) &&
617 <                            (t = v.deqTask()) != null) {
618 <                            randomVictimSeed = r;
619 <                            ++stealCount;
620 <                            return t;
621 <                        }
622 <                        continue restart; // restart on contention
623 <                    }
624 <                    if ((probes >> 1) <= mask) // n-1 random then circular
625 <                        idx = (probes++ < 0)? r : (idx + 1);
626 <                    else
627 <                        break;
628 <                }
629 <            }
630 <            if (checkSubmissions && p.hasQueuedSubmissions()) {
631 <                activate();
632 <                ForkJoinTask<?> t = p.pollSubmission();
633 <                if (t != null)
496 >    final ForkJoinTask<?> locallyDeqTask() {
497 >        ForkJoinTask<?> t; int m, b, i;
498 >        ForkJoinTask<?>[] q = queue;
499 >        if (q != null && (m = q.length - 1) >= 0) {
500 >            while (queueTop != (b = queueBase)) {
501 >                if ((t = q[i = m & b]) != null &&
502 >                    queueBase == b &&
503 >                    UNSAFE.compareAndSwapObject(q, (i << ASHIFT) + ABASE,
504 >                                                t, null)) {
505 >                    queueBase = b + 1;
506                      return t;
507 <            }
636 <            else {
637 <                long ec = eventCount;     // restart on pool event
638 <                if ((eventCount = p.getEventCount()) == ec)
639 <                    break;
507 >                }
508              }
509          }
510          return null;
511      }
512  
513      /**
514 <     * Callback from pool.sync to rescan before blocking.  If a
515 <     * task is found, it is pushed so it can be executed upon return.
516 <     * @return true if found and pushed a task
517 <     */
518 <    final boolean prescan() {
519 <        ForkJoinTask<?> t = scan(null, true);
520 <        if (t != null) {
521 <            pushTask(t);
522 <            return true;
523 <        }
524 <        else {
525 <            inactivate();
526 <            return false;
514 >     * Returns a popped task, or null if empty.
515 >     * Called only by this thread.
516 >     */
517 >    private ForkJoinTask<?> popTask() {
518 >        int m;
519 >        ForkJoinTask<?>[] q = queue;
520 >        if (q != null && (m = q.length - 1) >= 0) {
521 >            for (int s; (s = queueTop) != queueBase;) {
522 >                int i = m & --s;
523 >                long u = (i << ASHIFT) + ABASE; // raw offset
524 >                ForkJoinTask<?> t = q[i];
525 >                if (t == null)   // lost to stealer
526 >                    break;
527 >                if (UNSAFE.compareAndSwapObject(q, u, t, null)) {
528 >                    queueTop = s; // or putOrderedInt
529 >                    return t;
530 >                }
531 >            }
532          }
533 +        return null;
534      }
535  
536      /**
537 <     * Implements ForkJoinTask.helpJoin
537 >     * Specialized version of popTask to pop only if topmost element
538 >     * is the given task. Called only by this thread.
539 >     *
540 >     * @param t the task. Caller must ensure non-null.
541       */
542 <    final int helpJoinTask(ForkJoinTask<?> joinMe) {
543 <        ForkJoinTask<?> t = null;
542 >    final boolean unpushTask(ForkJoinTask<?> t) {
543 >        ForkJoinTask<?>[] q;
544          int s;
545 <        while ((s = joinMe.status) >= 0) {
546 <            if (t == null) {
547 <                if ((t = scan(joinMe, false)) == null)  // block if no work
548 <                    return joinMe.awaitDone(this, false);
549 <                // else recheck status before exec
673 <            }
674 <            else {
675 <                t.quietlyExec();
676 <                t = null;
677 <            }
545 >        if ((q = queue) != null && (s = queueTop) != queueBase &&
546 >            UNSAFE.compareAndSwapObject
547 >            (q, (((q.length - 1) & --s) << ASHIFT) + ABASE, t, null)) {
548 >            queueTop = s; // or putOrderedInt
549 >            return true;
550          }
551 <        if (t != null) // unsteal
680 <            pushTask(t);
681 <        return s;
551 >        return false;
552      }
553  
684    // Support for public static and/or ForkJoinTask methods
685
554      /**
555 <     * Returns an estimate of the number of tasks in the queue.
555 >     * Returns next task, or null if empty or contended.
556       */
557 <    final int getQueueSize() {
558 <        int b = base;
559 <        int n = sp - b;
560 <        return n <= 0? 0 : n; // suppress momentarily negative values
557 >    final ForkJoinTask<?> peekTask() {
558 >        int m;
559 >        ForkJoinTask<?>[] q = queue;
560 >        if (q == null || (m = q.length - 1) < 0)
561 >            return null;
562 >        int i = locallyFifo ? queueBase : (queueTop - 1);
563 >        return q[i & m];
564      }
565  
566 <    /**
696 <     * Runs one popped task, if available
697 <     * @return true if ran a task
698 <     */
699 <    private boolean runLocalTask() {
700 <        ForkJoinTask<?> t = popTask();
701 <        if (t == null)
702 <            return false;
703 <        t.quietlyExec();
704 <        return true;
705 <    }
566 >    // Support methods for ForkJoinPool
567  
568      /**
569 <     * Pops or steals a task
709 <     * @return task, or null if none available
569 >     * Runs the given task, plus any local tasks until queue is empty
570       */
571 <    private ForkJoinTask<?> getLocalOrStolenTask() {
572 <        ForkJoinTask<?> t = popTask();
573 <        return t != null? t : scan(null, false);
571 >    final void execTask(ForkJoinTask<?> t) {
572 >        currentSteal = t;
573 >        for (;;) {
574 >            if (t != null)
575 >                t.doExec();
576 >            if (queueTop == queueBase)
577 >                break;
578 >            t = locallyFifo ? locallyDeqTask() : popTask();
579 >        }
580 >        ++stealCount;
581 >        currentSteal = null;
582      }
583  
584      /**
585 <     * Runs a popped or stolen task, if available
586 <     * @return true if ran a task
585 >     * Removes and cancels all tasks in queue.  Can be called from any
586 >     * thread.
587       */
588 <    private boolean runLocalOrStolenTask() {
589 <        ForkJoinTask<?> t = getLocalOrStolenTask();
590 <        if (t == null)
591 <            return false;
592 <        t.quietlyExec();
593 <        return true;
588 >    final void cancelTasks() {
589 >        ForkJoinTask<?> cj = currentJoin; // try to cancel ongoing tasks
590 >        if (cj != null && cj.status >= 0)
591 >            cj.cancelIgnoringExceptions();
592 >        ForkJoinTask<?> cs = currentSteal;
593 >        if (cs != null && cs.status >= 0)
594 >            cs.cancelIgnoringExceptions();
595 >        while (queueBase != queueTop) {
596 >            ForkJoinTask<?> t = deqTask();
597 >            if (t != null)
598 >                t.cancelIgnoringExceptions();
599 >        }
600      }
601  
602      /**
603 <     * Runs tasks until pool isQuiescent
603 >     * Drains tasks to given collection c.
604 >     *
605 >     * @return the number of tasks drained
606       */
607 <    final void helpQuiescePool() {
608 <        activate();
609 <        for (;;) {
610 <            if (!runLocalOrStolenTask()) {
611 <                inactivate();
612 <                if (pool.isQuiescent()) {
613 <                    activate(); // re-activate on exit
738 <                    break;
739 <                }
607 >    final int drainTasksTo(Collection<? super ForkJoinTask<?>> c) {
608 >        int n = 0;
609 >        while (queueBase != queueTop) {
610 >            ForkJoinTask<?> t = deqTask();
611 >            if (t != null) {
612 >                c.add(t);
613 >                ++n;
614              }
615          }
616 +        return n;
617      }
618  
619 <    /**
745 <     * Returns an estimate of the number of tasks, offset by a
746 <     * function of number of idle workers.
747 <     */
748 <    final int getEstimatedSurplusTaskCount() {
749 <        return (sp - base) - (pool.getIdleThreadCount() >>> 1);
750 <    }
751 <
752 <    // Public methods on current thread
619 >    // Support methods for ForkJoinTask
620  
621      /**
622 <     * Returns the pool hosting the current task execution.
756 <     * @return the pool
622 >     * Returns an estimate of the number of tasks in the queue.
623       */
624 <    public static ForkJoinPool getPool() {
625 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).pool;
624 >    final int getQueueSize() {
625 >        return queueTop - queueBase;
626      }
627  
628      /**
629 <     * Returns the index number of the current worker thread in its
630 <     * pool.  The returned value ranges from zero to the maximum
631 <     * number of threads (minus one) that have ever been created in
766 <     * the pool.  This method may be useful for applications that
767 <     * track status or collect results per-worker rather than
768 <     * per-task.
769 <     * @return the index number.
629 >     * Gets and removes a local task.
630 >     *
631 >     * @return a task, if available
632       */
633 <    public static int getPoolIndex() {
634 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).poolIndex;
633 >    final ForkJoinTask<?> pollLocalTask() {
634 >        return locallyFifo ? locallyDeqTask() : popTask();
635      }
636  
637      /**
638 <     * Returns an estimate of the number of tasks waiting to be run by
639 <     * the current worker thread. This value may be useful for
640 <     * heuristic decisions about whether to fork other tasks.
779 <     * @return the number of tasks
638 >     * Gets and removes a local or stolen task.
639 >     *
640 >     * @return a task, if available
641       */
642 <    public static int getLocalQueueSize() {
643 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
644 <            getQueueSize();
642 >    final ForkJoinTask<?> pollTask() {
643 >        ForkJoinWorkerThread[] ws;
644 >        ForkJoinTask<?> t = pollLocalTask();
645 >        if (t != null || (ws = pool.workers) == null)
646 >            return t;
647 >        int n = ws.length; // cheap version of FJP.scan
648 >        int steps = n << 1;
649 >        int r = nextSeed();
650 >        int i = 0;
651 >        while (i < steps) {
652 >            ForkJoinWorkerThread w = ws[(i++ + r) & (n - 1)];
653 >            if (w != null && w.queueBase != w.queueTop && w.queue != null) {
654 >                if ((t = w.deqTask()) != null)
655 >                    return t;
656 >                i = 0;
657 >            }
658 >        }
659 >        return null;
660      }
661  
662      /**
663 <     * Returns, but does not remove or execute, the next task locally
664 <     * queued for execution by the current worker thread. There is no
665 <     * guarantee that this task will be the next one actually returned
666 <     * or executed from other polling or execution methods.
667 <     * @return the next task or null if none
663 >     * The maximum stolen->joining link depth allowed in helpJoinTask,
664 >     * as well as the maximum number of retries (allowing on average
665 >     * one staleness retry per level) per attempt to instead try
666 >     * compensation.  Depths for legitimate chains are unbounded, but
667 >     * we use a fixed constant to avoid (otherwise unchecked) cycles
668 >     * and bound staleness of traversal parameters at the expense of
669 >     * sometimes blocking when we could be helping.
670       */
671 <    public static ForkJoinTask<?> peekLocalTask() {
794 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).peekTask();
795 <    }
671 >    private static final int MAX_HELP = 16;
672  
673      /**
674 <     * Removes and returns, without executing, the next task queued
675 <     * for execution in the current worker thread's local queue.
676 <     * @return the next task to execute, or null if none
674 >     * Possibly runs some tasks and/or blocks, until joinMe is done.
675 >     *
676 >     * @param joinMe the task to join
677 >     * @return completion status on exit
678       */
679 <    public static ForkJoinTask<?> pollLocalTask() {
680 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).popTask();
679 >    final int joinTask(ForkJoinTask<?> joinMe) {
680 >        ForkJoinTask<?> prevJoin = currentJoin;
681 >        currentJoin = joinMe;
682 >        for (int s, retries = MAX_HELP;;) {
683 >            if ((s = joinMe.status) < 0) {
684 >                currentJoin = prevJoin;
685 >                return s;
686 >            }
687 >            if (retries > 0) {
688 >                if (queueTop != queueBase) {
689 >                    if (!localHelpJoinTask(joinMe))
690 >                        retries = 0;           // cannot help
691 >                }
692 >                else if (retries == MAX_HELP >>> 1) {
693 >                    --retries;                 // check uncommon case
694 >                    if (tryDeqAndExec(joinMe) >= 0)
695 >                        Thread.yield();        // for politeness
696 >                }
697 >                else
698 >                    retries = helpJoinTask(joinMe)? MAX_HELP : retries - 1;
699 >            }
700 >            else {
701 >                retries = MAX_HELP;           // restart if not done
702 >                pool.tryAwaitJoin(joinMe);
703 >            }
704 >        }
705      }
706  
707      /**
708 <     * Execute the next task locally queued by the current worker, if
709 <     * one is available.
710 <     * @return true if a task was run; a false return indicates
711 <     * that no task was available.
708 >     * If present, pops and executes the given task, or any other
709 >     * cancelled task
710 >     *
711 >     * @return false if any other non-cancelled task exists in local queue
712       */
713 <    public static boolean executeLocalTask() {
714 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
715 <            runLocalTask();
713 >    private boolean localHelpJoinTask(ForkJoinTask<?> joinMe) {
714 >        int s, i; ForkJoinTask<?>[] q; ForkJoinTask<?> t;
715 >        if ((s = queueTop) != queueBase && (q = queue) != null &&
716 >            (i = (q.length - 1) & --s) >= 0 &&
717 >            (t = q[i]) != null) {
718 >            if (t != joinMe && t.status >= 0)
719 >                return false;
720 >            if (UNSAFE.compareAndSwapObject
721 >                (q, (i << ASHIFT) + ABASE, t, null)) {
722 >                queueTop = s;           // or putOrderedInt
723 >                t.doExec();
724 >            }
725 >        }
726 >        return true;
727      }
728  
729      /**
730 <     * Removes and returns, without executing, the next task queued
731 <     * for execution in the current worker thread's local queue or if
732 <     * none, a task stolen from another worker, if one is available.
733 <     * A null return does not necessarily imply that all tasks are
734 <     * completed, only that there are currently none available.
735 <     * @return the next task to execute, or null if none
730 >     * Tries to locate and execute tasks for a stealer of the given
731 >     * task, or in turn one of its stealers, Traces
732 >     * currentSteal->currentJoin links looking for a thread working on
733 >     * a descendant of the given task and with a non-empty queue to
734 >     * steal back and execute tasks from.  The implementation is very
735 >     * branchy to cope with potential inconsistencies or loops
736 >     * encountering chains that are stale, unknown, or of length
737 >     * greater than MAX_HELP links.  All of these cases are dealt with
738 >     * by just retrying by caller.
739 >     *
740 >     * @param joinMe the task to join
741 >     * @param canSteal true if local queue is empty
742 >     * @return true if ran a task
743       */
744 <    public static ForkJoinTask<?> pollTask() {
745 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
746 <            getLocalOrStolenTask();
744 >    private boolean helpJoinTask(ForkJoinTask<?> joinMe) {
745 >        boolean helped = false;
746 >        int m = pool.scanGuard & SMASK;
747 >        ForkJoinWorkerThread[] ws = pool.workers;
748 >        if (ws != null && ws.length > m && joinMe.status >= 0) {
749 >            int levels = MAX_HELP;              // remaining chain length
750 >            ForkJoinTask<?> task = joinMe;      // base of chain
751 >            outer:for (ForkJoinWorkerThread thread = this;;) {
752 >                // Try to find v, the stealer of task, by first using hint
753 >                ForkJoinWorkerThread v = ws[thread.stealHint & m];
754 >                if (v == null || v.currentSteal != task) {
755 >                    for (int j = 0; ;) {        // search array
756 >                        if ((v = ws[j]) != null && v.currentSteal == task) {
757 >                            thread.stealHint = j;
758 >                            break;              // save hint for next time
759 >                        }
760 >                        if (++j > m)
761 >                            break outer;        // can't find stealer
762 >                    }
763 >                }
764 >                // Try to help v, using specialized form of deqTask
765 >                for (;;) {
766 >                    ForkJoinTask<?>[] q; int b, i;
767 >                    if (joinMe.status < 0)
768 >                        break outer;
769 >                    if ((b = v.queueBase) == v.queueTop ||
770 >                        (q = v.queue) == null ||
771 >                        (i = (q.length-1) & b) < 0)
772 >                        break;                  // empty
773 >                    long u = (i << ASHIFT) + ABASE;
774 >                    ForkJoinTask<?> t = q[i];
775 >                    if (task.status < 0)
776 >                        break outer;            // stale
777 >                    if (t != null && v.queueBase == b &&
778 >                        UNSAFE.compareAndSwapObject(q, u, t, null)) {
779 >                        v.queueBase = b + 1;
780 >                        v.stealHint = poolIndex;
781 >                        ForkJoinTask<?> ps = currentSteal;
782 >                        currentSteal = t;
783 >                        t.doExec();
784 >                        currentSteal = ps;
785 >                        helped = true;
786 >                    }
787 >                }
788 >                // Try to descend to find v's stealer
789 >                ForkJoinTask<?> next = v.currentJoin;
790 >                if (--levels > 0 && task.status >= 0 &&
791 >                    next != null && next != task) {
792 >                    task = next;
793 >                    thread = v;
794 >                }
795 >                else
796 >                    break;  // max levels, stale, dead-end, or cyclic
797 >            }
798 >        }
799 >        return helped;
800      }
801  
802      /**
803 <     * Helps this program complete by processing a local or stolen
804 <     * task, if one is available.  This method may be useful when
833 <     * several tasks are forked, and only one of them must be joined,
834 <     * as in:
803 >     * Performs an uncommon case for joinTask: If task t is at base of
804 >     * some workers queue, steals and executes it.
805       *
806 <     * <pre>
807 <     *   while (!t1.isDone() &amp;&amp; !t2.isDone())
838 <     *     ForkJoinWorkerThread.executeTask();
839 <     * </pre>
840 <     *
841 <     * @return true if a task was run; a false return indicates
842 <     * that no task was available.
806 >     * @param t the task
807 >     * @return t's status
808       */
809 <    public static boolean executeTask() {
810 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
811 <            runLocalOrStolenTask();
812 <    }
813 <
814 <    // Per-worker exported random numbers
815 <
816 <    // Same constants as java.util.Random
817 <    final static long JURandomMultiplier = 0x5DEECE66DL;
818 <    final static long JURandomAddend = 0xBL;
819 <    final static long JURandomMask = (1L << 48) - 1;
820 <
821 <    private final int nextJURandom(int bits) {
822 <        long next = (juRandomSeed * JURandomMultiplier + JURandomAddend) &
823 <            JURandomMask;
824 <        juRandomSeed = next;
825 <        return (int)(next >>> (48 - bits));
826 <    }
827 <
828 <    private final int nextJURandomInt(int n) {
829 <        if (n <= 0)
830 <            throw new IllegalArgumentException("n must be positive");
831 <        int bits = nextJURandom(31);
832 <        if ((n & -n) == n)
833 <            return (int)((n * (long)bits) >> 31);
869 <
870 <        for (;;) {
871 <            int val = bits % n;
872 <            if (bits - val + (n-1) >= 0)
873 <                return val;
874 <            bits = nextJURandom(31);
875 <        }
876 <    }
877 <
878 <    private final long nextJURandomLong() {
879 <        return ((long)(nextJURandom(32)) << 32) + nextJURandom(32);
880 <    }
881 <
882 <    private final long nextJURandomLong(long n) {
883 <        if (n <= 0)
884 <            throw new IllegalArgumentException("n must be positive");
885 <        long offset = 0;
886 <        while (n >= Integer.MAX_VALUE) { // randomly pick half range
887 <            int bits = nextJURandom(2); // 2nd bit for odd vs even split
888 <            long half = n >>> 1;
889 <            long nextn = ((bits & 2) == 0)? half : n - half;
890 <            if ((bits & 1) == 0)
891 <                offset += n - nextn;
892 <            n = nextn;
809 >    private int tryDeqAndExec(ForkJoinTask<?> t) {
810 >        int m = pool.scanGuard & SMASK;
811 >        ForkJoinWorkerThread[] ws = pool.workers;
812 >        if (ws != null && ws.length > m && t.status >= 0) {
813 >            for (int j = 0; j <= m; ++j) {
814 >                ForkJoinTask<?>[] q; int b, i;
815 >                ForkJoinWorkerThread v = ws[j];
816 >                if (v != null &&
817 >                    (b = v.queueBase) != v.queueTop &&
818 >                    (q = v.queue) != null &&
819 >                    (i = (q.length - 1) & b) >= 0 &&
820 >                    q[i] ==  t) {
821 >                    long u = (i << ASHIFT) + ABASE;
822 >                    if (v.queueBase == b &&
823 >                        UNSAFE.compareAndSwapObject(q, u, t, null)) {
824 >                        v.queueBase = b + 1;
825 >                        v.stealHint = poolIndex;
826 >                        ForkJoinTask<?> ps = currentSteal;
827 >                        currentSteal = t;
828 >                        t.doExec();
829 >                        currentSteal = ps;
830 >                    }
831 >                    break;
832 >                }
833 >            }
834          }
835 <        return offset + nextJURandomInt((int)n);
895 <    }
896 <
897 <    private final double nextJURandomDouble() {
898 <        return (((long)(nextJURandom(26)) << 27) + nextJURandom(27))
899 <            / (double)(1L << 53);
835 >        return t.status;
836      }
837  
838      /**
839 <     * Returns a random integer using a per-worker random
840 <     * number generator with the same properties as
841 <     * {@link java.util.Random#nextInt}
842 <     * @return the next pseudorandom, uniformly distributed {@code int}
843 <     *         value from this worker's random number generator's sequence
839 >     * Implements ForkJoinTask.getSurplusQueuedTaskCount().  Returns
840 >     * an estimate of the number of tasks, offset by a function of
841 >     * number of idle workers.
842 >     *
843 >     * This method provides a cheap heuristic guide for task
844 >     * partitioning when programmers, frameworks, tools, or languages
845 >     * have little or no idea about task granularity.  In essence by
846 >     * offering this method, we ask users only about tradeoffs in
847 >     * overhead vs expected throughput and its variance, rather than
848 >     * how finely to partition tasks.
849 >     *
850 >     * In a steady state strict (tree-structured) computation, each
851 >     * thread makes available for stealing enough tasks for other
852 >     * threads to remain active. Inductively, if all threads play by
853 >     * the same rules, each thread should make available only a
854 >     * constant number of tasks.
855 >     *
856 >     * The minimum useful constant is just 1. But using a value of 1
857 >     * would require immediate replenishment upon each steal to
858 >     * maintain enough tasks, which is infeasible.  Further,
859 >     * partitionings/granularities of offered tasks should minimize
860 >     * steal rates, which in general means that threads nearer the top
861 >     * of computation tree should generate more than those nearer the
862 >     * bottom. In perfect steady state, each thread is at
863 >     * approximately the same level of computation tree. However,
864 >     * producing extra tasks amortizes the uncertainty of progress and
865 >     * diffusion assumptions.
866 >     *
867 >     * So, users will want to use values larger, but not much larger
868 >     * than 1 to both smooth over transient shortages and hedge
869 >     * against uneven progress; as traded off against the cost of
870 >     * extra task overhead. We leave the user to pick a threshold
871 >     * value to compare with the results of this call to guide
872 >     * decisions, but recommend values such as 3.
873 >     *
874 >     * When all threads are active, it is on average OK to estimate
875 >     * surplus strictly locally. In steady-state, if one thread is
876 >     * maintaining say 2 surplus tasks, then so are others. So we can
877 >     * just use estimated queue length (although note that (queueTop -
878 >     * queueBase) can be an overestimate because of stealers lagging
879 >     * increments of queueBase).  However, this strategy alone leads
880 >     * to serious mis-estimates in some non-steady-state conditions
881 >     * (ramp-up, ramp-down, other stalls). We can detect many of these
882 >     * by further considering the number of "idle" threads, that are
883 >     * known to have zero queued tasks, so compensate by a factor of
884 >     * (#idle/#active) threads.
885       */
886 <    public static int nextRandomInt() {
887 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
911 <            nextJURandom(32);
886 >    final int getEstimatedSurplusTaskCount() {
887 >        return queueTop - queueBase - pool.idlePerActive();
888      }
889  
890      /**
891 <     * Returns a random integer using a per-worker random
892 <     * number generator with the same properties as
893 <     * {@link java.util.Random#nextInt(int)}
894 <     * @param n the bound on the random number to be returned.  Must be
895 <     *        positive.
896 <     * @return the next pseudorandom, uniformly distributed {@code int}
897 <     *         value between {@code 0} (inclusive) and {@code n} (exclusive)
922 <     *         from this worker's random number generator's sequence
923 <     * @throws IllegalArgumentException if n is not positive
891 >     * Runs tasks until {@code pool.isQuiescent()}. We piggyback on
892 >     * pool's active count ctl maintenance, but rather than blocking
893 >     * when tasks cannot be found, we rescan until all others cannot
894 >     * find tasks either. The bracketing by pool quiescerCounts
895 >     * updates suppresses pool auto-shutdown mechanics that could
896 >     * otherwise prematurely terminate the pool because all threads
897 >     * appear to be inactive.
898       */
899 <    public static int nextRandomInt(int n) {
900 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
901 <            nextJURandomInt(n);
899 >    final void helpQuiescePool() {
900 >        boolean active = true;
901 >        ForkJoinTask<?> ps = currentSteal; // to restore below
902 >        ForkJoinPool p = pool;
903 >        p.addQuiescerCount(1);
904 >        for (;;) {
905 >            ForkJoinWorkerThread[] ws = p.workers;
906 >            ForkJoinWorkerThread v = null;
907 >            int n;
908 >            if (queueTop != queueBase)
909 >                v = this;
910 >            else if (ws != null && (n = ws.length) > 1) {
911 >                ForkJoinWorkerThread w;
912 >                int r = nextSeed(); // cheap version of FJP.scan
913 >                int steps = n << 1;
914 >                for (int i = 0; i < steps; ++i) {
915 >                    if ((w = ws[(i + r) & (n - 1)]) != null &&
916 >                        w.queueBase != w.queueTop) {
917 >                        v = w;
918 >                        break;
919 >                    }
920 >                }
921 >            }
922 >            if (v != null) {
923 >                ForkJoinTask<?> t;
924 >                if (!active) {
925 >                    active = true;
926 >                    p.addActiveCount(1);
927 >                }
928 >                if ((t = (v != this) ? v.deqTask() :
929 >                     locallyFifo? locallyDeqTask() : popTask()) != null) {
930 >                    currentSteal = t;
931 >                    t.doExec();
932 >                    currentSteal = ps;
933 >                }
934 >            }
935 >            else {
936 >                if (active) {
937 >                    active = false;
938 >                    p.addActiveCount(-1);
939 >                }
940 >                if (p.isQuiescent()) {
941 >                    p.addActiveCount(1);
942 >                    p.addQuiescerCount(-1);
943 >                    break;
944 >                }
945 >            }
946 >        }
947      }
948  
949 <    /**
950 <     * Returns a random long using a per-worker random
951 <     * number generator with the same properties as
952 <     * {@link java.util.Random#nextLong}
934 <     * @return the next pseudorandom, uniformly distributed {@code long}
935 <     *         value from this worker's random number generator's sequence
936 <     */
937 <    public static long nextRandomLong() {
938 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
939 <            nextJURandomLong();
940 <    }
949 >    // Unsafe mechanics
950 >    private static final sun.misc.Unsafe UNSAFE;
951 >    private static final long ABASE;
952 >    private static final int ASHIFT;
953  
954 <    /**
955 <     * Returns a random integer using a per-worker random
956 <     * number generator with the same properties as
957 <     * {@link java.util.Random#nextInt(int)}
958 <     * @param n the bound on the random number to be returned.  Must be
959 <     *        positive.
960 <     * @return the next pseudorandom, uniformly distributed {@code int}
961 <     *         value between {@code 0} (inclusive) and {@code n} (exclusive)
962 <     *         from this worker's random number generator's sequence
963 <     * @throws IllegalArgumentException if n is not positive
964 <     */
965 <    public static long nextRandomLong(long n) {
966 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
955 <            nextJURandomLong(n);
954 >    static {
955 >        int s;
956 >        try {
957 >            UNSAFE = getUnsafe();
958 >            Class a = ForkJoinTask[].class;
959 >            ABASE = UNSAFE.arrayBaseOffset(a);
960 >            s = UNSAFE.arrayIndexScale(a);
961 >        } catch (Exception e) {
962 >            throw new Error(e);
963 >        }
964 >        if ((s & (s-1)) != 0)
965 >            throw new Error("data type scale not a power of two");
966 >        ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
967      }
968  
969      /**
970 <     * Returns a random double using a per-worker random
971 <     * number generator with the same properties as
972 <     * {@link java.util.Random#nextDouble}
973 <     * @return the next pseudorandom, uniformly distributed {@code double}
974 <     *         value between {@code 0.0} and {@code 1.0} from this
964 <     *         worker's random number generator's sequence
970 >     * Returns a sun.misc.Unsafe.  Suitable for use in a 3rd party package.
971 >     * Replace with a simple call to Unsafe.getUnsafe when integrating
972 >     * into a jdk.
973 >     *
974 >     * @return a sun.misc.Unsafe
975       */
976 <    public static double nextRandomDouble() {
967 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).
968 <            nextJURandomDouble();
969 <    }
970 <
971 <    // Temporary Unsafe mechanics for preliminary release
972 <
973 <    static final Unsafe _unsafe;
974 <    static final long baseOffset;
975 <    static final long spOffset;
976 <    static final long qBase;
977 <    static final int qShift;
978 <    static final long runStateOffset;
979 <    static {
976 >    private static sun.misc.Unsafe getUnsafe() {
977          try {
978 <            if (ForkJoinWorkerThread.class.getClassLoader() != null) {
979 <                Field f = Unsafe.class.getDeclaredField("theUnsafe");
980 <                f.setAccessible(true);
981 <                _unsafe = (Unsafe)f.get(null);
982 <            }
983 <            else
984 <                _unsafe = Unsafe.getUnsafe();
985 <            baseOffset = _unsafe.objectFieldOffset
986 <                (ForkJoinWorkerThread.class.getDeclaredField("base"));
987 <            spOffset = _unsafe.objectFieldOffset
988 <                (ForkJoinWorkerThread.class.getDeclaredField("sp"));
989 <            runStateOffset = _unsafe.objectFieldOffset
990 <                (ForkJoinWorkerThread.class.getDeclaredField("runState"));
991 <            qBase = _unsafe.arrayBaseOffset(ForkJoinTask[].class);
992 <            int s = _unsafe.arrayIndexScale(ForkJoinTask[].class);
993 <            if ((s & (s-1)) != 0)
997 <                throw new Error("data type scale not a power of two");
998 <            qShift = 31 - Integer.numberOfLeadingZeros(s);
999 <        } catch (Exception e) {
1000 <            throw new RuntimeException("Could not initialize intrinsics", e);
978 >            return sun.misc.Unsafe.getUnsafe();
979 >        } catch (SecurityException se) {
980 >            try {
981 >                return java.security.AccessController.doPrivileged
982 >                    (new java.security
983 >                     .PrivilegedExceptionAction<sun.misc.Unsafe>() {
984 >                        public sun.misc.Unsafe run() throws Exception {
985 >                            java.lang.reflect.Field f = sun.misc
986 >                                .Unsafe.class.getDeclaredField("theUnsafe");
987 >                            f.setAccessible(true);
988 >                            return (sun.misc.Unsafe) f.get(null);
989 >                        }});
990 >            } catch (java.security.PrivilegedActionException e) {
991 >                throw new RuntimeException("Could not initialize intrinsics",
992 >                                           e.getCause());
993 >            }
994          }
995      }
996   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines