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.73 by jsr166, Sun Nov 28 21:21:03 2010 UTC vs.
Revision 1.87 by dl, Sun Mar 4 15:52:45 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>tagged</em> with a {@code
141 > * short} value using {@link #setForkJoinTaskTag} or {@link
142 > * #compareAndSetForkJoinTaskTag} and checked using {@link
143 > * #getForkJoinTaskTag}. The ForkJoinTask implementation does not
144 > * use these {@code protected} methods or tags for any purpose, but
145 > * they may be of use in the construction of specialized subclasses.
146 > * For example, parallel graph traversals can use the supplied methods
147 > * to avoid revisiting nodes/tasks that have already been processed.
148 > * Also, completion based designs can use them to record that subtasks
149 > * have completed. (Method names for tagging are bulky in part to
150 > * encourage definition of methods that reflect their usage 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 status field holds run control status bits packed into a
202       * single int to minimize footprint and to ensure atomicity (via
203       * CAS).  Status is initially zero, and takes on nonnegative
204 <     * values until completed, upon which status holds value
205 <     * NORMAL, CANCELLED, or EXCEPTIONAL. Tasks undergoing blocking
206 <     * waits by other threads have the SIGNAL bit set.  Completion of
207 <     * a stolen task with SIGNAL set awakens any waiters via
208 <     * notifyAll. Even though suboptimal for some purposes, we use
209 <     * basic builtin wait/notify to take advantage of "monitor
210 <     * inflation" in JVMs that we would otherwise need to emulate to
211 <     * avoid adding further per-task bookkeeping overhead.  We want
212 <     * these monitors to be "fat", i.e., not use biasing or thin-lock
213 <     * techniques, so use some odd coding idioms that tend to avoid
214 <     * them.
204 >     * values until completed, upon which status (anded with
205 >     * DONE_MASK) holds value NORMAL, CANCELLED, or EXCEPTIONAL. Tasks
206 >     * undergoing blocking waits by other threads have the SIGNAL bit
207 >     * set.  Completion of a stolen task with SIGNAL set awakens any
208 >     * waiters via notifyAll. Even though suboptimal for some
209 >     * purposes, we use basic builtin wait/notify to take advantage of
210 >     * "monitor inflation" in JVMs that we would otherwise need to
211 >     * emulate to avoid adding further per-task bookkeeping overhead.
212 >     * We want these monitors to be "fat", i.e., not use biasing or
213 >     * thin-lock techniques, so use some odd coding idioms that tend
214 >     * to avoid them, mainly by arranging that every synchronized
215 >     * block performs a wait, notifyAll or both.
216 >     *
217 >     * These control bits occupy only (some of) the upper half (16
218 >     * bits) of status field. The lower bits are used for user-defined
219 >     * tags.
220       */
221  
222      /** The run status of this task */
223      volatile int status; // accessed directly by pool and workers
224 <
225 <    private static final int NORMAL      = -1;
226 <    private static final int CANCELLED   = -2;
227 <    private static final int EXCEPTIONAL = -3;
228 <    private static final int SIGNAL      =  1;
224 >    static final int DONE_MASK   = 0xf0000000;  // mask out non-completion bits
225 >    static final int NORMAL      = 0xf0000000;  // must be negative
226 >    static final int CANCELLED   = 0xc0000000;  // must be < NORMAL
227 >    static final int EXCEPTIONAL = 0x80000000;  // must be < CANCELLED
228 >    static final int SIGNAL      = 0x00010000;  // must be >= 1 << 16
229 >    static final int SMASK       = 0x0000ffff;  // short bits for tags
230  
231      /**
232 <     * Table of exceptions thrown by tasks, to enable reporting by
233 <     * callers. Because exceptions are rare, we don't directly keep
234 <     * them with task objects, but instead use a weak ref table.  Note
235 <     * that cancellation exceptions don't appear in the table, but are
236 <     * instead recorded as status values.
201 <     * TODO: Use ConcurrentReferenceHashMap
232 >     * Marks completion and wakes up threads waiting to join this
233 >     * task.
234 >     *
235 >     * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
236 >     * @return completion status on exit
237       */
238 <    static final Map<ForkJoinTask<?>, Throwable> exceptionMap =
239 <        Collections.synchronizedMap
240 <        (new WeakHashMap<ForkJoinTask<?>, Throwable>());
238 >    private int setCompletion(int completion) {
239 >        for (int s;;) {
240 >            if ((s = status) < 0)
241 >                return s;
242 >            if (U.compareAndSwapInt(this, STATUS, s, s | completion)) {
243 >                if ((s >>> 16) != 0)
244 >                    synchronized (this) { notifyAll(); }
245 >                return completion;
246 >            }
247 >        }
248 >    }
249  
250 <    // Maintaining completion status
250 >    /**
251 >     * Primary execution method for stolen tasks. Unless done, calls
252 >     * exec and records status if completed, but doesn't wait for
253 >     * completion otherwise.
254 >     *
255 >     * @return status on exit from this method
256 >     */
257 >    final int doExec() {
258 >        int s; boolean completed;
259 >        if ((s = status) >= 0) {
260 >            try {
261 >                completed = exec();
262 >            } catch (Throwable rex) {
263 >                return setExceptionalCompletion(rex);
264 >            }
265 >            if (completed)
266 >                s = setCompletion(NORMAL);
267 >        }
268 >        return s;
269 >    }
270  
271      /**
272 <     * Marks completion and wakes up threads waiting to join this task,
273 <     * also clearing signal request bits.
272 >     * Tries to set SIGNAL status. Used by ForkJoinPool. Other
273 >     * variants are directly incorporated into externalAwaitDone etc.
274       *
275 <     * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
275 >     * @return true if successful
276 >     */
277 >    final boolean trySetSignal() {
278 >        int s;
279 >        return U.compareAndSwapInt(this, STATUS, s = status, s | SIGNAL);
280 >    }
281 >
282 >    /**
283 >     * Blocks a non-worker-thread until completion.
284 >     * @return status upon completion
285       */
286 <    private void setCompletion(int completion) {
286 >    private int externalAwaitDone() {
287 >        boolean interrupted = false;
288          int s;
289          while ((s = status) >= 0) {
290 <            if (UNSAFE.compareAndSwapInt(this, statusOffset, s, completion)) {
291 <                if (s != 0)
292 <                    synchronized (this) { notifyAll(); }
293 <                break;
290 >            if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
291 >                synchronized (this) {
292 >                    if (status >= 0) {
293 >                        try {
294 >                            wait();
295 >                        } catch (InterruptedException ie) {
296 >                            interrupted = true;
297 >                        }
298 >                    }
299 >                    else
300 >                        notifyAll();
301 >                }
302              }
303          }
304 +        if (interrupted)
305 +            Thread.currentThread().interrupt();
306 +        return s;
307 +    }
308 +
309 +    /**
310 +     * Blocks a non-worker-thread until completion or interruption.
311 +     */
312 +    private int externalInterruptibleAwaitDone() throws InterruptedException {
313 +        int s;
314 +        if (Thread.interrupted())
315 +            throw new InterruptedException();
316 +        while ((s = status) >= 0) {
317 +            if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
318 +                synchronized (this) {
319 +                    if (status >= 0)
320 +                        wait();
321 +                    else
322 +                        notifyAll();
323 +                }
324 +            }
325 +        }
326 +        return s;
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 ForkJoinPool.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 +                if (!(w = (wt = (ForkJoinWorkerThread)t).workQueue).
341 +                    tryUnpush(this) || (s = doExec()) >= 0)
342 +                    s = wt.pool.awaitJoin(w, this);
343 +            }
344 +            else
345 +                s = externalAwaitDone();
346 +        }
347 +        return s;
348 +    }
349 +
350 +    /**
351 +     * Implementation for invoke, quietlyInvoke.
352 +     *
353 +     * @return status upon completion
354 +     */
355 +    private int doInvoke() {
356 +        int s; Thread t; ForkJoinWorkerThread wt;
357 +        if ((s = doExec()) >= 0) {
358 +            if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
359 +                s = (wt = (ForkJoinWorkerThread)t).pool.awaitJoin(wt.workQueue,
360 +                                                                  this);
361 +            else
362 +                s = externalAwaitDone();
363 +        }
364 +        return s;
365 +    }
366 +
367 +    // Exception table support
368 +
369 +    /**
370 +     * Table of exceptions thrown by tasks, to enable reporting by
371 +     * callers. Because exceptions are rare, we don't directly keep
372 +     * them with task objects, but instead use a weak ref table.  Note
373 +     * that cancellation exceptions don't appear in the table, but are
374 +     * instead recorded as status values.
375 +     *
376 +     * Note: These statics are initialized below in static block.
377 +     */
378 +    private static final ExceptionNode[] exceptionTable;
379 +    private static final ReentrantLock exceptionTableLock;
380 +    private static final ReferenceQueue<Object> exceptionTableRefQueue;
381 +
382 +    /**
383 +     * Fixed capacity for exceptionTable.
384 +     */
385 +    private static final int EXCEPTION_MAP_CAPACITY = 32;
386 +
387 +    /**
388 +     * Key-value nodes for exception table.  The chained hash table
389 +     * uses identity comparisons, full locking, and weak references
390 +     * for keys. The table has a fixed capacity because it only
391 +     * maintains task exceptions long enough for joiners to access
392 +     * them, so should never become very large for sustained
393 +     * periods. However, since we do not know when the last joiner
394 +     * completes, we must use weak references and expunge them. We do
395 +     * so on each operation (hence full locking). Also, some thread in
396 +     * any ForkJoinPool will call helpExpungeStaleExceptions when its
397 +     * pool becomes isQuiescent.
398 +     */
399 +    static final class ExceptionNode extends WeakReference<ForkJoinTask<?>> {
400 +        final Throwable ex;
401 +        ExceptionNode next;
402 +        final long thrower;  // use id not ref to avoid weak cycles
403 +        ExceptionNode(ForkJoinTask<?> task, Throwable ex, ExceptionNode next) {
404 +            super(task, exceptionTableRefQueue);
405 +            this.ex = ex;
406 +            this.next = next;
407 +            this.thrower = Thread.currentThread().getId();
408 +        }
409      }
410  
411      /**
# Line 228 | Line 413 | public abstract class ForkJoinTask<V> im
413       *
414       * @return status on exit
415       */
416 <    private void setExceptionalCompletion(Throwable rex) {
417 <        exceptionMap.put(this, rex);
418 <        setCompletion(EXCEPTIONAL);
416 >    private int setExceptionalCompletion(Throwable ex) {
417 >        int h = System.identityHashCode(this);
418 >        final ReentrantLock lock = exceptionTableLock;
419 >        lock.lock();
420 >        try {
421 >            expungeStaleExceptions();
422 >            ExceptionNode[] t = exceptionTable;
423 >            int i = h & (t.length - 1);
424 >            for (ExceptionNode e = t[i]; ; e = e.next) {
425 >                if (e == null) {
426 >                    t[i] = new ExceptionNode(this, ex, t[i]);
427 >                    break;
428 >                }
429 >                if (e.get() == this) // already present
430 >                    break;
431 >            }
432 >        } finally {
433 >            lock.unlock();
434 >        }
435 >        return setCompletion(EXCEPTIONAL);
436      }
437  
438      /**
439 <     * Blocks a worker thread until completed or timed out.  Called
440 <     * only by pool.
439 >     * Cancels, ignoring any exceptions thrown by cancel. Used during
440 >     * worker and pool shutdown. Cancel is spec'ed not to throw any
441 >     * exceptions, but if it does anyway, we have no recourse during
442 >     * shutdown, so guard against this case.
443       */
444 <    final void internalAwaitDone(long millis, int nanos) {
445 <        int s = status;
446 <        if ((s == 0 &&
447 <             UNSAFE.compareAndSwapInt(this, statusOffset, 0, SIGNAL)) ||
448 <            s > 0)  {
449 <            try {     // the odd construction reduces lock bias effects
450 <                synchronized (this) {
451 <                    if (status > 0)
452 <                        wait(millis, nanos);
444 >    static final void cancelIgnoringExceptions(ForkJoinTask<?> t) {
445 >        if (t != null && t.status >= 0) {
446 >            try {
447 >                t.cancel(false);
448 >            } catch (Throwable ignore) {
449 >            }
450 >        }
451 >    }
452 >
453 >    /**
454 >     * Removes exception node and clears status
455 >     */
456 >    private void clearExceptionalCompletion() {
457 >        int h = System.identityHashCode(this);
458 >        final ReentrantLock lock = exceptionTableLock;
459 >        lock.lock();
460 >        try {
461 >            ExceptionNode[] t = exceptionTable;
462 >            int i = h & (t.length - 1);
463 >            ExceptionNode e = t[i];
464 >            ExceptionNode pred = null;
465 >            while (e != null) {
466 >                ExceptionNode next = e.next;
467 >                if (e.get() == this) {
468 >                    if (pred == null)
469 >                        t[i] = next;
470                      else
471 <                        notifyAll();
471 >                        pred.next = next;
472 >                    break;
473                  }
474 <            } catch (InterruptedException ie) {
475 <                cancelIfTerminating();
474 >                pred = e;
475 >                e = next;
476              }
477 +            expungeStaleExceptions();
478 +            status = 0;
479 +        } finally {
480 +            lock.unlock();
481          }
482      }
483  
484      /**
485 <     * Blocks a non-worker-thread until completion.
486 <     */
487 <    private void externalAwaitDone() {
488 <        if (status >= 0) {
489 <            boolean interrupted = false;
490 <            synchronized (this) {
491 <                for (;;) {
492 <                    int s = status;
493 <                    if (s == 0)
494 <                        UNSAFE.compareAndSwapInt(this, statusOffset,
495 <                                                 0, SIGNAL);
496 <                    else if (s < 0) {
497 <                        notifyAll();
498 <                        break;
499 <                    }
500 <                    else {
501 <                        try {
502 <                            wait();
503 <                        } catch (InterruptedException ie) {
504 <                            interrupted = true;
505 <                        }
506 <                    }
485 >     * Returns a rethrowable exception for the given task, if
486 >     * available. To provide accurate stack traces, if the exception
487 >     * was not thrown by the current thread, we try to create a new
488 >     * exception of the same type as the one thrown, but with the
489 >     * recorded exception as its cause. If there is no such
490 >     * constructor, we instead try to use a no-arg constructor,
491 >     * followed by initCause, to the same effect. If none of these
492 >     * apply, or any fail due to other exceptions, we return the
493 >     * recorded exception, which is still correct, although it may
494 >     * contain a misleading stack trace.
495 >     *
496 >     * @return the exception, or null if none
497 >     */
498 >    private Throwable getThrowableException() {
499 >        if ((status & DONE_MASK) != EXCEPTIONAL)
500 >            return null;
501 >        int h = System.identityHashCode(this);
502 >        ExceptionNode e;
503 >        final ReentrantLock lock = exceptionTableLock;
504 >        lock.lock();
505 >        try {
506 >            expungeStaleExceptions();
507 >            ExceptionNode[] t = exceptionTable;
508 >            e = t[h & (t.length - 1)];
509 >            while (e != null && e.get() != this)
510 >                e = e.next;
511 >        } finally {
512 >            lock.unlock();
513 >        }
514 >        Throwable ex;
515 >        if (e == null || (ex = e.ex) == null)
516 >            return null;
517 >        if (e.thrower != Thread.currentThread().getId()) {
518 >            Class<? extends Throwable> ec = ex.getClass();
519 >            try {
520 >                Constructor<?> noArgCtor = null;
521 >                Constructor<?>[] cs = ec.getConstructors();// public ctors only
522 >                for (int i = 0; i < cs.length; ++i) {
523 >                    Constructor<?> c = cs[i];
524 >                    Class<?>[] ps = c.getParameterTypes();
525 >                    if (ps.length == 0)
526 >                        noArgCtor = c;
527 >                    else if (ps.length == 1 && ps[0] == Throwable.class)
528 >                        return (Throwable)(c.newInstance(ex));
529                  }
530 +                if (noArgCtor != null) {
531 +                    Throwable wx = (Throwable)(noArgCtor.newInstance());
532 +                    wx.initCause(ex);
533 +                    return wx;
534 +                }
535 +            } catch (Exception ignore) {
536              }
283            if (interrupted)
284                Thread.currentThread().interrupt();
537          }
538 +        return ex;
539      }
540  
541      /**
542 <     * Blocks a non-worker-thread until completion or interruption or timeout.
542 >     * Poll stale refs and remove them. Call only while holding lock.
543       */
544 <    private void externalInterruptibleAwaitDone(boolean timed, long nanos)
545 <        throws InterruptedException {
546 <        if (Thread.interrupted())
547 <            throw new InterruptedException();
548 <        if (status >= 0) {
549 <            long startTime = timed ? System.nanoTime() : 0L;
550 <            synchronized (this) {
551 <                for (;;) {
552 <                    long nt;
553 <                    int s = status;
554 <                    if (s == 0)
555 <                        UNSAFE.compareAndSwapInt(this, statusOffset,
556 <                                                 0, SIGNAL);
557 <                    else if (s < 0) {
558 <                        notifyAll();
544 >    private static void expungeStaleExceptions() {
545 >        for (Object x; (x = exceptionTableRefQueue.poll()) != null;) {
546 >            if (x instanceof ExceptionNode) {
547 >                ForkJoinTask<?> key = ((ExceptionNode)x).get();
548 >                ExceptionNode[] t = exceptionTable;
549 >                int i = System.identityHashCode(key) & (t.length - 1);
550 >                ExceptionNode e = t[i];
551 >                ExceptionNode pred = null;
552 >                while (e != null) {
553 >                    ExceptionNode next = e.next;
554 >                    if (e == x) {
555 >                        if (pred == null)
556 >                            t[i] = next;
557 >                        else
558 >                            pred.next = next;
559                          break;
560                      }
561 <                    else if (!timed)
562 <                        wait();
310 <                    else if ((nt = nanos - (System.nanoTime()-startTime)) > 0L)
311 <                        wait(nt / 1000000, (int)(nt % 1000000));
312 <                    else
313 <                        break;
561 >                    pred = e;
562 >                    e = next;
563                  }
564              }
565          }
566      }
567  
568      /**
569 <     * Unless done, calls exec and records status if completed, but
570 <     * doesn't wait for completion otherwise. Primary execution method
322 <     * for ForkJoinWorkerThread.
569 >     * If lock is available, poll stale refs and remove them.
570 >     * Called from ForkJoinPool when pools become quiescent.
571       */
572 <    final void quietlyExec() {
573 <        try {
574 <            if (status < 0 || !exec())
575 <                return;
576 <        } catch (Throwable rex) {
577 <            setExceptionalCompletion(rex);
578 <            return;
572 >    static final void helpExpungeStaleExceptions() {
573 >        final ReentrantLock lock = exceptionTableLock;
574 >        if (lock.tryLock()) {
575 >            try {
576 >                expungeStaleExceptions();
577 >            } finally {
578 >                lock.unlock();
579 >            }
580          }
581 <        setCompletion(NORMAL); // must be outside try block
581 >    }
582 >
583 >    /**
584 >     * Throws exception, if any, associated with the given status.
585 >     */
586 >    private void reportException(int s) {
587 >        Throwable ex = ((s == CANCELLED) ?  new CancellationException() :
588 >                        (s == EXCEPTIONAL) ? getThrowableException() :
589 >                        null);
590 >        if (ex != null)
591 >            U.throwException(ex);
592      }
593  
594      // public methods
# Line 353 | Line 612 | public abstract class ForkJoinTask<V> im
612       * @return {@code this}, to simplify usage
613       */
614      public final ForkJoinTask<V> fork() {
615 <        ((ForkJoinWorkerThread) Thread.currentThread())
357 <            .pushTask(this);
615 >        ((ForkJoinWorkerThread)Thread.currentThread()).workQueue.push(this);
616          return this;
617      }
618  
# Line 370 | Line 628 | public abstract class ForkJoinTask<V> im
628       * @return the computed result
629       */
630      public final V join() {
631 <        quietlyJoin();
632 <        Throwable ex;
633 <        if (status < NORMAL && (ex = getException()) != null)
376 <            UNSAFE.throwException(ex);
631 >        int s;
632 >        if ((s = doJoin() & DONE_MASK) != NORMAL)
633 >            reportException(s);
634          return getRawResult();
635      }
636  
# Line 386 | Line 643 | public abstract class ForkJoinTask<V> im
643       * @return the computed result
644       */
645      public final V invoke() {
646 <        quietlyInvoke();
647 <        Throwable ex;
648 <        if (status < NORMAL && (ex = getException()) != null)
392 <            UNSAFE.throwException(ex);
646 >        int s;
647 >        if ((s = doInvoke() & DONE_MASK) != NORMAL)
648 >            reportException(s);
649          return getRawResult();
650      }
651  
# Line 417 | Line 673 | public abstract class ForkJoinTask<V> im
673       * @throws NullPointerException if any task is null
674       */
675      public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) {
676 +        int s1, s2;
677          t2.fork();
678 <        t1.invoke();
679 <        t2.join();
678 >        if ((s1 = t1.doInvoke() & DONE_MASK) != NORMAL)
679 >            t1.reportException(s1);
680 >        if ((s2 = t2.doJoin() & DONE_MASK) != NORMAL)
681 >            t2.reportException(s2);
682      }
683  
684      /**
# Line 454 | Line 713 | public abstract class ForkJoinTask<V> im
713              }
714              else if (i != 0)
715                  t.fork();
716 <            else {
717 <                t.quietlyInvoke();
459 <                if (ex == null && t.status < NORMAL)
460 <                    ex = t.getException();
461 <            }
716 >            else if (t.doInvoke() < NORMAL && ex == null)
717 >                ex = t.getException();
718          }
719          for (int i = 1; i <= last; ++i) {
720              ForkJoinTask<?> t = tasks[i];
721              if (t != null) {
722                  if (ex != null)
723                      t.cancel(false);
724 <                else {
725 <                    t.quietlyJoin();
470 <                    if (ex == null && t.status < NORMAL)
471 <                        ex = t.getException();
472 <                }
724 >                else if (t.doJoin() < NORMAL)
725 >                    ex = t.getException();
726              }
727          }
728          if (ex != null)
729 <            UNSAFE.throwException(ex);
729 >            U.throwException(ex);
730      }
731  
732      /**
# Line 517 | Line 770 | public abstract class ForkJoinTask<V> im
770              }
771              else if (i != 0)
772                  t.fork();
773 <            else {
774 <                t.quietlyInvoke();
522 <                if (ex == null && t.status < NORMAL)
523 <                    ex = t.getException();
524 <            }
773 >            else if (t.doInvoke() < NORMAL && ex == null)
774 >                ex = t.getException();
775          }
776          for (int i = 1; i <= last; ++i) {
777              ForkJoinTask<?> t = ts.get(i);
778              if (t != null) {
779                  if (ex != null)
780                      t.cancel(false);
781 <                else {
782 <                    t.quietlyJoin();
533 <                    if (ex == null && t.status < NORMAL)
534 <                        ex = t.getException();
535 <                }
781 >                else if (t.doJoin() < NORMAL)
782 >                    ex = t.getException();
783              }
784          }
785          if (ex != null)
786 <            UNSAFE.throwException(ex);
786 >            U.throwException(ex);
787          return tasks;
788      }
789  
# Line 568 | Line 815 | public abstract class ForkJoinTask<V> im
815       * @return {@code true} if this task is now cancelled
816       */
817      public boolean cancel(boolean mayInterruptIfRunning) {
818 <        setCompletion(CANCELLED);
572 <        return status == CANCELLED;
573 <    }
574 <
575 <    /**
576 <     * Cancels, ignoring any exceptions thrown by cancel. Used during
577 <     * worker and pool shutdown. Cancel is spec'ed not to throw any
578 <     * exceptions, but if it does anyway, we have no recourse during
579 <     * shutdown, so guard against this case.
580 <     */
581 <    final void cancelIgnoringExceptions() {
582 <        try {
583 <            cancel(false);
584 <        } catch (Throwable ignore) {
585 <        }
586 <    }
587 <
588 <    /**
589 <     * Cancels if current thread is a terminating worker thread,
590 <     * ignoring any exceptions thrown by cancel.
591 <     */
592 <    final void cancelIfTerminating() {
593 <        Thread t = Thread.currentThread();
594 <        if ((t instanceof ForkJoinWorkerThread) &&
595 <            ((ForkJoinWorkerThread) t).isTerminating()) {
596 <            try {
597 <                cancel(false);
598 <            } catch (Throwable ignore) {
599 <            }
600 <        }
818 >        return (setCompletion(CANCELLED) & DONE_MASK) == CANCELLED;
819      }
820  
821      public final boolean isDone() {
# Line 605 | Line 823 | public abstract class ForkJoinTask<V> im
823      }
824  
825      public final boolean isCancelled() {
826 <        return status == CANCELLED;
826 >        return (status & DONE_MASK) == CANCELLED;
827      }
828  
829      /**
# Line 625 | Line 843 | public abstract class ForkJoinTask<V> im
843       * exception and was not cancelled
844       */
845      public final boolean isCompletedNormally() {
846 <        return status == NORMAL;
846 >        return (status & DONE_MASK) == NORMAL;
847      }
848  
849      /**
# Line 636 | Line 854 | public abstract class ForkJoinTask<V> im
854       * @return the exception, or {@code null} if none
855       */
856      public final Throwable getException() {
857 <        int s = status;
857 >        int s = status & DONE_MASK;
858          return ((s >= NORMAL)    ? null :
859                  (s == CANCELLED) ? new CancellationException() :
860 <                exceptionMap.get(this));
860 >                getThrowableException());
861      }
862  
863      /**
# Line 686 | Line 904 | public abstract class ForkJoinTask<V> im
904      }
905  
906      /**
907 +     * Completes this task. The most recent value established by
908 +     * {@link #setRawResult} (or {@code null}) will be returned as the
909 +     * result of subsequent invocations of {@code join} and related
910 +     * operations. This method may be useful when processing sets of
911 +     * tasks when some do not otherwise complete normally. Its use in
912 +     * other situations is discouraged.
913 +     */
914 +    public final void quietlyComplete() {
915 +        setCompletion(NORMAL);
916 +    }
917 +
918 +    /**
919       * Waits if necessary for the computation to complete, and then
920       * retrieves its result.
921       *
# Line 697 | Line 927 | public abstract class ForkJoinTask<V> im
927       * member of a ForkJoinPool and was interrupted while waiting
928       */
929      public final V get() throws InterruptedException, ExecutionException {
930 <        Thread t = Thread.currentThread();
931 <        if (t instanceof ForkJoinWorkerThread)
932 <            quietlyJoin();
933 <        else
934 <            externalInterruptibleAwaitDone(false, 0L);
935 <        int s = status;
936 <        if (s != NORMAL) {
707 <            Throwable ex;
708 <            if (s == CANCELLED)
709 <                throw new CancellationException();
710 <            if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
711 <                throw new ExecutionException(ex);
712 <        }
930 >        int s = (Thread.currentThread() instanceof ForkJoinWorkerThread) ?
931 >            doJoin() : externalInterruptibleAwaitDone();
932 >        Throwable ex;
933 >        if ((s &= DONE_MASK) == CANCELLED)
934 >            throw new CancellationException();
935 >        if (s == EXCEPTIONAL && (ex = getThrowableException()) != null)
936 >            throw new ExecutionException(ex);
937          return getRawResult();
938      }
939  
# Line 729 | Line 953 | public abstract class ForkJoinTask<V> im
953       */
954      public final V get(long timeout, TimeUnit unit)
955          throws InterruptedException, ExecutionException, TimeoutException {
956 <        long nanos = unit.toNanos(timeout);
957 <        Thread t = Thread.currentThread();
958 <        if (t instanceof ForkJoinWorkerThread)
959 <            ((ForkJoinWorkerThread)t).joinTask(this, true, nanos);
960 <        else
961 <            externalInterruptibleAwaitDone(true, nanos);
962 <        int s = status;
963 <        if (s != NORMAL) {
956 >        if (Thread.interrupted())
957 >            throw new InterruptedException();
958 >        // Messy in part because we measure in nanosecs, but wait in millisecs
959 >        int s; long ns, ms;
960 >        if ((s = status) >= 0 && (ns = unit.toNanos(timeout)) > 0L) {
961 >            long deadline = System.nanoTime() + ns;
962 >            ForkJoinPool p = null;
963 >            ForkJoinPool.WorkQueue w = null;
964 >            Thread t = Thread.currentThread();
965 >            if (t instanceof ForkJoinWorkerThread) {
966 >                ForkJoinWorkerThread wt = (ForkJoinWorkerThread)t;
967 >                p = wt.pool;
968 >                w = wt.workQueue;
969 >                s = p.helpJoinOnce(w, this); // no retries on failure
970 >            }
971 >            boolean canBlock = false;
972 >            boolean interrupted = false;
973 >            try {
974 >                while ((s = status) >= 0) {
975 >                    if (w != null && w.runState < 0)
976 >                        cancelIgnoringExceptions(this);
977 >                    else if (!canBlock) {
978 >                        if (p == null || p.tryCompensate(this, null))
979 >                            canBlock = true;
980 >                    }
981 >                    else {
982 >                        if ((ms = TimeUnit.NANOSECONDS.toMillis(ns)) > 0L &&
983 >                            U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
984 >                            synchronized (this) {
985 >                                if (status >= 0) {
986 >                                    try {
987 >                                        wait(ms);
988 >                                    } catch (InterruptedException ie) {
989 >                                        if (p == null)
990 >                                            interrupted = true;
991 >                                    }
992 >                                }
993 >                                else
994 >                                    notifyAll();
995 >                            }
996 >                        }
997 >                        if ((s = status) < 0 || interrupted ||
998 >                            (ns = deadline - System.nanoTime()) <= 0L)
999 >                            break;
1000 >                    }
1001 >                }
1002 >            } finally {
1003 >                if (p != null && canBlock)
1004 >                    p.incrementActiveCount();
1005 >            }
1006 >            if (interrupted)
1007 >                throw new InterruptedException();
1008 >        }
1009 >        if ((s &= DONE_MASK) != NORMAL) {
1010              Throwable ex;
1011              if (s == CANCELLED)
1012                  throw new CancellationException();
1013 <            if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null)
1013 >            if (s != EXCEPTIONAL)
1014 >                throw new TimeoutException();
1015 >            if ((ex = getThrowableException()) != null)
1016                  throw new ExecutionException(ex);
745            throw new TimeoutException();
1017          }
1018          return getRawResult();
1019      }
# Line 754 | Line 1025 | public abstract class ForkJoinTask<V> im
1025       * known to have aborted.
1026       */
1027      public final void quietlyJoin() {
1028 <        Thread t;
758 <        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
759 <            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
760 <            if (status >= 0) {
761 <                if (w.unpushTask(this)) {
762 <                    boolean completed;
763 <                    try {
764 <                        completed = exec();
765 <                    } catch (Throwable rex) {
766 <                        setExceptionalCompletion(rex);
767 <                        return;
768 <                    }
769 <                    if (completed) {
770 <                        setCompletion(NORMAL);
771 <                        return;
772 <                    }
773 <                }
774 <                w.joinTask(this, false, 0L);
775 <            }
776 <        }
777 <        else
778 <            externalAwaitDone();
1028 >        doJoin();
1029      }
1030  
1031      /**
# Line 784 | Line 1034 | public abstract class ForkJoinTask<V> im
1034       * exception.
1035       */
1036      public final void quietlyInvoke() {
1037 <        if (status >= 0) {
788 <            boolean completed;
789 <            try {
790 <                completed = exec();
791 <            } catch (Throwable rex) {
792 <                setExceptionalCompletion(rex);
793 <                return;
794 <            }
795 <            if (completed)
796 <                setCompletion(NORMAL);
797 <            else
798 <                quietlyJoin();
799 <        }
1037 >        doInvoke();
1038      }
1039  
1040      /**
# Line 813 | Line 1051 | public abstract class ForkJoinTask<V> im
1051       * ClassCastException}.
1052       */
1053      public static void helpQuiesce() {
1054 <        ((ForkJoinWorkerThread) Thread.currentThread())
1055 <            .helpQuiescePool();
1054 >        ForkJoinWorkerThread wt =
1055 >            (ForkJoinWorkerThread)Thread.currentThread();
1056 >        wt.pool.helpQuiescePool(wt.workQueue);
1057      }
1058  
1059      /**
# Line 834 | Line 1073 | public abstract class ForkJoinTask<V> im
1073       * setRawResult(null)}.
1074       */
1075      public void reinitialize() {
1076 <        if (status == EXCEPTIONAL)
1077 <            exceptionMap.remove(this);
1078 <        status = 0;
1076 >        if ((status & DONE_MASK) == EXCEPTIONAL)
1077 >            clearExceptionalCompletion();
1078 >        else
1079 >            status = 0;
1080      }
1081  
1082      /**
# Line 881 | Line 1121 | public abstract class ForkJoinTask<V> im
1121       * @return {@code true} if unforked
1122       */
1123      public boolean tryUnfork() {
1124 <        return ((ForkJoinWorkerThread) Thread.currentThread())
1125 <            .unpushTask(this);
1124 >        return ((ForkJoinWorkerThread)Thread.currentThread())
1125 >            .workQueue.tryUnpush(this);
1126      }
1127  
1128      /**
# Line 901 | Line 1141 | public abstract class ForkJoinTask<V> im
1141       */
1142      public static int getQueuedTaskCount() {
1143          return ((ForkJoinWorkerThread) Thread.currentThread())
1144 <            .getQueueSize();
1144 >            .workQueue.queueSize();
1145      }
1146  
1147      /**
# Line 923 | Line 1163 | public abstract class ForkJoinTask<V> im
1163       * @return the surplus number of tasks, which may be negative
1164       */
1165      public static int getSurplusQueuedTaskCount() {
1166 <        return ((ForkJoinWorkerThread) Thread.currentThread())
1167 <            .getEstimatedSurplusTaskCount();
1166 >        /*
1167 >         * The aim of this method is to return a cheap heuristic guide
1168 >         * for task partitioning when programmers, frameworks, tools,
1169 >         * or languages have little or no idea about task granularity.
1170 >         * In essence by offering this method, we ask users only about
1171 >         * tradeoffs in overhead vs expected throughput and its
1172 >         * variance, rather than how finely to partition tasks.
1173 >         *
1174 >         * In a steady state strict (tree-structured) computation,
1175 >         * each thread makes available for stealing enough tasks for
1176 >         * other threads to remain active. Inductively, if all threads
1177 >         * play by the same rules, each thread should make available
1178 >         * only a constant number of tasks.
1179 >         *
1180 >         * The minimum useful constant is just 1. But using a value of
1181 >         * 1 would require immediate replenishment upon each steal to
1182 >         * maintain enough tasks, which is infeasible.  Further,
1183 >         * partitionings/granularities of offered tasks should
1184 >         * minimize steal rates, which in general means that threads
1185 >         * nearer the top of computation tree should generate more
1186 >         * than those nearer the bottom. In perfect steady state, each
1187 >         * thread is at approximately the same level of computation
1188 >         * tree. However, producing extra tasks amortizes the
1189 >         * uncertainty of progress and diffusion assumptions.
1190 >         *
1191 >         * So, users will want to use values larger, but not much
1192 >         * larger than 1 to both smooth over transient shortages and
1193 >         * hedge against uneven progress; as traded off against the
1194 >         * cost of extra task overhead. We leave the user to pick a
1195 >         * threshold value to compare with the results of this call to
1196 >         * guide decisions, but recommend values such as 3.
1197 >         *
1198 >         * When all threads are active, it is on average OK to
1199 >         * estimate surplus strictly locally. In steady-state, if one
1200 >         * thread is maintaining say 2 surplus tasks, then so are
1201 >         * others. So we can just use estimated queue length.
1202 >         * However, this strategy alone leads to serious mis-estimates
1203 >         * in some non-steady-state conditions (ramp-up, ramp-down,
1204 >         * other stalls). We can detect many of these by further
1205 >         * considering the number of "idle" threads, that are known to
1206 >         * have zero queued tasks, so compensate by a factor of
1207 >         * (#idle/#active) threads.
1208 >         */
1209 >        ForkJoinWorkerThread wt =
1210 >            (ForkJoinWorkerThread)Thread.currentThread();
1211 >        return wt.workQueue.queueSize() - wt.pool.idlePerActive();
1212      }
1213  
1214      // Extension methods
# Line 981 | Line 1265 | public abstract class ForkJoinTask<V> im
1265       * @return the next task, or {@code null} if none are available
1266       */
1267      protected static ForkJoinTask<?> peekNextLocalTask() {
1268 <        return ((ForkJoinWorkerThread) Thread.currentThread())
985 <            .peekTask();
1268 >        return ((ForkJoinWorkerThread) Thread.currentThread()).workQueue.peek();
1269      }
1270  
1271      /**
# Line 1001 | Line 1284 | public abstract class ForkJoinTask<V> im
1284       */
1285      protected static ForkJoinTask<?> pollNextLocalTask() {
1286          return ((ForkJoinWorkerThread) Thread.currentThread())
1287 <            .pollLocalTask();
1287 >            .workQueue.nextLocalTask();
1288      }
1289  
1290      /**
# Line 1023 | Line 1306 | public abstract class ForkJoinTask<V> im
1306       * @return a task, or {@code null} if none are available
1307       */
1308      protected static ForkJoinTask<?> pollTask() {
1309 <        return ((ForkJoinWorkerThread) Thread.currentThread())
1310 <            .pollTask();
1309 >        ForkJoinWorkerThread wt =
1310 >            (ForkJoinWorkerThread)Thread.currentThread();
1311 >        return wt.pool.nextTaskFor(wt.workQueue);
1312 >    }
1313 >
1314 >    // tag operations
1315 >
1316 >    /**
1317 >     * Returns the tag for this task.
1318 >     *
1319 >     * @return the tag for this task
1320 >     * @since 1.8
1321 >     */
1322 >    public final short getForkJoinTaskTag() {
1323 >        return (short)status;
1324 >    }
1325 >
1326 >    /**
1327 >     * Atomically sets the tag value for this task.
1328 >     *
1329 >     * @param tag the tag value
1330 >     * @return the previous value of the tag
1331 >     * @since 1.8
1332 >     */
1333 >    public final short setForkJoinTaskTag(short tag) {
1334 >        for (int s;;) {
1335 >            if (U.compareAndSwapInt(this, STATUS, s = status,
1336 >                                    (s & ~SMASK) | (tag & SMASK)))
1337 >                return (short)s;
1338 >        }
1339 >    }
1340 >
1341 >    /**
1342 >     * Atomically conditionally sets the tag value for this task.
1343 >     * Among other applications, tags can be used as visit markers
1344 >     * in tasks operating on graphs, as in mathods that check: {@code
1345 >     * if (task.compareAndSetForkJoinTaskTag((short)0, (short)1))}
1346 >     * before processing, otherwise exiting because the node has
1347 >     * already been visited.
1348 >     *
1349 >     * @param e the expected tag value
1350 >     * @param tag the new tag value
1351 >     * @return true if successful; i.e., the current value was
1352 >     * equal to e and is now tag.
1353 >     * @since 1.8
1354 >     */
1355 >    public final boolean compareAndSetForkJoinTaskTag(short e, short tag) {
1356 >        for (int s;;) {
1357 >            if ((short)(s = status) != e)
1358 >                return false;
1359 >            if (U.compareAndSwapInt(this, STATUS, s,
1360 >                                    (s & ~SMASK) | (tag & SMASK)))
1361 >                return true;
1362 >        }
1363      }
1364  
1365      /**
# Line 1035 | Line 1370 | public abstract class ForkJoinTask<V> im
1370      static final class AdaptedRunnable<T> extends ForkJoinTask<T>
1371          implements RunnableFuture<T> {
1372          final Runnable runnable;
1038        final T resultOnCompletion;
1373          T result;
1374          AdaptedRunnable(Runnable runnable, T result) {
1375              if (runnable == null) throw new NullPointerException();
1376              this.runnable = runnable;
1377 <            this.resultOnCompletion = result;
1377 >            this.result = result; // OK to set this even before completion
1378          }
1379 <        public T getRawResult() { return result; }
1380 <        public void setRawResult(T v) { result = v; }
1381 <        public boolean exec() {
1382 <            runnable.run();
1383 <            result = resultOnCompletion;
1384 <            return true;
1379 >        public final T getRawResult() { return result; }
1380 >        public final void setRawResult(T v) { result = v; }
1381 >        public final boolean exec() { runnable.run(); return true; }
1382 >        public final void run() { invoke(); }
1383 >        private static final long serialVersionUID = 5232453952276885070L;
1384 >    }
1385 >
1386 >    /**
1387 >     * Adaptor for Runnables without results
1388 >     */
1389 >    static final class AdaptedRunnableAction extends ForkJoinTask<Void>
1390 >        implements RunnableFuture<Void> {
1391 >        final Runnable runnable;
1392 >        AdaptedRunnableAction(Runnable runnable) {
1393 >            if (runnable == null) throw new NullPointerException();
1394 >            this.runnable = runnable;
1395          }
1396 <        public void run() { invoke(); }
1396 >        public final Void getRawResult() { return null; }
1397 >        public final void setRawResult(Void v) { }
1398 >        public final boolean exec() { runnable.run(); return true; }
1399 >        public final void run() { invoke(); }
1400          private static final long serialVersionUID = 5232453952276885070L;
1401      }
1402  
# Line 1064 | Line 1411 | public abstract class ForkJoinTask<V> im
1411              if (callable == null) throw new NullPointerException();
1412              this.callable = callable;
1413          }
1414 <        public T getRawResult() { return result; }
1415 <        public void setRawResult(T v) { result = v; }
1416 <        public boolean exec() {
1414 >        public final T getRawResult() { return result; }
1415 >        public final void setRawResult(T v) { result = v; }
1416 >        public final boolean exec() {
1417              try {
1418                  result = callable.call();
1419                  return true;
# Line 1078 | Line 1425 | public abstract class ForkJoinTask<V> im
1425                  throw new RuntimeException(ex);
1426              }
1427          }
1428 <        public void run() { invoke(); }
1428 >        public final void run() { invoke(); }
1429          private static final long serialVersionUID = 2838392045355241008L;
1430      }
1431  
# Line 1091 | Line 1438 | public abstract class ForkJoinTask<V> im
1438       * @return the task
1439       */
1440      public static ForkJoinTask<?> adapt(Runnable runnable) {
1441 <        return new AdaptedRunnable<Void>(runnable, null);
1441 >        return new AdaptedRunnableAction(runnable);
1442      }
1443  
1444      /**
# Line 1125 | Line 1472 | public abstract class ForkJoinTask<V> im
1472      private static final long serialVersionUID = -7721805057305804111L;
1473  
1474      /**
1475 <     * Saves the state to a stream (that is, serializes it).
1475 >     * Saves this task to a stream (that is, serializes it).
1476       *
1477       * @serialData the current run status and the exception thrown
1478       * during execution, or {@code null} if none
1132     * @param s the stream
1479       */
1480      private void writeObject(java.io.ObjectOutputStream s)
1481          throws java.io.IOException {
# Line 1138 | Line 1484 | public abstract class ForkJoinTask<V> im
1484      }
1485  
1486      /**
1487 <     * Reconstitutes the instance from a stream (that is, deserializes it).
1142 <     *
1143 <     * @param s the stream
1487 >     * Reconstitutes this task from a stream (that is, deserializes it).
1488       */
1489      private void readObject(java.io.ObjectInputStream s)
1490          throws java.io.IOException, ClassNotFoundException {
1491          s.defaultReadObject();
1492          Object ex = s.readObject();
1493          if (ex != null)
1494 <            setExceptionalCompletion((Throwable) ex);
1494 >            setExceptionalCompletion((Throwable)ex);
1495      }
1496  
1497      // Unsafe mechanics
1498 <
1499 <    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1500 <    private static final long statusOffset =
1501 <        objectFieldOffset("status", ForkJoinTask.class);
1502 <
1503 <    private static long objectFieldOffset(String field, Class<?> klazz) {
1498 >    private static final sun.misc.Unsafe U;
1499 >    private static final long STATUS;
1500 >    static {
1501 >        exceptionTableLock = new ReentrantLock();
1502 >        exceptionTableRefQueue = new ReferenceQueue<Object>();
1503 >        exceptionTable = new ExceptionNode[EXCEPTION_MAP_CAPACITY];
1504          try {
1505 <            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field));
1506 <        } catch (NoSuchFieldException e) {
1507 <            // Convert Exception to corresponding Error
1508 <            NoSuchFieldError error = new NoSuchFieldError(field);
1509 <            error.initCause(e);
1166 <            throw error;
1505 >            U = getUnsafe();
1506 >            STATUS = U.objectFieldOffset
1507 >                (ForkJoinTask.class.getDeclaredField("status"));
1508 >        } catch (Exception e) {
1509 >            throw new Error(e);
1510          }
1511      }
1512  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines