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.71 by dl, Tue Nov 23 10:51:18 2010 UTC vs.
Revision 1.85 by jsr166, Tue Jan 31 01:51: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
8   import java.io.Serializable;
9   import java.util.Collection;
11 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;
19 import java.util.concurrent.Executor;
20 import java.util.concurrent.ExecutorService;
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 44 | Line 42 | import java.util.concurrent.TimeoutExcep
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 82 | Line 93 | import java.util.concurrent.TimeoutExcep
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 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 118 | Line 136 | import java.util.concurrent.TimeoutExcep
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.
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 processed.
147 > * Also, completion based designs can use them to record that one
148 > * subtask has completed. (Method names for marking are bulky in part
149 > * 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
# Line 158 | 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
212       * single int to minimize footprint and to ensure atomicity (via
# Line 186 | 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 <
230 <    private static final int NORMAL      = -1;
231 <    private static final int CANCELLED   = -2;
232 <    private static final int EXCEPTIONAL = -3;
233 <    private static final int SIGNAL      =  1;
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      /**
236 <     * Table of exceptions thrown by tasks, to enable reporting by
237 <     * callers. Because exceptions are rare, we don't directly keep
238 <     * them with task objects, but instead use a weak ref table.  Note
199 <     * that cancellation exceptions don't appear in the table, but are
200 <     * instead recorded as status values.
201 <     * TODO: Use ConcurrentReferenceHashMap
202 <     */
203 <    static final Map<ForkJoinTask<?>, Throwable> exceptionMap =
204 <        Collections.synchronizedMap
205 <        (new WeakHashMap<ForkJoinTask<?>, Throwable>());
206 <
207 <    // Maintaining completion status
208 <
209 <    /**
210 <     * Marks completion and wakes up threads waiting to join this task,
211 <     * also clearing signal request bits.
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 void setCompletion(int completion) {
244 <        int s;
245 <        while ((s = status) >= 0) {
246 <            if (UNSAFE.compareAndSwapInt(this, statusOffset, s, completion)) {
247 <                if (s != 0)
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 <                break;
250 >                return completion;
251              }
252          }
253      }
254  
255      /**
256 <     * Records exception and sets exceptional completion.
257 <     *
258 <     * @return status on exit
259 <     */
260 <    private void setExceptionalCompletion(Throwable rex) {
261 <        exceptionMap.put(this, rex);
262 <        setCompletion(EXCEPTIONAL);
263 <    }
264 <
265 <    /**
266 <     * Blocks a worker thread until completed or timed out.  Called
267 <     * only by pool.
268 <     */
269 <    final void internalAwaitDone(long millis, int nanos) {
270 <        if (status >= 0) {
271 <            try {     // the odd construction reduces lock bias effects
272 <                synchronized (this) {
273 <                    if (status > 0 ||
274 <                        UNSAFE.compareAndSwapInt(this, statusOffset,
246 <                                                 0, SIGNAL))
247 <                        wait(millis, nanos);
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 >    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                  }
249            } catch (InterruptedException ie) {
250                cancelIfTerminating();
276              }
277          }
278 +        return s;
279      }
280  
281      /**
282       * Blocks a non-worker-thread until completion.
283 +     * @return status upon completion
284       */
285 <    private void externalAwaitDone() {
286 <        if (status >= 0) {
285 >    private int externalAwaitDone() {
286 >        int s;
287 >        if ((s = status) >= 0) {
288              boolean interrupted = false;
289 <            synchronized(this) {
262 <                int s;
289 >            synchronized (this) {
290                  while ((s = status) >= 0) {
291 <                    if (s == 0 &&
292 <                        !UNSAFE.compareAndSwapInt(this, statusOffset,
293 <                                                  0, SIGNAL))
294 <                        continue;
295 <                    try {
296 <                        wait();
270 <                    } catch (InterruptedException ie) {
271 <                        interrupted = true;
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 void externalInterruptibleAwaitDone(boolean timed, long nanos)
309 >    private int externalInterruptibleAwaitDone(long millis)
310          throws InterruptedException {
311 +        int s;
312          if (Thread.interrupted())
313              throw new InterruptedException();
314 <        if (status >= 0) {
315 <            long startTime = timed ? System.nanoTime() : 0L;
289 <            synchronized(this) {
290 <                int s;
314 >        if ((s = status) >= 0) {
315 >            synchronized (this) {
316                  while ((s = status) >= 0) {
317 <                    long nt;
318 <                    if (s == 0 &&
319 <                        !UNSAFE.compareAndSwapInt(this, statusOffset,
320 <                                                  0, SIGNAL))
321 <                        continue;
322 <                    else if (!timed)
323 <                        wait();
324 <                    else if ((nt = nanos - (System.nanoTime()-startTime)) > 0L)
325 <                        wait(nt / 1000000, (int)(nt % 1000000));
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 >
328 >
329 >    /**
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 >     * @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 int awaitJoin(ForkJoinPool.WorkQueue w, ForkJoinPool p) {
356 >        int s;
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; Thread t;
399 >        if ((s = doExec()) >= 0) {
400 >            if (!((t = Thread.currentThread()) instanceof ForkJoinWorkerThread))
401 >                s = externalAwaitDone();
402 >            else {
403 >                ForkJoinWorkerThread wt = (ForkJoinWorkerThread)t;
404 >                s = awaitJoin(wt.workQueue, wt.pool);
405 >            }
406 >        }
407 >        return s;
408 >    }
409 >
410 >    // Exception table support
411 >
412 >    /**
413 >     * Table of exceptions thrown by tasks, to enable reporting by
414 >     * callers. Because exceptions are rare, we don't directly keep
415 >     * them with task objects, but instead use a weak ref table.  Note
416 >     * that cancellation exceptions don't appear in the table, but are
417 >     * instead recorded as status values.
418 >     *
419 >     * Note: These statics are initialized below in static block.
420 >     */
421 >    private static final ExceptionNode[] exceptionTable;
422 >    private static final ReentrantLock exceptionTableLock;
423 >    private static final ReferenceQueue<Object> exceptionTableRefQueue;
424 >
425 >    /**
426 >     * Fixed capacity for exceptionTable.
427 >     */
428 >    private static final int EXCEPTION_MAP_CAPACITY = 32;
429 >
430 >    /**
431 >     * Key-value nodes for exception table.  The chained hash table
432 >     * uses identity comparisons, full locking, and weak references
433 >     * for keys. The table has a fixed capacity because it only
434 >     * maintains task exceptions long enough for joiners to access
435 >     * them, so should never become very large for sustained
436 >     * periods. However, since we do not know when the last joiner
437 >     * completes, we must use weak references and expunge them. We do
438 >     * so on each operation (hence full locking). Also, some thread in
439 >     * any ForkJoinPool will call helpExpungeStaleExceptions when its
440 >     * pool becomes isQuiescent.
441 >     */
442 >    static final class ExceptionNode extends WeakReference<ForkJoinTask<?>> {
443 >        final Throwable ex;
444 >        ExceptionNode next;
445 >        final long thrower;  // use id not ref to avoid weak cycles
446 >        ExceptionNode(ForkJoinTask<?> task, Throwable ex, ExceptionNode next) {
447 >            super(task, exceptionTableRefQueue);
448 >            this.ex = ex;
449 >            this.next = next;
450 >            this.thrower = Thread.currentThread().getId();
451 >        }
452 >    }
453 >
454 >    /**
455 >     * Records exception and sets exceptional completion.
456 >     *
457 >     * @return status on exit
458 >     */
459 >    private int setExceptionalCompletion(Throwable ex) {
460 >        int h = System.identityHashCode(this);
461 >        final ReentrantLock lock = exceptionTableLock;
462 >        lock.lock();
463 >        try {
464 >            expungeStaleExceptions();
465 >            ExceptionNode[] t = exceptionTable;
466 >            int i = h & (t.length - 1);
467 >            for (ExceptionNode e = t[i]; ; e = e.next) {
468 >                if (e == null) {
469 >                    t[i] = new ExceptionNode(this, ex, t[i]);
470 >                    break;
471 >                }
472 >                if (e.get() == this) // already present
473 >                    break;
474 >            }
475 >        } finally {
476 >            lock.unlock();
477 >        }
478 >        return setCompletion(EXCEPTIONAL);
479 >    }
480 >
481 >    /**
482 >     * Cancels, ignoring any exceptions thrown by cancel. Used during
483 >     * worker and pool shutdown. Cancel is spec'ed not to throw any
484 >     * exceptions, but if it does anyway, we have no recourse during
485 >     * shutdown, so guard against this case.
486 >     */
487 >    static final void cancelIgnoringExceptions(ForkJoinTask<?> t) {
488 >        if (t != null && t.status >= 0) {
489 >            try {
490 >                t.cancel(false);
491 >            } catch (Throwable ignore) {
492 >            }
493 >        }
494 >    }
495 >
496 >    /**
497 >     * Removes exception node and clears status
498 >     */
499 >    private void clearExceptionalCompletion() {
500 >        int h = System.identityHashCode(this);
501 >        final ReentrantLock lock = exceptionTableLock;
502 >        lock.lock();
503 >        try {
504 >            ExceptionNode[] t = exceptionTable;
505 >            int i = h & (t.length - 1);
506 >            ExceptionNode e = t[i];
507 >            ExceptionNode pred = null;
508 >            while (e != null) {
509 >                ExceptionNode next = e.next;
510 >                if (e.get() == this) {
511 >                    if (pred == null)
512 >                        t[i] = next;
513                      else
514 +                        pred.next = next;
515 +                    break;
516 +                }
517 +                pred = e;
518 +                e = next;
519 +            }
520 +            expungeStaleExceptions();
521 +            status = 0;
522 +        } finally {
523 +            lock.unlock();
524 +        }
525 +    }
526 +
527 +    /**
528 +     * Returns a rethrowable exception for the given task, if
529 +     * available. To provide accurate stack traces, if the exception
530 +     * was not thrown by the current thread, we try to create a new
531 +     * exception of the same type as the one thrown, but with the
532 +     * recorded exception as its cause. If there is no such
533 +     * constructor, we instead try to use a no-arg constructor,
534 +     * followed by initCause, to the same effect. If none of these
535 +     * apply, or any fail due to other exceptions, we return the
536 +     * recorded exception, which is still correct, although it may
537 +     * contain a misleading stack trace.
538 +     *
539 +     * @return the exception, or null if none
540 +     */
541 +    private Throwable getThrowableException() {
542 +        if (status != EXCEPTIONAL)
543 +            return null;
544 +        int h = System.identityHashCode(this);
545 +        ExceptionNode e;
546 +        final ReentrantLock lock = exceptionTableLock;
547 +        lock.lock();
548 +        try {
549 +            expungeStaleExceptions();
550 +            ExceptionNode[] t = exceptionTable;
551 +            e = t[h & (t.length - 1)];
552 +            while (e != null && e.get() != this)
553 +                e = e.next;
554 +        } finally {
555 +            lock.unlock();
556 +        }
557 +        Throwable ex;
558 +        if (e == null || (ex = e.ex) == null)
559 +            return null;
560 +        if (e.thrower != Thread.currentThread().getId()) {
561 +            Class<? extends Throwable> ec = ex.getClass();
562 +            try {
563 +                Constructor<?> noArgCtor = null;
564 +                Constructor<?>[] cs = ec.getConstructors();// public ctors only
565 +                for (int i = 0; i < cs.length; ++i) {
566 +                    Constructor<?> c = cs[i];
567 +                    Class<?>[] ps = c.getParameterTypes();
568 +                    if (ps.length == 0)
569 +                        noArgCtor = c;
570 +                    else if (ps.length == 1 && ps[0] == Throwable.class)
571 +                        return (Throwable)(c.newInstance(ex));
572 +                }
573 +                if (noArgCtor != null) {
574 +                    Throwable wx = (Throwable)(noArgCtor.newInstance());
575 +                    wx.initCause(ex);
576 +                    return wx;
577 +                }
578 +            } catch (Exception ignore) {
579 +            }
580 +        }
581 +        return ex;
582 +    }
583 +
584 +    /**
585 +     * Poll stale refs and remove them. Call only while holding lock.
586 +     */
587 +    private static void expungeStaleExceptions() {
588 +        for (Object x; (x = exceptionTableRefQueue.poll()) != null;) {
589 +            if (x instanceof ExceptionNode) {
590 +                ForkJoinTask<?> key = ((ExceptionNode)x).get();
591 +                ExceptionNode[] t = exceptionTable;
592 +                int i = System.identityHashCode(key) & (t.length - 1);
593 +                ExceptionNode e = t[i];
594 +                ExceptionNode pred = null;
595 +                while (e != null) {
596 +                    ExceptionNode next = e.next;
597 +                    if (e == x) {
598 +                        if (pred == null)
599 +                            t[i] = next;
600 +                        else
601 +                            pred.next = next;
602                          break;
603 +                    }
604 +                    pred = e;
605 +                    e = next;
606                  }
607              }
608          }
609      }
610  
611      /**
612 <     * Unless done, calls exec and records status if completed, but
613 <     * doesn't wait for completion otherwise. Primary execution method
311 <     * for ForkJoinWorkerThread.
612 >     * If lock is available, poll stale refs and remove them.
613 >     * Called from ForkJoinPool when pools become quiescent.
614       */
615 <    final void quietlyExec() {
616 <        try {
617 <            if (status < 0 || !exec())
618 <                return;
619 <        } catch (Throwable rex) {
620 <            setExceptionalCompletion(rex);
621 <            return;
615 >    static final void helpExpungeStaleExceptions() {
616 >        final ReentrantLock lock = exceptionTableLock;
617 >        if (lock.tryLock()) {
618 >            try {
619 >                expungeStaleExceptions();
620 >            } finally {
621 >                lock.unlock();
622 >            }
623          }
624 <        setCompletion(NORMAL); // must be outside try block
624 >    }
625 >
626 >    /**
627 >     * Report the result of invoke or join; called only upon
628 >     * non-normal return of internal versions.
629 >     */
630 >    private V reportResult() {
631 >        int s; Throwable ex;
632 >        if ((s = status) == CANCELLED)
633 >            throw new CancellationException();
634 >        if (s == EXCEPTIONAL && (ex = getThrowableException()) != null)
635 >            U.throwException(ex);
636 >        return getRawResult();
637      }
638  
639      // public methods
# Line 342 | Line 657 | public abstract class ForkJoinTask<V> im
657       * @return {@code this}, to simplify usage
658       */
659      public final ForkJoinTask<V> fork() {
660 <        ((ForkJoinWorkerThread) Thread.currentThread())
661 <            .pushTask(this);
660 >        ForkJoinWorkerThread wt;
661 >        (wt = (ForkJoinWorkerThread)Thread.currentThread()).
662 >            workQueue.push(this, wt.pool);
663          return this;
664      }
665  
# Line 359 | Line 675 | public abstract class ForkJoinTask<V> im
675       * @return the computed result
676       */
677      public final V join() {
678 <        quietlyJoin();
679 <        Throwable ex;
680 <        if (status < NORMAL && (ex = getException()) != null)
681 <            UNSAFE.throwException(ex);
366 <        return getRawResult();
678 >        if (doJoin() != NORMAL)
679 >            return reportResult();
680 >        else
681 >            return getRawResult();
682      }
683  
684      /**
# Line 375 | Line 690 | public abstract class ForkJoinTask<V> im
690       * @return the computed result
691       */
692      public final V invoke() {
693 <        quietlyInvoke();
694 <        Throwable ex;
695 <        if (status < NORMAL && (ex = getException()) != null)
696 <            UNSAFE.throwException(ex);
382 <        return getRawResult();
693 >        if (doInvoke() != NORMAL)
694 >            return reportResult();
695 >        else
696 >            return getRawResult();
697      }
698  
699      /**
# Line 443 | Line 757 | public abstract class ForkJoinTask<V> im
757              }
758              else if (i != 0)
759                  t.fork();
760 <            else {
761 <                t.quietlyInvoke();
448 <                if (ex == null && t.status < NORMAL)
449 <                    ex = t.getException();
450 <            }
760 >            else if (t.doInvoke() < NORMAL && ex == null)
761 >                ex = t.getException();
762          }
763          for (int i = 1; i <= last; ++i) {
764              ForkJoinTask<?> t = tasks[i];
765              if (t != null) {
766                  if (ex != null)
767                      t.cancel(false);
768 <                else {
769 <                    t.quietlyJoin();
459 <                    if (ex == null && t.status < NORMAL)
460 <                        ex = t.getException();
461 <                }
768 >                else if (t.doJoin() < NORMAL)
769 >                    ex = t.getException();
770              }
771          }
772          if (ex != null)
773 <            UNSAFE.throwException(ex);
773 >            U.throwException(ex);
774      }
775  
776      /**
# Line 506 | Line 814 | public abstract class ForkJoinTask<V> im
814              }
815              else if (i != 0)
816                  t.fork();
817 <            else {
818 <                t.quietlyInvoke();
511 <                if (ex == null && t.status < NORMAL)
512 <                    ex = t.getException();
513 <            }
817 >            else if (t.doInvoke() < NORMAL && ex == null)
818 >                ex = t.getException();
819          }
820          for (int i = 1; i <= last; ++i) {
821              ForkJoinTask<?> t = ts.get(i);
822              if (t != null) {
823                  if (ex != null)
824                      t.cancel(false);
825 <                else {
826 <                    t.quietlyJoin();
522 <                    if (ex == null && t.status < NORMAL)
523 <                        ex = t.getException();
524 <                }
825 >                else if (t.doJoin() < NORMAL)
826 >                    ex = t.getException();
827              }
828          }
829          if (ex != null)
830 <            UNSAFE.throwException(ex);
830 >            U.throwException(ex);
831          return tasks;
832      }
833  
# Line 557 | Line 859 | public abstract class ForkJoinTask<V> im
859       * @return {@code true} if this task is now cancelled
860       */
861      public boolean cancel(boolean mayInterruptIfRunning) {
862 <        setCompletion(CANCELLED);
561 <        return status == CANCELLED;
562 <    }
563 <
564 <    /**
565 <     * Cancels, ignoring any exceptions thrown by cancel. Used during
566 <     * worker and pool shutdown. Cancel is spec'ed not to throw any
567 <     * exceptions, but if it does anyway, we have no recourse during
568 <     * shutdown, so guard against this case.
569 <     */
570 <    final void cancelIgnoringExceptions() {
571 <        try {
572 <            cancel(false);
573 <        } catch (Throwable ignore) {
574 <        }
575 <    }
576 <
577 <    /**
578 <     * Cancels if current thread is a terminating worker thread,
579 <     * ignoring any exceptions thrown by cancel.
580 <     */
581 <    final void cancelIfTerminating() {
582 <        Thread t = Thread.currentThread();
583 <        if ((t instanceof ForkJoinWorkerThread) &&
584 <            ((ForkJoinWorkerThread) t).isTerminating()) {
585 <            try {
586 <                cancel(false);
587 <            } catch (Throwable ignore) {
588 <            }
589 <        }
862 >        return setCompletion(CANCELLED) == CANCELLED;
863      }
864  
865      public final boolean isDone() {
# Line 628 | Line 901 | public abstract class ForkJoinTask<V> im
901          int s = status;
902          return ((s >= NORMAL)    ? null :
903                  (s == CANCELLED) ? new CancellationException() :
904 <                exceptionMap.get(this));
904 >                getThrowableException());
905      }
906  
907      /**
# Line 686 | Line 959 | public abstract class ForkJoinTask<V> im
959       * member of a ForkJoinPool and was interrupted while waiting
960       */
961      public final V get() throws InterruptedException, ExecutionException {
962 <        Thread t = Thread.currentThread();
963 <        if (t instanceof ForkJoinWorkerThread)
964 <            quietlyJoin();
965 <        else
966 <            externalInterruptibleAwaitDone(false, 0L);
967 <        int s = status;
968 <        if (s != NORMAL) {
696 <            Throwable ex;
697 <            if (s == CANCELLED)
698 <                throw new CancellationException();
699 <            if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
700 <                throw new ExecutionException(ex);
701 <        }
962 >        int s = (Thread.currentThread() instanceof ForkJoinWorkerThread) ?
963 >            doJoin() : externalInterruptibleAwaitDone(0L);
964 >        Throwable ex;
965 >        if (s == CANCELLED)
966 >            throw new CancellationException();
967 >        if (s == EXCEPTIONAL && (ex = getThrowableException()) != null)
968 >            throw new ExecutionException(ex);
969          return getRawResult();
970      }
971  
# Line 718 | Line 985 | public abstract class ForkJoinTask<V> im
985       */
986      public final V get(long timeout, TimeUnit unit)
987          throws InterruptedException, ExecutionException, TimeoutException {
988 <        long nanos = unit.toNanos(timeout);
988 >        // Messy in part because we measure in nanos, but wait in millis
989 >        int s; long millis, nanos;
990          Thread t = Thread.currentThread();
991 <        if (t instanceof ForkJoinWorkerThread)
992 <            ((ForkJoinWorkerThread)t).joinTask(this, true, nanos);
993 <        else
994 <            externalInterruptibleAwaitDone(true, nanos);
995 <        int s = status;
991 >        if (!(t instanceof ForkJoinWorkerThread)) {
992 >            if ((millis = unit.toMillis(timeout)) > 0L)
993 >                s = externalInterruptibleAwaitDone(millis);
994 >            else
995 >                s = status;
996 >        }
997 >        else if ((s = status) >= 0 && (nanos = unit.toNanos(timeout)) > 0L) {
998 >            long deadline = System.nanoTime() + nanos;
999 >            ForkJoinWorkerThread wt = (ForkJoinWorkerThread)t;
1000 >            ForkJoinPool.WorkQueue w = wt.workQueue;
1001 >            ForkJoinPool p = wt.pool;
1002 >            if (w.tryUnpush(this))
1003 >                doExec();
1004 >            boolean blocking = false;
1005 >            try {
1006 >                while ((s = status) >= 0) {
1007 >                    if (w.runState < 0)
1008 >                        cancelIgnoringExceptions(this);
1009 >                    else if (!blocking)
1010 >                        blocking = p.tryCompensate();
1011 >                    else {
1012 >                        millis = TimeUnit.NANOSECONDS.toMillis(nanos);
1013 >                        if (millis > 0L &&
1014 >                            U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
1015 >                            try {
1016 >                                synchronized (this) {
1017 >                                    if (status >= 0)
1018 >                                        wait(millis);
1019 >                                }
1020 >                            } catch (InterruptedException ie) {
1021 >                            }
1022 >                        }
1023 >                        if ((s = status) < 0 ||
1024 >                            (nanos = deadline - System.nanoTime()) <= 0L)
1025 >                            break;
1026 >                    }
1027 >                }
1028 >            } finally {
1029 >                if (blocking)
1030 >                    p.incrementActiveCount();
1031 >            }
1032 >        }
1033          if (s != NORMAL) {
1034              Throwable ex;
1035              if (s == CANCELLED)
1036                  throw new CancellationException();
1037 <            if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
1037 >            if (s != EXCEPTIONAL)
1038 >                throw new TimeoutException();
1039 >            if ((ex = getThrowableException()) != null)
1040                  throw new ExecutionException(ex);
734            throw new TimeoutException();
1041          }
1042          return getRawResult();
1043      }
# Line 743 | Line 1049 | public abstract class ForkJoinTask<V> im
1049       * known to have aborted.
1050       */
1051      public final void quietlyJoin() {
1052 <        Thread t;
747 <        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
748 <            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
749 <            if (status >= 0) {
750 <                if (w.unpushTask(this)) {
751 <                    boolean completed;
752 <                    try {
753 <                        completed = exec();
754 <                    } catch (Throwable rex) {
755 <                        setExceptionalCompletion(rex);
756 <                        return;
757 <                    }
758 <                    if (completed) {
759 <                        setCompletion(NORMAL);
760 <                        return;
761 <                    }
762 <                }
763 <                w.joinTask(this, false, 0L);
764 <            }
765 <        }
766 <        else
767 <            externalAwaitDone();
1052 >        doJoin();
1053      }
1054  
1055      /**
# Line 773 | Line 1058 | public abstract class ForkJoinTask<V> im
1058       * exception.
1059       */
1060      public final void quietlyInvoke() {
1061 <        if (status >= 0) {
777 <            boolean completed;
778 <            try {
779 <                completed = exec();
780 <            } catch (Throwable rex) {
781 <                setExceptionalCompletion(rex);
782 <                return;
783 <            }
784 <            if (completed)
785 <                setCompletion(NORMAL);
786 <            else
787 <                quietlyJoin();
788 <        }
1061 >        doInvoke();
1062      }
1063  
1064      /**
# Line 802 | Line 1075 | public abstract class ForkJoinTask<V> im
1075       * ClassCastException}.
1076       */
1077      public static void helpQuiesce() {
1078 <        ((ForkJoinWorkerThread) Thread.currentThread())
1079 <            .helpQuiescePool();
1078 >        ForkJoinWorkerThread wt =
1079 >            (ForkJoinWorkerThread)Thread.currentThread();
1080 >        wt.pool.helpQuiescePool(wt.workQueue);
1081      }
1082  
1083      /**
# Line 824 | Line 1098 | public abstract class ForkJoinTask<V> im
1098       */
1099      public void reinitialize() {
1100          if (status == EXCEPTIONAL)
1101 <            exceptionMap.remove(this);
1102 <        status = 0;
1101 >            clearExceptionalCompletion();
1102 >        else
1103 >            status = 0;
1104      }
1105  
1106      /**
# Line 870 | Line 1145 | public abstract class ForkJoinTask<V> im
1145       * @return {@code true} if unforked
1146       */
1147      public boolean tryUnfork() {
1148 <        return ((ForkJoinWorkerThread) Thread.currentThread())
1149 <            .unpushTask(this);
1148 >        return ((ForkJoinWorkerThread)Thread.currentThread())
1149 >            .workQueue.tryUnpush(this);
1150      }
1151  
1152      /**
# Line 890 | Line 1165 | public abstract class ForkJoinTask<V> im
1165       */
1166      public static int getQueuedTaskCount() {
1167          return ((ForkJoinWorkerThread) Thread.currentThread())
1168 <            .getQueueSize();
1168 >            .workQueue.queueSize();
1169      }
1170  
1171      /**
# Line 912 | Line 1187 | public abstract class ForkJoinTask<V> im
1187       * @return the surplus number of tasks, which may be negative
1188       */
1189      public static int getSurplusQueuedTaskCount() {
1190 <        return ((ForkJoinWorkerThread) Thread.currentThread())
1191 <            .getEstimatedSurplusTaskCount();
1190 >        /*
1191 >         * The aim of this method is to return a cheap heuristic guide
1192 >         * for task partitioning when programmers, frameworks, tools,
1193 >         * or languages have little or no idea about task granularity.
1194 >         * In essence by offering this method, we ask users only about
1195 >         * tradeoffs in overhead vs expected throughput and its
1196 >         * variance, rather than how finely to partition tasks.
1197 >         *
1198 >         * In a steady state strict (tree-structured) computation,
1199 >         * each thread makes available for stealing enough tasks for
1200 >         * other threads to remain active. Inductively, if all threads
1201 >         * play by the same rules, each thread should make available
1202 >         * only a constant number of tasks.
1203 >         *
1204 >         * The minimum useful constant is just 1. But using a value of
1205 >         * 1 would require immediate replenishment upon each steal to
1206 >         * maintain enough tasks, which is infeasible.  Further,
1207 >         * partitionings/granularities of offered tasks should
1208 >         * minimize steal rates, which in general means that threads
1209 >         * nearer the top of computation tree should generate more
1210 >         * than those nearer the bottom. In perfect steady state, each
1211 >         * thread is at approximately the same level of computation
1212 >         * tree. However, producing extra tasks amortizes the
1213 >         * uncertainty of progress and diffusion assumptions.
1214 >         *
1215 >         * So, users will want to use values larger, but not much
1216 >         * larger than 1 to both smooth over transient shortages and
1217 >         * hedge against uneven progress; as traded off against the
1218 >         * cost of extra task overhead. We leave the user to pick a
1219 >         * threshold value to compare with the results of this call to
1220 >         * guide decisions, but recommend values such as 3.
1221 >         *
1222 >         * When all threads are active, it is on average OK to
1223 >         * estimate surplus strictly locally. In steady-state, if one
1224 >         * thread is maintaining say 2 surplus tasks, then so are
1225 >         * others. So we can just use estimated queue length.
1226 >         * However, this strategy alone leads to serious mis-estimates
1227 >         * in some non-steady-state conditions (ramp-up, ramp-down,
1228 >         * other stalls). We can detect many of these by further
1229 >         * considering the number of "idle" threads, that are known to
1230 >         * have zero queued tasks, so compensate by a factor of
1231 >         * (#idle/#active) threads.
1232 >         */
1233 >        ForkJoinWorkerThread wt =
1234 >            (ForkJoinWorkerThread)Thread.currentThread();
1235 >        return wt.workQueue.queueSize() - wt.pool.idlePerActive();
1236      }
1237  
1238      // Extension methods
# Line 970 | Line 1289 | public abstract class ForkJoinTask<V> im
1289       * @return the next task, or {@code null} if none are available
1290       */
1291      protected static ForkJoinTask<?> peekNextLocalTask() {
1292 <        return ((ForkJoinWorkerThread) Thread.currentThread())
974 <            .peekTask();
1292 >        return ((ForkJoinWorkerThread) Thread.currentThread()).workQueue.peek();
1293      }
1294  
1295      /**
# Line 990 | Line 1308 | public abstract class ForkJoinTask<V> im
1308       */
1309      protected static ForkJoinTask<?> pollNextLocalTask() {
1310          return ((ForkJoinWorkerThread) Thread.currentThread())
1311 <            .pollLocalTask();
1311 >            .workQueue.nextLocalTask();
1312      }
1313  
1314      /**
# Line 1012 | Line 1330 | public abstract class ForkJoinTask<V> im
1330       * @return a task, or {@code null} if none are available
1331       */
1332      protected static ForkJoinTask<?> pollTask() {
1333 <        return ((ForkJoinWorkerThread) Thread.currentThread())
1334 <            .pollTask();
1333 >        ForkJoinWorkerThread wt =
1334 >            (ForkJoinWorkerThread)Thread.currentThread();
1335 >        return wt.pool.nextTaskFor(wt.workQueue);
1336 >    }
1337 >
1338 >    // Mark-bit operations
1339 >
1340 >    /**
1341 >     * Returns true if this task is marked.
1342 >     *
1343 >     * @return true if this task is marked
1344 >     * @since 1.8
1345 >     */
1346 >    public final boolean isMarkedForkJoinTask() {
1347 >        return (status & MARKED) != 0;
1348 >    }
1349 >
1350 >    /**
1351 >     * Atomically sets the mark on this task.
1352 >     *
1353 >     * @return true if this task was previously unmarked
1354 >     * @since 1.8
1355 >     */
1356 >    public final boolean markForkJoinTask() {
1357 >        for (int s;;) {
1358 >            if (((s = status) & MARKED) != 0)
1359 >                return false;
1360 >            if (U.compareAndSwapInt(this, STATUS, s, s | MARKED))
1361 >                return true;
1362 >        }
1363 >    }
1364 >
1365 >    /**
1366 >     * Atomically clears the mark on this task.
1367 >     *
1368 >     * @return true if this task was previously marked
1369 >     * @since 1.8
1370 >     */
1371 >    public final boolean unmarkForkJoinTask() {
1372 >        for (int s;;) {
1373 >            if (((s = status) & MARKED) == 0)
1374 >                return false;
1375 >            if (U.compareAndSwapInt(this, STATUS, s, s & ~MARKED))
1376 >                return true;
1377 >        }
1378      }
1379  
1380      /**
# Line 1114 | Line 1475 | public abstract class ForkJoinTask<V> im
1475      private static final long serialVersionUID = -7721805057305804111L;
1476  
1477      /**
1478 <     * Saves the state to a stream (that is, serializes it).
1478 >     * Saves this task to a stream (that is, serializes it).
1479       *
1480       * @serialData the current run status and the exception thrown
1481       * during execution, or {@code null} if none
1121     * @param s the stream
1482       */
1483      private void writeObject(java.io.ObjectOutputStream s)
1484          throws java.io.IOException {
# Line 1127 | Line 1487 | public abstract class ForkJoinTask<V> im
1487      }
1488  
1489      /**
1490 <     * Reconstitutes the instance from a stream (that is, deserializes it).
1131 <     *
1132 <     * @param s the stream
1490 >     * Reconstitutes this task from a stream (that is, deserializes it).
1491       */
1492      private void readObject(java.io.ObjectInputStream s)
1493          throws java.io.IOException, ClassNotFoundException {
1494          s.defaultReadObject();
1495          Object ex = s.readObject();
1496          if (ex != null)
1497 <            setExceptionalCompletion((Throwable) ex);
1497 >            setExceptionalCompletion((Throwable)ex);
1498      }
1499  
1500      // Unsafe mechanics
1501 <
1502 <    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1503 <    private static final long statusOffset =
1504 <        objectFieldOffset("status", ForkJoinTask.class);
1505 <
1506 <    private static long objectFieldOffset(String field, Class<?> klazz) {
1501 >    private static final sun.misc.Unsafe U;
1502 >    private static final long STATUS;
1503 >    static {
1504 >        exceptionTableLock = new ReentrantLock();
1505 >        exceptionTableRefQueue = new ReferenceQueue<Object>();
1506 >        exceptionTable = new ExceptionNode[EXCEPTION_MAP_CAPACITY];
1507          try {
1508 <            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1509 <        } catch (NoSuchFieldException e) {
1510 <            // Convert Exception to corresponding Error
1511 <            NoSuchFieldError error = new NoSuchFieldError(field);
1512 <            error.initCause(e);
1155 <            throw error;
1508 >            U = getUnsafe();
1509 >            STATUS = U.objectFieldOffset
1510 >                (ForkJoinTask.class.getDeclaredField("status"));
1511 >        } catch (Exception e) {
1512 >            throw new Error(e);
1513          }
1514      }
1515  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines