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

Comparing jsr166/src/jsr166y/ForkJoinTask.java (file contents):
Revision 1.63 by dl, Sat Sep 18 12:10:21 2010 UTC vs.
Revision 1.81 by dl, Thu Jan 26 00:08:13 2012 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
9 import java.util.concurrent.*;
8   import java.io.Serializable;
9   import java.util.Collection;
12 import java.util.Collections;
10   import java.util.List;
11   import java.util.RandomAccess;
12 < import java.util.Map;
13 < import java.util.WeakHashMap;
12 > import java.lang.ref.WeakReference;
13 > import java.lang.ref.ReferenceQueue;
14 > import java.util.concurrent.Callable;
15 > import java.util.concurrent.CancellationException;
16 > import java.util.concurrent.ExecutionException;
17 > import java.util.concurrent.Future;
18 > import java.util.concurrent.RejectedExecutionException;
19 > import java.util.concurrent.RunnableFuture;
20 > import java.util.concurrent.TimeUnit;
21 > import java.util.concurrent.TimeoutException;
22 > import java.util.concurrent.locks.ReentrantLock;
23 > import java.lang.reflect.Constructor;
24  
25   /**
26   * Abstract base class for tasks that run within a {@link ForkJoinPool}.
# Line 35 | Line 42 | import java.util.WeakHashMap;
42   * <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}.
43   * The efficiency of {@code ForkJoinTask}s stems from a set of
44   * restrictions (that are only partially statically enforceable)
45 < * reflecting their intended use as computational tasks calculating
46 < * pure functions or operating on purely isolated objects.  The
47 < * primary coordination mechanisms are {@link #fork}, that arranges
45 > * reflecting their main use as computational tasks calculating pure
46 > * functions or operating on purely isolated objects.  The primary
47 > * coordination mechanisms are {@link #fork}, that arranges
48   * asynchronous execution, and {@link #join}, that doesn't proceed
49   * until the task's result has been computed.  Computations should
50 < * avoid {@code synchronized} methods or blocks, and should minimize
51 < * other blocking synchronization apart from joining other tasks or
52 < * using synchronizers such as Phasers that are advertised to
53 < * cooperate with fork/join scheduling. Tasks should also not perform
54 < * blocking IO, and should ideally access variables that are
55 < * completely independent of those accessed by other running
56 < * tasks. Minor breaches of these restrictions, for example using
57 < * shared output streams, may be tolerable in practice, but frequent
58 < * use may result in poor performance, and the potential to
59 < * indefinitely stall if the number of threads not waiting for IO or
60 < * other external synchronization becomes exhausted. This usage
61 < * restriction is in part enforced by not permitting checked
62 < * exceptions such as {@code IOExceptions} to be thrown. However,
63 < * computations may still encounter unchecked exceptions, that are
64 < * rethrown to callers attempting to join them. These exceptions may
65 < * additionally include {@link RejectedExecutionException} stemming
66 < * from internal resource exhaustion, such as failure to allocate
67 < * internal task queues.
50 > * ideally avoid {@code synchronized} methods or blocks, and should
51 > * minimize other blocking synchronization apart from joining other
52 > * tasks or using synchronizers such as Phasers that are advertised to
53 > * cooperate with fork/join scheduling. Subdividable tasks should also
54 > * not perform blocking IO, and should ideally access variables that
55 > * are completely independent of those accessed by other running
56 > * tasks. These guidelines are loosely enforced by not permitting
57 > * checked exceptions such as {@code IOExceptions} to be
58 > * thrown. However, computations may still encounter unchecked
59 > * exceptions, that are rethrown to callers attempting to join
60 > * them. These exceptions may additionally include {@link
61 > * RejectedExecutionException} stemming from internal resource
62 > * exhaustion, such as failure to allocate internal task
63 > * queues. Rethrown exceptions behave in the same way as regular
64 > * exceptions, but, when possible, contain stack traces (as displayed
65 > * for example using {@code ex.printStackTrace()}) of both the thread
66 > * that initiated the computation as well as the thread actually
67 > * encountering the exception; minimally only the latter.
68 > *
69 > * <p>It is possible to define and use ForkJoinTasks that may block,
70 > * but doing do requires three further considerations: (1) Completion
71 > * of few if any <em>other</em> tasks should be dependent on a task
72 > * that blocks on external synchronization or IO. Event-style async
73 > * tasks that are never joined often fall into this category.  (2) To
74 > * minimize resource impact, tasks should be small; ideally performing
75 > * only the (possibly) blocking action. (3) Unless the {@link
76 > * ForkJoinPool.ManagedBlocker} API is used, or the number of possibly
77 > * blocked tasks is known to be less than the pool's {@link
78 > * ForkJoinPool#getParallelism} level, the pool cannot guarantee that
79 > * enough threads will be available to ensure progress or good
80 > * performance.
81   *
82   * <p>The primary method for awaiting completion and extracting
83   * results of a task is {@link #join}, but there are several variants:
# Line 73 | Line 93 | import java.util.WeakHashMap;
93   * performs the most common form of parallel invocation: forking a set
94   * of tasks and joining them all.
95   *
96 + * <p>In the most typical usages, a fork-join pair act like a a call
97 + * (fork) and return (join) from a parallel recursive function. As is
98 + * the case with other forms of recursive calls, returns (joins)
99 + * should be performed innermost-first. For example, {@code a.fork();
100 + * b.fork(); b.join(); a.join();} is likely to be substantially more
101 + * efficient than joining {@code a} before {@code b}.
102 + *
103   * <p>The execution status of tasks may be queried at several levels
104   * of detail: {@link #isDone} is true if a task completed in any way
105   * (including the case where a task was cancelled without executing);
# Line 101 | Line 128 | import java.util.WeakHashMap;
128   * result in exceptions or errors, possibly including
129   * {@code ClassCastException}.
130   *
131 + * <p>Method {@link #join} and its variants are appropriate for use
132 + * only when completion dependencies are acyclic; that is, the
133 + * parallel computation can be described as a directed acyclic graph
134 + * (DAG). Otherwise, executions may encounter a form of deadlock as
135 + * tasks cyclically wait for each other.  However, this framework
136 + * supports other methods and techniques (for example the use of
137 + * {@link Phaser}, {@link #helpQuiesce}, and {@link #complete}) that
138 + * may be of use in constructing custom subclasses for problems that
139 + * are not statically structured as DAGs. To support such usages a
140 + * ForkJoinTask may be atomically <em>marked</em> using {@link
141 + * #markForkJoinTask} and checked for marking using {@link
142 + * #isMarkedForkJoinTask}. The ForkJoinTask implementation does not
143 + * use these {@code protected} methods or marks for any purpose, but
144 + * they may be of use in the construction of specialized subclasses.
145 + * For example, parallel graph traversals can use the supplied methods
146 + * to avoid revisiting nodes/tasks that have already been
147 + * processed. Also, completion based designs can use them to record
148 + * that one subtask has completed. (Method names for marking are bulky
149 + * in part to encourage definition of methods that reflect their usage
150 + * patterns.)
151 + *
152   * <p>Most base support methods are {@code final}, to prevent
153   * overriding of implementations that are intrinsically tied to the
154   * underlying lightweight task scheduling framework.  Developers
# Line 115 | Line 163 | import java.util.WeakHashMap;
163   * computation. Large tasks should be split into smaller subtasks,
164   * usually via recursive decomposition. As a very rough rule of thumb,
165   * a task should perform more than 100 and less than 10000 basic
166 < * computational steps. If tasks are too big, then parallelism cannot
167 < * improve throughput. If too small, then memory and internal task
168 < * maintenance overhead may overwhelm processing.
166 > * computational steps, and should avoid indefinite looping. If tasks
167 > * are too big, then parallelism cannot improve throughput. If too
168 > * small, then memory and internal task maintenance overhead may
169 > * overwhelm processing.
170   *
171   * <p>This class provides {@code adapt} methods for {@link Runnable}
172   * and {@link Callable}, that may be of use when mixing execution of
# Line 138 | Line 187 | public abstract class ForkJoinTask<V> im
187       * See the internal documentation of class ForkJoinPool for a
188       * general implementation overview.  ForkJoinTasks are mainly
189       * responsible for maintaining their "status" field amidst relays
190 <     * to methods in ForkJoinWorkerThread and ForkJoinPool. The
191 <     * methods of this class are more-or-less layered into (1) basic
192 <     * status maintenance (2) execution and awaiting completion (3)
193 <     * user-level methods that additionally report results. This is
194 <     * sometimes hard to see because this file orders exported methods
195 <     * in a way that flows well in javadocs. In particular, most
196 <     * join mechanics are in method quietlyJoin, below.
190 >     * to methods in ForkJoinWorkerThread and ForkJoinPool.
191 >     *
192 >     * The methods of this class are more-or-less layered into
193 >     * (1) basic status maintenance
194 >     * (2) execution and awaiting completion
195 >     * (3) user-level methods that additionally report results.
196 >     * This is sometimes hard to see because this file orders exported
197 >     * methods in a way that flows well in javadocs.
198 >     */
199 >
200 >    /**
201 >     * The number of times to try to help join a task without any
202 >     * apparent progress before giving up and blocking. The value is
203 >     * arbitrary but should be large enough to cope with transient
204 >     * stalls (due to GC etc) that can cause helping methods not to be
205 >     * able to proceed because other workers have not progressed to
206 >     * the point where subtasks can be found or taken.
207       */
208 +    private static final int HELP_RETRIES = 32;
209  
210      /*
211       * The status field holds run control status bits packed into a
# Line 166 | Line 226 | public abstract class ForkJoinTask<V> im
226  
227      /** The run status of this task */
228      volatile int status; // accessed directly by pool and workers
229 +    static final int NORMAL      = 0xfffffffc;  // negative with low 2 bits 0
230 +    static final int CANCELLED   = 0xfffffff8;  // must be < NORMAL
231 +    static final int EXCEPTIONAL = 0xfffffff4;  // must be < CANCELLED
232 +    static final int SIGNAL      = 0x00000001;
233 +    static final int MARKED      = 0x00000002;
234  
235 <    private static final int NORMAL      = -1;
236 <    private static final int CANCELLED   = -2;
237 <    private static final int EXCEPTIONAL = -3;
238 <    private static final int SIGNAL      =  1;
235 >    /**
236 >     * Marks completion and wakes up threads waiting to join this
237 >     * task, also clearing signal request bits. A specialization for
238 >     * NORMAL completion is in method doExec
239 >     *
240 >     * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
241 >     * @return completion status on exit
242 >     */
243 >    private int setCompletion(int completion) {
244 >        for (int s;;) {
245 >            if ((s = status) < 0)
246 >                return s;
247 >            if (U.compareAndSwapInt(this, STATUS, s, (s & ~SIGNAL)|completion)) {
248 >                if ((s & SIGNAL) != 0)
249 >                    synchronized (this) { notifyAll(); }
250 >                return completion;
251 >            }
252 >        }
253 >    }
254  
255      /**
256 <     * Table of exceptions thrown by tasks, to enable reporting by
257 <     * callers. Because exceptions are rare, we don't directly keep
258 <     * them with task objects, but instead use a weak ref table.  Note
259 <     * that cancellation exceptions don't appear in the table, but are
260 <     * instead recorded as status values.
181 <     * TODO: Use ConcurrentReferenceHashMap
256 >     * Primary execution method for stolen tasks. Unless done, calls
257 >     * exec and records status if completed, but doesn't wait for
258 >     * completion otherwise.
259 >     *
260 >     * @return status on exit from this method
261       */
262 <    static final Map<ForkJoinTask<?>, Throwable> exceptionMap =
263 <        Collections.synchronizedMap
264 <        (new WeakHashMap<ForkJoinTask<?>, Throwable>());
262 >    final int doExec() {
263 >        int s; boolean completed;
264 >        if ((s = status) >= 0) {
265 >            try {
266 >                completed = exec();
267 >            } catch (Throwable rex) {
268 >                return setExceptionalCompletion(rex);
269 >            }
270 >            while ((s = status) >= 0 && completed) {
271 >                if (U.compareAndSwapInt(this, STATUS, s, (s & ~SIGNAL)|NORMAL)) {
272 >                    if ((s & SIGNAL) != 0)
273 >                        synchronized (this) { notifyAll(); }
274 >                    return NORMAL;
275 >                }
276 >            }
277 >        }
278 >        return s;
279 >    }
280 >
281 >    /**
282 >     * Blocks a non-worker-thread until completion.
283 >     * @return status upon completion
284 >     */
285 >    private int externalAwaitDone() {
286 >        int s;
287 >        if ((s = status) >= 0) {
288 >            boolean interrupted = false;
289 >            synchronized (this) {
290 >                while ((s = status) >= 0) {
291 >                    if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
292 >                        try {
293 >                            wait();
294 >                        } catch (InterruptedException ie) {
295 >                            interrupted = true;
296 >                        }
297 >                    }
298 >                }
299 >            }
300 >            if (interrupted)
301 >                Thread.currentThread().interrupt();
302 >        }
303 >        return s;
304 >    }
305 >
306 >    /**
307 >     * Blocks a non-worker-thread until completion or interruption or timeout.
308 >     */
309 >    private int externalInterruptibleAwaitDone(long millis)
310 >        throws InterruptedException {
311 >        int s;
312 >        if (Thread.interrupted())
313 >            throw new InterruptedException();
314 >        if ((s = status) >= 0) {
315 >            synchronized (this) {
316 >                while ((s = status) >= 0) {
317 >                    if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
318 >                        wait(millis);
319 >                        if (millis > 0L)
320 >                            break;
321 >                    }
322 >                }
323 >            }
324 >        }
325 >        return s;
326 >    }
327  
187    // Maintaining completion status
328  
329      /**
330 <     * Marks completion and wakes up threads waiting to join this task,
331 <     * also clearing signal request bits.
330 >     * Implementation for join, get, quietlyJoin. Directly handles
331 >     * only cases of already-completed, external wait, and
332 >     * unfork+exec.  Others are relayed to awaitJoin.
333       *
334 <     * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
334 >     * @return status upon completion
335 >     */
336 >    private int doJoin() {
337 >        int s; Thread t; ForkJoinWorkerThread wt; ForkJoinPool.WorkQueue w;
338 >        if ((s = status) >= 0) {
339 >            if (!((t = Thread.currentThread()) instanceof ForkJoinWorkerThread))
340 >                s = externalAwaitDone();
341 >            else if (!(w = (wt = (ForkJoinWorkerThread)t).workQueue).
342 >                     tryUnpush(this) || (s = doExec()) >= 0)
343 >                s = awaitJoin(w, wt.pool);
344 >        }
345 >        return s;
346 >    }
347 >
348 >    /**
349 >     * Helps and/or blocks until joined.
350 >     *
351 >     * @param w the joiner
352 >     * @param p the pool
353 >     * @return status upon completion
354       */
355 <    private void setCompletion(int completion) {
355 >    private int awaitJoin(ForkJoinPool.WorkQueue w, ForkJoinPool p) {
356          int s;
357 <        while ((s = status) >= 0) {
358 <            if (UNSAFE.compareAndSwapInt(this, statusOffset, s, completion)) {
359 <                if (s != 0)
360 <                    synchronized (this) { notifyAll(); }
357 >        ForkJoinTask<?> prevJoin = w.currentJoin;
358 >        w.currentJoin = this;
359 >        for (int k = HELP_RETRIES; (s = status) >= 0;) {
360 >            if ((w.queueSize() > 0) ?
361 >                w.tryRemoveAndExec(this) :        // self-help
362 >                p.tryHelpStealer(w, this))        // help process tasks
363 >                k = HELP_RETRIES;                 // reset if made progress
364 >            else if ((s = status) < 0)            // recheck
365                  break;
366 +            else if (--k > 0) {
367 +                if ((k & 3) == 1)
368 +                    Thread.yield();               // occasionally yield
369 +            }
370 +            else if (k == 0)
371 +                p.tryPollForAndExec(w, this);     // uncommon self-help case
372 +            else if (p.tryCompensate()) {         // true if can block
373 +                try {
374 +                    int ss = status;
375 +                    if (ss >= 0 &&                // assert need signal
376 +                        U.compareAndSwapInt(this, STATUS, ss, ss | SIGNAL)) {
377 +                        synchronized (this) {
378 +                            if (status >= 0)      // block
379 +                                wait();
380 +                        }
381 +                    }
382 +                } catch (InterruptedException ignore) {
383 +                } finally {
384 +                    p.incrementActiveCount();     // re-activate
385 +                }
386              }
387          }
388 +        w.currentJoin = prevJoin;
389 +        return s;
390 +    }
391 +
392 +    /**
393 +     * Implementation for invoke, quietlyInvoke.
394 +     *
395 +     * @return status upon completion
396 +     */
397 +    private int doInvoke() {
398 +        int s;
399 +        if ((s = doExec()) < 0)
400 +            return s;
401 +        else
402 +            return doJoin();
403 +    }
404 +
405 +    // Exception table support
406 +
407 +    /**
408 +     * Table of exceptions thrown by tasks, to enable reporting by
409 +     * callers. Because exceptions are rare, we don't directly keep
410 +     * them with task objects, but instead use a weak ref table.  Note
411 +     * that cancellation exceptions don't appear in the table, but are
412 +     * instead recorded as status values.
413 +     *
414 +     * Note: These statics are initialized below in static block.
415 +     */
416 +    private static final ExceptionNode[] exceptionTable;
417 +    private static final ReentrantLock exceptionTableLock;
418 +    private static final ReferenceQueue<Object> exceptionTableRefQueue;
419 +
420 +    /**
421 +     * Fixed capacity for exceptionTable.
422 +     */
423 +    private static final int EXCEPTION_MAP_CAPACITY = 32;
424 +
425 +    /**
426 +     * Key-value nodes for exception table.  The chained hash table
427 +     * uses identity comparisons, full locking, and weak references
428 +     * for keys. The table has a fixed capacity because it only
429 +     * maintains task exceptions long enough for joiners to access
430 +     * them, so should never become very large for sustained
431 +     * periods. However, since we do not know when the last joiner
432 +     * completes, we must use weak references and expunge them. We do
433 +     * so on each operation (hence full locking). Also, some thread in
434 +     * any ForkJoinPool will call helpExpungeStaleExceptions when its
435 +     * pool becomes isQuiescent.
436 +     */
437 +    static final class ExceptionNode extends WeakReference<ForkJoinTask<?>>{
438 +        final Throwable ex;
439 +        ExceptionNode next;
440 +        final long thrower;  // use id not ref to avoid weak cycles
441 +        ExceptionNode(ForkJoinTask<?> task, Throwable ex, ExceptionNode next) {
442 +            super(task, exceptionTableRefQueue);
443 +            this.ex = ex;
444 +            this.next = next;
445 +            this.thrower = Thread.currentThread().getId();
446 +        }
447      }
448  
449      /**
# Line 208 | Line 451 | public abstract class ForkJoinTask<V> im
451       *
452       * @return status on exit
453       */
454 <    private void setExceptionalCompletion(Throwable rex) {
455 <        exceptionMap.put(this, rex);
456 <        setCompletion(EXCEPTIONAL);
454 >    private int setExceptionalCompletion(Throwable ex) {
455 >        int h = System.identityHashCode(this);
456 >        final ReentrantLock lock = exceptionTableLock;
457 >        lock.lock();
458 >        try {
459 >            expungeStaleExceptions();
460 >            ExceptionNode[] t = exceptionTable;
461 >            int i = h & (t.length - 1);
462 >            for (ExceptionNode e = t[i]; ; e = e.next) {
463 >                if (e == null) {
464 >                    t[i] = new ExceptionNode(this, ex, t[i]);
465 >                    break;
466 >                }
467 >                if (e.get() == this) // already present
468 >                    break;
469 >            }
470 >        } finally {
471 >            lock.unlock();
472 >        }
473 >        return setCompletion(EXCEPTIONAL);
474      }
475  
476      /**
477 <     * Blocks a worker thread until completion. Called only by
478 <     * pool. Currently unused -- pool-based waits use timeout
479 <     * version below.
477 >     * Cancels, ignoring any exceptions thrown by cancel. Used during
478 >     * worker and pool shutdown. Cancel is spec'ed not to throw any
479 >     * exceptions, but if it does anyway, we have no recourse during
480 >     * shutdown, so guard against this case.
481       */
482 <    final void internalAwaitDone() {
483 <        int s;         // the odd construction reduces lock bias effects
223 <        while ((s = status) >= 0) {
482 >    static final void cancelIgnoringExceptions(ForkJoinTask<?> t) {
483 >        if (t != null && t.status >= 0) {
484              try {
485 <                synchronized (this) {
486 <                    if (UNSAFE.compareAndSwapInt(this, statusOffset, s,SIGNAL))
227 <                        wait();
228 <                }
229 <            } catch (InterruptedException ie) {
230 <                cancelIfTerminating();
485 >                t.cancel(false);
486 >            } catch (Throwable ignore) {
487              }
488          }
489      }
490  
491      /**
492 <     * Blocks a worker thread until completed or timed out.  Called
237 <     * only by pool.
238 <     *
239 <     * @return status on exit
492 >     * Removes exception node and clears status
493       */
494 <    final int internalAwaitDone(long millis) {
495 <        int s;
496 <        if ((s = status) >= 0) {
494 >    private void clearExceptionalCompletion() {
495 >        int h = System.identityHashCode(this);
496 >        final ReentrantLock lock = exceptionTableLock;
497 >        lock.lock();
498 >        try {
499 >            ExceptionNode[] t = exceptionTable;
500 >            int i = h & (t.length - 1);
501 >            ExceptionNode e = t[i];
502 >            ExceptionNode pred = null;
503 >            while (e != null) {
504 >                ExceptionNode next = e.next;
505 >                if (e.get() == this) {
506 >                    if (pred == null)
507 >                        t[i] = next;
508 >                    else
509 >                        pred.next = next;
510 >                    break;
511 >                }
512 >                pred = e;
513 >                e = next;
514 >            }
515 >            expungeStaleExceptions();
516 >            status = 0;
517 >        } finally {
518 >            lock.unlock();
519 >        }
520 >    }
521 >
522 >    /**
523 >     * Returns a rethrowable exception for the given task, if
524 >     * available. To provide accurate stack traces, if the exception
525 >     * was not thrown by the current thread, we try to create a new
526 >     * exception of the same type as the one thrown, but with the
527 >     * recorded exception as its cause. If there is no such
528 >     * constructor, we instead try to use a no-arg constructor,
529 >     * followed by initCause, to the same effect. If none of these
530 >     * apply, or any fail due to other exceptions, we return the
531 >     * recorded exception, which is still correct, although it may
532 >     * contain a misleading stack trace.
533 >     *
534 >     * @return the exception, or null if none
535 >     */
536 >    private Throwable getThrowableException() {
537 >        if (status != EXCEPTIONAL)
538 >            return null;
539 >        int h = System.identityHashCode(this);
540 >        ExceptionNode e;
541 >        final ReentrantLock lock = exceptionTableLock;
542 >        lock.lock();
543 >        try {
544 >            expungeStaleExceptions();
545 >            ExceptionNode[] t = exceptionTable;
546 >            e = t[h & (t.length - 1)];
547 >            while (e != null && e.get() != this)
548 >                e = e.next;
549 >        } finally {
550 >            lock.unlock();
551 >        }
552 >        Throwable ex;
553 >        if (e == null || (ex = e.ex) == null)
554 >            return null;
555 >        if (e.thrower != Thread.currentThread().getId()) {
556 >            Class<? extends Throwable> ec = ex.getClass();
557              try {
558 <                synchronized (this) {
559 <                    if (UNSAFE.compareAndSwapInt(this, statusOffset, s,SIGNAL))
560 <                        wait(millis, 0);
558 >                Constructor<?> noArgCtor = null;
559 >                Constructor<?>[] cs = ec.getConstructors();// public ctors only
560 >                for (int i = 0; i < cs.length; ++i) {
561 >                    Constructor<?> c = cs[i];
562 >                    Class<?>[] ps = c.getParameterTypes();
563 >                    if (ps.length == 0)
564 >                        noArgCtor = c;
565 >                    else if (ps.length == 1 && ps[0] == Throwable.class)
566 >                        return (Throwable)(c.newInstance(ex));
567 >                }
568 >                if (noArgCtor != null) {
569 >                    Throwable wx = (Throwable)(noArgCtor.newInstance());
570 >                    wx.initCause(ex);
571 >                    return wx;
572                  }
573 <            } catch (InterruptedException ie) {
250 <                cancelIfTerminating();
573 >            } catch (Exception ignore) {
574              }
252            s = status;
575          }
576 <        return s;
576 >        return ex;
577      }
578  
579      /**
580 <     * Blocks a non-worker-thread until completion.
580 >     * Poll stale refs and remove them. Call only while holding lock.
581       */
582 <    private void externalAwaitDone() {
583 <        int s;
584 <        while ((s = status) >= 0) {
585 <            synchronized (this) {
586 <                if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)){
587 <                    boolean interrupted = false;
588 <                    while (status >= 0) {
589 <                        try {
590 <                            wait();
591 <                        } catch (InterruptedException ie) {
592 <                            interrupted = true;
593 <                        }
582 >    private static void expungeStaleExceptions() {
583 >        for (Object x; (x = exceptionTableRefQueue.poll()) != null;) {
584 >            if (x instanceof ExceptionNode) {
585 >                ForkJoinTask<?> key = ((ExceptionNode)x).get();
586 >                ExceptionNode[] t = exceptionTable;
587 >                int i = System.identityHashCode(key) & (t.length - 1);
588 >                ExceptionNode e = t[i];
589 >                ExceptionNode pred = null;
590 >                while (e != null) {
591 >                    ExceptionNode next = e.next;
592 >                    if (e == x) {
593 >                        if (pred == null)
594 >                            t[i] = next;
595 >                        else
596 >                            pred.next = next;
597 >                        break;
598                      }
599 <                    if (interrupted)
600 <                        Thread.currentThread().interrupt();
275 <                    break;
599 >                    pred = e;
600 >                    e = next;
601                  }
602              }
603          }
604      }
605  
606      /**
607 <     * Unless done, calls exec and records status if completed, but
608 <     * doesn't wait for completion otherwise. Primary execution method
284 <     * for ForkJoinWorkerThread.
607 >     * If lock is available, poll stale refs and remove them.
608 >     * Called from ForkJoinPool when pools become quiescent.
609       */
610 <    final void quietlyExec() {
611 <        try {
612 <            if (status < 0 || !exec())
613 <                return;
614 <        } catch (Throwable rex) {
615 <            setExceptionalCompletion(rex);
616 <            return;
610 >    static final void helpExpungeStaleExceptions() {
611 >        final ReentrantLock lock = exceptionTableLock;
612 >        if (lock.tryLock()) {
613 >            try {
614 >                expungeStaleExceptions();
615 >            } finally {
616 >                lock.unlock();
617 >            }
618          }
619 <        setCompletion(NORMAL); // must be outside try block
619 >    }
620 >
621 >    /**
622 >     * Report the result of invoke or join; called only upon
623 >     * non-normal return of internal versions.
624 >     */
625 >    private V reportResult() {
626 >        int s; Throwable ex;
627 >        if ((s = status) == CANCELLED)
628 >            throw new CancellationException();
629 >        if (s == EXCEPTIONAL && (ex = getThrowableException()) != null)
630 >            U.throwException(ex);
631 >        return getRawResult();
632      }
633  
634      // public methods
# Line 307 | Line 644 | public abstract class ForkJoinTask<V> im
644       * #isDone} returning {@code true}.
645       *
646       * <p>This method may be invoked only from within {@code
647 <     * ForkJoinTask} computations (as may be determined using method
647 >     * ForkJoinPool} computations (as may be determined using method
648       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
649       * result in exceptions or errors, possibly including {@code
650       * ClassCastException}.
# Line 315 | Line 652 | public abstract class ForkJoinTask<V> im
652       * @return {@code this}, to simplify usage
653       */
654      public final ForkJoinTask<V> fork() {
655 <        ((ForkJoinWorkerThread) Thread.currentThread())
656 <            .pushTask(this);
655 >        ForkJoinWorkerThread wt;
656 >        (wt = (ForkJoinWorkerThread)Thread.currentThread()).
657 >            workQueue.push(this, wt.pool);
658          return this;
659      }
660  
661      /**
662 <     * Returns the result of the computation when it {@link #isDone is done}.
663 <     * This method differs from {@link #get()} in that
662 >     * Returns the result of the computation when it {@link #isDone is
663 >     * done}.  This method differs from {@link #get()} in that
664       * abnormal completion results in {@code RuntimeException} or
665 <     * {@code Error}, not {@code ExecutionException}.
665 >     * {@code Error}, not {@code ExecutionException}, and that
666 >     * interrupts of the calling thread do <em>not</em> cause the
667 >     * method to abruptly return by throwing {@code
668 >     * InterruptedException}.
669       *
670       * @return the computed result
671       */
672      public final V join() {
673 <        quietlyJoin();
674 <        Throwable ex;
675 <        if (status < NORMAL && (ex = getException()) != null)
676 <            UNSAFE.throwException(ex);
336 <        return getRawResult();
673 >        if (doJoin() != NORMAL)
674 >            return reportResult();
675 >        else
676 >            return getRawResult();
677      }
678  
679      /**
# Line 345 | Line 685 | public abstract class ForkJoinTask<V> im
685       * @return the computed result
686       */
687      public final V invoke() {
688 <        quietlyInvoke();
689 <        Throwable ex;
690 <        if (status < NORMAL && (ex = getException()) != null)
691 <            UNSAFE.throwException(ex);
352 <        return getRawResult();
688 >        if (doInvoke() != NORMAL)
689 >            return reportResult();
690 >        else
691 >            return getRawResult();
692      }
693  
694      /**
# Line 366 | Line 705 | public abstract class ForkJoinTask<V> im
705       * unprocessed.
706       *
707       * <p>This method may be invoked only from within {@code
708 <     * ForkJoinTask} computations (as may be determined using method
708 >     * ForkJoinPool} computations (as may be determined using method
709       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
710       * result in exceptions or errors, possibly including {@code
711       * ClassCastException}.
# Line 394 | Line 733 | public abstract class ForkJoinTask<V> im
733       * normally or exceptionally, or left unprocessed.
734       *
735       * <p>This method may be invoked only from within {@code
736 <     * ForkJoinTask} computations (as may be determined using method
736 >     * ForkJoinPool} computations (as may be determined using method
737       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
738       * result in exceptions or errors, possibly including {@code
739       * ClassCastException}.
# Line 413 | Line 752 | public abstract class ForkJoinTask<V> im
752              }
753              else if (i != 0)
754                  t.fork();
755 <            else {
756 <                t.quietlyInvoke();
418 <                if (ex == null && t.status < NORMAL)
419 <                    ex = t.getException();
420 <            }
755 >            else if (t.doInvoke() < NORMAL && ex == null)
756 >                ex = t.getException();
757          }
758          for (int i = 1; i <= last; ++i) {
759              ForkJoinTask<?> t = tasks[i];
760              if (t != null) {
761                  if (ex != null)
762                      t.cancel(false);
763 <                else {
764 <                    t.quietlyJoin();
429 <                    if (ex == null && t.status < NORMAL)
430 <                        ex = t.getException();
431 <                }
763 >                else if (t.doJoin() < NORMAL)
764 >                    ex = t.getException();
765              }
766          }
767          if (ex != null)
768 <            UNSAFE.throwException(ex);
768 >            U.throwException(ex);
769      }
770  
771      /**
# Line 449 | Line 782 | public abstract class ForkJoinTask<V> im
782       * unprocessed.
783       *
784       * <p>This method may be invoked only from within {@code
785 <     * ForkJoinTask} computations (as may be determined using method
785 >     * ForkJoinPool} computations (as may be determined using method
786       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
787       * result in exceptions or errors, possibly including {@code
788       * ClassCastException}.
# Line 476 | Line 809 | public abstract class ForkJoinTask<V> im
809              }
810              else if (i != 0)
811                  t.fork();
812 <            else {
813 <                t.quietlyInvoke();
481 <                if (ex == null && t.status < NORMAL)
482 <                    ex = t.getException();
483 <            }
812 >            else if (t.doInvoke() < NORMAL && ex == null)
813 >                ex = t.getException();
814          }
815          for (int i = 1; i <= last; ++i) {
816              ForkJoinTask<?> t = ts.get(i);
817              if (t != null) {
818                  if (ex != null)
819                      t.cancel(false);
820 <                else {
821 <                    t.quietlyJoin();
492 <                    if (ex == null && t.status < NORMAL)
493 <                        ex = t.getException();
494 <                }
820 >                else if (t.doJoin() < NORMAL)
821 >                    ex = t.getException();
822              }
823          }
824          if (ex != null)
825 <            UNSAFE.throwException(ex);
825 >            U.throwException(ex);
826          return tasks;
827      }
828  
829      /**
830       * Attempts to cancel execution of this task. This attempt will
831 <     * fail if the task has already completed, has already been
832 <     * cancelled, or could not be cancelled for some other reason. If
833 <     * successful, and this task has not started when cancel is
834 <     * called, execution of this task is suppressed, {@link
835 <     * #isCancelled} will report true, and {@link #join} will result
836 <     * in a {@code CancellationException} being thrown.
831 >     * fail if the task has already completed or could not be
832 >     * cancelled for some other reason. If successful, and this task
833 >     * has not started when {@code cancel} is called, execution of
834 >     * this task is suppressed. After this method returns
835 >     * successfully, unless there is an intervening call to {@link
836 >     * #reinitialize}, subsequent calls to {@link #isCancelled},
837 >     * {@link #isDone}, and {@code cancel} will return {@code true}
838 >     * and calls to {@link #join} and related methods will result in
839 >     * {@code CancellationException}.
840       *
841       * <p>This method may be overridden in subclasses, but if so, must
842 <     * still ensure that these minimal properties hold. In particular,
843 <     * the {@code cancel} method itself must not throw exceptions.
842 >     * still ensure that these properties hold. In particular, the
843 >     * {@code cancel} method itself must not throw exceptions.
844       *
845       * <p>This method is designed to be invoked by <em>other</em>
846       * tasks. To terminate the current task, you can just return or
847       * throw an unchecked exception from its computation method, or
848       * invoke {@link #completeExceptionally}.
849       *
850 <     * @param mayInterruptIfRunning this value is ignored in the
851 <     * default implementation because tasks are not
852 <     * cancelled via interruption
850 >     * @param mayInterruptIfRunning this value has no effect in the
851 >     * default implementation because interrupts are not used to
852 >     * control cancellation.
853       *
854       * @return {@code true} if this task is now cancelled
855       */
856      public boolean cancel(boolean mayInterruptIfRunning) {
857 <        setCompletion(CANCELLED);
528 <        return status == CANCELLED;
529 <    }
530 <
531 <    /**
532 <     * Cancels, ignoring any exceptions thrown by cancel. Used during
533 <     * worker and pool shutdown. Cancel is spec'ed not to throw any
534 <     * exceptions, but if it does anyway, we have no recourse during
535 <     * shutdown, so guard against this case.
536 <     */
537 <    final void cancelIgnoringExceptions() {
538 <        try {
539 <            cancel(false);
540 <        } catch (Throwable ignore) {
541 <        }
542 <    }
543 <
544 <    /**
545 <     * Cancels if current thread is a terminating worker thread,
546 <     * ignoring any exceptions thrown by cancel.
547 <     */
548 <    final void cancelIfTerminating() {
549 <        Thread t = Thread.currentThread();
550 <        if ((t instanceof ForkJoinWorkerThread) &&
551 <            ((ForkJoinWorkerThread) t).isTerminating()) {
552 <            try {
553 <                cancel(false);
554 <            } catch (Throwable ignore) {
555 <            }
556 <        }
857 >        return setCompletion(CANCELLED) == CANCELLED;
858      }
859  
860      public final boolean isDone() {
# Line 595 | Line 896 | public abstract class ForkJoinTask<V> im
896          int s = status;
897          return ((s >= NORMAL)    ? null :
898                  (s == CANCELLED) ? new CancellationException() :
899 <                exceptionMap.get(this));
899 >                getThrowableException());
900      }
901  
902      /**
# Line 653 | Line 954 | public abstract class ForkJoinTask<V> im
954       * member of a ForkJoinPool and was interrupted while waiting
955       */
956      public final V get() throws InterruptedException, ExecutionException {
957 <        int s;
958 <        if (Thread.currentThread() instanceof ForkJoinWorkerThread) {
959 <            quietlyJoin();
960 <            s = status;
961 <        }
962 <        else {
963 <            while ((s = status) >= 0) {
663 <                synchronized (this) { // interruptible form of awaitDone
664 <                    if (UNSAFE.compareAndSwapInt(this, statusOffset,
665 <                                                 s, SIGNAL)) {
666 <                        while (status >= 0)
667 <                            wait();
668 <                    }
669 <                }
670 <            }
671 <        }
672 <        if (s < NORMAL) {
673 <            Throwable ex;
674 <            if (s == CANCELLED)
675 <                throw new CancellationException();
676 <            if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
677 <                throw new ExecutionException(ex);
678 <        }
957 >        int s = (Thread.currentThread() instanceof ForkJoinWorkerThread) ?
958 >            doJoin() : externalInterruptibleAwaitDone(0L);
959 >        Throwable ex;
960 >        if (s == CANCELLED)
961 >            throw new CancellationException();
962 >        if (s == EXCEPTIONAL && (ex = getThrowableException()) != null)
963 >            throw new ExecutionException(ex);
964          return getRawResult();
965      }
966  
# Line 695 | Line 980 | public abstract class ForkJoinTask<V> im
980       */
981      public final V get(long timeout, TimeUnit unit)
982          throws InterruptedException, ExecutionException, TimeoutException {
983 +        // Messy in part because we measure in nanos, but wait in millis
984 +        int s; long millis, nanos;
985          Thread t = Thread.currentThread();
986 <        ForkJoinPool pool;
987 <        if (t instanceof ForkJoinWorkerThread) {
988 <            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
989 <            if (status >= 0 && w.unpushTask(this))
990 <                quietlyExec();
704 <            pool = w.pool;
986 >        if (!(t instanceof ForkJoinWorkerThread)) {
987 >            if ((millis = unit.toMillis(timeout)) > 0L)
988 >                s = externalInterruptibleAwaitDone(millis);
989 >            else
990 >                s = status;
991          }
992 <        else
993 <            pool = null;
994 <        /*
995 <         * Timed wait loop intermixes cases for FJ (pool != null) and
996 <         * non FJ threads. For FJ, decrement pool count but don't try
997 <         * for replacement; increment count on completion. For non-FJ,
998 <         * deal with interrupts. This is messy, but a little less so
999 <         * than is splitting the FJ and nonFJ cases.
1000 <         */
1001 <        boolean interrupted = false;
1002 <        boolean dec = false; // true if pool count decremented
1003 <        long nanos = unit.toNanos(timeout);
1004 <        for (;;) {
1005 <            if (pool == null && Thread.interrupted()) {
720 <                interrupted = true;
721 <                break;
722 <            }
723 <            int s = status;
724 <            if (s < 0)
725 <                break;
726 <            if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)) {
727 <                long startTime = System.nanoTime();
728 <                long nt; // wait time
729 <                while (status >= 0 &&
730 <                       (nt = nanos - (System.nanoTime() - startTime)) > 0) {
731 <                    if (pool != null && !dec)
732 <                        dec = pool.tryDecrementRunningCount();
992 >        else if ((s = status) >= 0 && (nanos = unit.toNanos(timeout)) > 0L) {
993 >            long deadline = System.nanoTime() + nanos;
994 >            ForkJoinWorkerThread wt = (ForkJoinWorkerThread)t;
995 >            ForkJoinPool.WorkQueue w = wt.workQueue;
996 >            ForkJoinPool p = wt.pool;
997 >            if (w.tryUnpush(this))
998 >                doExec();
999 >            boolean blocking = false;
1000 >            try {
1001 >                while ((s = status) >= 0) {
1002 >                    if (w.runState < 0)
1003 >                        cancelIgnoringExceptions(this);
1004 >                    else if (!blocking)
1005 >                        blocking = p.tryCompensate();
1006                      else {
1007 <                        long ms = nt / 1000000;
1008 <                        int ns = (int) (nt % 1000000);
1009 <                        try {
1010 <                            synchronized (this) {
1011 <                                if (status >= 0)
1012 <                                    wait(ms, ns);
1013 <                            }
1014 <                        } catch (InterruptedException ie) {
1015 <                            if (pool != null)
743 <                                cancelIfTerminating();
744 <                            else {
745 <                                interrupted = true;
746 <                                break;
1007 >                        millis = TimeUnit.NANOSECONDS.toMillis(nanos);
1008 >                        if (millis > 0L &&
1009 >                            U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
1010 >                            try {
1011 >                                synchronized (this) {
1012 >                                    if (status >= 0)
1013 >                                        wait(millis);
1014 >                                }
1015 >                            } catch (InterruptedException ie) {
1016                              }
1017                          }
1018 +                        if ((s = status) < 0 ||
1019 +                            (nanos = deadline - System.nanoTime()) <= 0L)
1020 +                            break;
1021                      }
1022                  }
1023 <                break;
1023 >            } finally {
1024 >                if (blocking)
1025 >                    p.incrementActiveCount();
1026              }
1027          }
1028 <        if (pool != null && dec)
755 <            pool.incrementRunningCount();
756 <        if (interrupted)
757 <            throw new InterruptedException();
758 <        int es = status;
759 <        if (es != NORMAL) {
1028 >        if (s != NORMAL) {
1029              Throwable ex;
1030 <            if (es == CANCELLED)
1030 >            if (s == CANCELLED)
1031                  throw new CancellationException();
1032 <            if (es == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
1032 >            if (s != EXCEPTIONAL)
1033 >                throw new TimeoutException();
1034 >            if ((ex = getThrowableException()) != null)
1035                  throw new ExecutionException(ex);
765            throw new TimeoutException();
1036          }
1037          return getRawResult();
1038      }
# Line 774 | Line 1044 | public abstract class ForkJoinTask<V> im
1044       * known to have aborted.
1045       */
1046      public final void quietlyJoin() {
1047 <        Thread t;
778 <        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
779 <            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
780 <            if (status >= 0) {
781 <                if (w.unpushTask(this)) {
782 <                    boolean completed;
783 <                    try {
784 <                        completed = exec();
785 <                    } catch (Throwable rex) {
786 <                        setExceptionalCompletion(rex);
787 <                        return;
788 <                    }
789 <                    if (completed) {
790 <                        setCompletion(NORMAL);
791 <                        return;
792 <                    }
793 <                }
794 <                w.joinTask(this);
795 <            }
796 <        }
797 <        else
798 <            externalAwaitDone();
1047 >        doJoin();
1048      }
1049  
1050      /**
# Line 804 | Line 1053 | public abstract class ForkJoinTask<V> im
1053       * exception.
1054       */
1055      public final void quietlyInvoke() {
1056 <        if (status >= 0) {
808 <            boolean completed;
809 <            try {
810 <                completed = exec();
811 <            } catch (Throwable rex) {
812 <                setExceptionalCompletion(rex);
813 <                return;
814 <            }
815 <            if (completed)
816 <                setCompletion(NORMAL);
817 <            else
818 <                quietlyJoin();
819 <        }
1056 >        doInvoke();
1057      }
1058  
1059      /**
# Line 827 | Line 1064 | public abstract class ForkJoinTask<V> im
1064       * processed.
1065       *
1066       * <p>This method may be invoked only from within {@code
1067 <     * ForkJoinTask} computations (as may be determined using method
1067 >     * ForkJoinPool} computations (as may be determined using method
1068       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1069       * result in exceptions or errors, possibly including {@code
1070       * ClassCastException}.
1071       */
1072      public static void helpQuiesce() {
1073 <        ((ForkJoinWorkerThread) Thread.currentThread())
1074 <            .helpQuiescePool();
1073 >        ForkJoinWorkerThread w =
1074 >            (ForkJoinWorkerThread)Thread.currentThread();
1075 >        w.pool.helpQuiescePool(w.workQueue);
1076      }
1077  
1078      /**
# Line 846 | Line 1084 | public abstract class ForkJoinTask<V> im
1084       * under any other usage conditions are not guaranteed.
1085       * This method may be useful when executing
1086       * pre-constructed trees of subtasks in loops.
1087 +     *
1088 +     * <p>Upon completion of this method, {@code isDone()} reports
1089 +     * {@code false}, and {@code getException()} reports {@code
1090 +     * null}. However, the value returned by {@code getRawResult} is
1091 +     * unaffected. To clear this value, you can invoke {@code
1092 +     * setRawResult(null)}.
1093       */
1094      public void reinitialize() {
1095          if (status == EXCEPTIONAL)
1096 <            exceptionMap.remove(this);
1097 <        status = 0;
1096 >            clearExceptionalCompletion();
1097 >        else
1098 >            status = 0;
1099      }
1100  
1101      /**
# Line 867 | Line 1112 | public abstract class ForkJoinTask<V> im
1112      }
1113  
1114      /**
1115 <     * Returns {@code true} if the current thread is executing as a
1116 <     * ForkJoinPool computation.
1115 >     * Returns {@code true} if the current thread is a {@link
1116 >     * ForkJoinWorkerThread} executing as a ForkJoinPool computation.
1117       *
1118 <     * @return {@code true} if the current thread is executing as a
1119 <     * ForkJoinPool computation, or false otherwise
1118 >     * @return {@code true} if the current thread is a {@link
1119 >     * ForkJoinWorkerThread} executing as a ForkJoinPool computation,
1120 >     * or {@code false} otherwise
1121       */
1122      public static boolean inForkJoinPool() {
1123          return Thread.currentThread() instanceof ForkJoinWorkerThread;
# Line 886 | Line 1132 | public abstract class ForkJoinTask<V> im
1132       * were not, stolen.
1133       *
1134       * <p>This method may be invoked only from within {@code
1135 <     * ForkJoinTask} computations (as may be determined using method
1135 >     * ForkJoinPool} computations (as may be determined using method
1136       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1137       * result in exceptions or errors, possibly including {@code
1138       * ClassCastException}.
# Line 894 | Line 1140 | public abstract class ForkJoinTask<V> im
1140       * @return {@code true} if unforked
1141       */
1142      public boolean tryUnfork() {
1143 <        return ((ForkJoinWorkerThread) Thread.currentThread())
1144 <            .unpushTask(this);
1143 >        return ((ForkJoinWorkerThread)Thread.currentThread())
1144 >            .workQueue.tryUnpush(this);
1145      }
1146  
1147      /**
# Line 905 | Line 1151 | public abstract class ForkJoinTask<V> im
1151       * fork other tasks.
1152       *
1153       * <p>This method may be invoked only from within {@code
1154 <     * ForkJoinTask} computations (as may be determined using method
1154 >     * ForkJoinPool} computations (as may be determined using method
1155       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1156       * result in exceptions or errors, possibly including {@code
1157       * ClassCastException}.
# Line 914 | Line 1160 | public abstract class ForkJoinTask<V> im
1160       */
1161      public static int getQueuedTaskCount() {
1162          return ((ForkJoinWorkerThread) Thread.currentThread())
1163 <            .getQueueSize();
1163 >            .workQueue.queueSize();
1164      }
1165  
1166      /**
# Line 928 | Line 1174 | public abstract class ForkJoinTask<V> im
1174       * exceeded.
1175       *
1176       * <p>This method may be invoked only from within {@code
1177 <     * ForkJoinTask} computations (as may be determined using method
1177 >     * ForkJoinPool} computations (as may be determined using method
1178       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1179       * result in exceptions or errors, possibly including {@code
1180       * ClassCastException}.
# Line 936 | Line 1182 | public abstract class ForkJoinTask<V> im
1182       * @return the surplus number of tasks, which may be negative
1183       */
1184      public static int getSurplusQueuedTaskCount() {
1185 <        return ((ForkJoinWorkerThread) Thread.currentThread())
1186 <            .getEstimatedSurplusTaskCount();
1185 >        /*
1186 >         * The aim of this method is to return a cheap heuristic guide
1187 >         * for task partitioning when programmers, frameworks, tools,
1188 >         * or languages have little or no idea about task granularity.
1189 >         * In essence by offering this method, we ask users only about
1190 >         * tradeoffs in overhead vs expected throughput and its
1191 >         * variance, rather than how finely to partition tasks.
1192 >         *
1193 >         * In a steady state strict (tree-structured) computation,
1194 >         * each thread makes available for stealing enough tasks for
1195 >         * other threads to remain active. Inductively, if all threads
1196 >         * play by the same rules, each thread should make available
1197 >         * only a constant number of tasks.
1198 >         *
1199 >         * The minimum useful constant is just 1. But using a value of
1200 >         * 1 would require immediate replenishment upon each steal to
1201 >         * maintain enough tasks, which is infeasible.  Further,
1202 >         * partitionings/granularities of offered tasks should
1203 >         * minimize steal rates, which in general means that threads
1204 >         * nearer the top of computation tree should generate more
1205 >         * than those nearer the bottom. In perfect steady state, each
1206 >         * thread is at approximately the same level of computation
1207 >         * tree. However, producing extra tasks amortizes the
1208 >         * uncertainty of progress and diffusion assumptions.
1209 >         *
1210 >         * So, users will want to use values larger, but not much
1211 >         * larger than 1 to both smooth over transient shortages and
1212 >         * hedge against uneven progress; as traded off against the
1213 >         * cost of extra task overhead. We leave the user to pick a
1214 >         * threshold value to compare with the results of this call to
1215 >         * guide decisions, but recommend values such as 3.
1216 >         *
1217 >         * When all threads are active, it is on average OK to
1218 >         * estimate surplus strictly locally. In steady-state, if one
1219 >         * thread is maintaining say 2 surplus tasks, then so are
1220 >         * others. So we can just use estimated queue length.
1221 >         * However, this strategy alone leads to serious mis-estimates
1222 >         * in some non-steady-state conditions (ramp-up, ramp-down,
1223 >         * other stalls). We can detect many of these by further
1224 >         * considering the number of "idle" threads, that are known to
1225 >         * have zero queued tasks, so compensate by a factor of
1226 >         * (#idle/#active) threads.
1227 >         */
1228 >        ForkJoinWorkerThread w =
1229 >            (ForkJoinWorkerThread)Thread.currentThread();
1230 >        return w.workQueue.queueSize() - w.pool.idlePerActive();
1231      }
1232  
1233      // Extension methods
# Line 986 | Line 1276 | public abstract class ForkJoinTask<V> im
1276       * otherwise.
1277       *
1278       * <p>This method may be invoked only from within {@code
1279 <     * ForkJoinTask} computations (as may be determined using method
1279 >     * ForkJoinPool} computations (as may be determined using method
1280       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1281       * result in exceptions or errors, possibly including {@code
1282       * ClassCastException}.
# Line 994 | Line 1284 | public abstract class ForkJoinTask<V> im
1284       * @return the next task, or {@code null} if none are available
1285       */
1286      protected static ForkJoinTask<?> peekNextLocalTask() {
1287 <        return ((ForkJoinWorkerThread) Thread.currentThread())
998 <            .peekTask();
1287 >        return ((ForkJoinWorkerThread) Thread.currentThread()).workQueue.peek();
1288      }
1289  
1290      /**
# Line 1005 | Line 1294 | public abstract class ForkJoinTask<V> im
1294       * be useful otherwise.
1295       *
1296       * <p>This method may be invoked only from within {@code
1297 <     * ForkJoinTask} computations (as may be determined using method
1297 >     * ForkJoinPool} computations (as may be determined using method
1298       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1299       * result in exceptions or errors, possibly including {@code
1300       * ClassCastException}.
# Line 1014 | Line 1303 | public abstract class ForkJoinTask<V> im
1303       */
1304      protected static ForkJoinTask<?> pollNextLocalTask() {
1305          return ((ForkJoinWorkerThread) Thread.currentThread())
1306 <            .pollLocalTask();
1306 >            .workQueue.nextLocalTask();
1307      }
1308  
1309      /**
# Line 1028 | Line 1317 | public abstract class ForkJoinTask<V> im
1317       * otherwise.
1318       *
1319       * <p>This method may be invoked only from within {@code
1320 <     * ForkJoinTask} computations (as may be determined using method
1320 >     * ForkJoinPool} computations (as may be determined using method
1321       * {@link #inForkJoinPool}).  Attempts to invoke in other contexts
1322       * result in exceptions or errors, possibly including {@code
1323       * ClassCastException}.
# Line 1036 | Line 1325 | public abstract class ForkJoinTask<V> im
1325       * @return a task, or {@code null} if none are available
1326       */
1327      protected static ForkJoinTask<?> pollTask() {
1328 <        return ((ForkJoinWorkerThread) Thread.currentThread())
1329 <            .pollTask();
1328 >        ForkJoinWorkerThread w =
1329 >            (ForkJoinWorkerThread)Thread.currentThread();
1330 >        return w.pool.nextTaskFor(w.workQueue);
1331 >    }
1332 >
1333 >    // Mark-bit operations
1334 >
1335 >    /**
1336 >     * Returns true if this task is marked.
1337 >     *
1338 >     * @return true if this task is marked
1339 >     * @since 1.8
1340 >     */
1341 >    public final boolean isMarkedForkJoinTask() {
1342 >        return (status & MARKED) != 0;
1343 >    }
1344 >
1345 >    /**
1346 >     * Atomically sets the mark on this task.
1347 >     *
1348 >     * @return true if this task was previously unmarked
1349 >     * @since 1.8
1350 >     */
1351 >    public final boolean markForkJoinTask() {
1352 >        for (int s;;) {
1353 >            if (((s = status) & MARKED) != 0)
1354 >                return false;
1355 >            if (U.compareAndSwapInt(this, STATUS, s, s | MARKED))
1356 >                return true;
1357 >        }
1358 >    }
1359 >
1360 >    /**
1361 >     * Atomically clears the mark on this task.
1362 >     *
1363 >     * @return true if this task was previously marked
1364 >     * @since 1.8
1365 >     */
1366 >    public final boolean unmarkForkJoinTask() {
1367 >        for (int s;;) {
1368 >            if (((s = status) & MARKED) == 0)
1369 >                return false;
1370 >            if (U.compareAndSwapInt(this, STATUS, s, s & ~MARKED))
1371 >                return true;
1372 >        }
1373      }
1374  
1375      /**
# Line 1138 | Line 1470 | public abstract class ForkJoinTask<V> im
1470      private static final long serialVersionUID = -7721805057305804111L;
1471  
1472      /**
1473 <     * Saves the state to a stream (that is, serializes it).
1473 >     * Saves this task to a stream (that is, serializes it).
1474       *
1475       * @serialData the current run status and the exception thrown
1476       * during execution, or {@code null} if none
1145     * @param s the stream
1477       */
1478      private void writeObject(java.io.ObjectOutputStream s)
1479          throws java.io.IOException {
# Line 1151 | Line 1482 | public abstract class ForkJoinTask<V> im
1482      }
1483  
1484      /**
1485 <     * Reconstitutes the instance from a stream (that is, deserializes it).
1155 <     *
1156 <     * @param s the stream
1485 >     * Reconstitutes this task from a stream (that is, deserializes it).
1486       */
1487      private void readObject(java.io.ObjectInputStream s)
1488          throws java.io.IOException, ClassNotFoundException {
1489          s.defaultReadObject();
1490          Object ex = s.readObject();
1491          if (ex != null)
1492 <            setExceptionalCompletion((Throwable) ex);
1492 >            setExceptionalCompletion((Throwable)ex);
1493      }
1494  
1495      // Unsafe mechanics
1496 <
1497 <    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1498 <    private static final long statusOffset =
1499 <        objectFieldOffset("status", ForkJoinTask.class);
1500 <
1501 <    private static long objectFieldOffset(String field, Class<?> klazz) {
1496 >    private static final sun.misc.Unsafe U;
1497 >    private static final long STATUS;
1498 >    static {
1499 >        exceptionTableLock = new ReentrantLock();
1500 >        exceptionTableRefQueue = new ReferenceQueue<Object>();
1501 >        exceptionTable = new ExceptionNode[EXCEPTION_MAP_CAPACITY];
1502          try {
1503 <            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1504 <        } catch (NoSuchFieldException e) {
1505 <            // Convert Exception to corresponding Error
1506 <            NoSuchFieldError error = new NoSuchFieldError(field);
1507 <            error.initCause(e);
1179 <            throw error;
1503 >            U = getUnsafe();
1504 >            STATUS = U.objectFieldOffset
1505 >                (ForkJoinTask.class.getDeclaredField("status"));
1506 >        } catch (Exception e) {
1507 >            throw new Error(e);
1508          }
1509      }
1510  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines