changeset 7489:a66e0dfd2973

Updates to JSR-166 code from Doug's workspace Contributed-by: dl
author mduigou
date Wed, 20 Feb 2013 15:42:21 -0800
parents c499c13fa66a
children 70bc1cf8584a
files src/share/classes/java/util/concurrent/AbstractExecutorService.java src/share/classes/java/util/concurrent/ArrayBlockingQueue.java src/share/classes/java/util/concurrent/BlockingDeque.java src/share/classes/java/util/concurrent/BlockingQueue.java src/share/classes/java/util/concurrent/BrokenBarrierException.java src/share/classes/java/util/concurrent/Callable.java src/share/classes/java/util/concurrent/CancellationException.java src/share/classes/java/util/concurrent/CompletableFuture.java src/share/classes/java/util/concurrent/CompletionException.java src/share/classes/java/util/concurrent/CompletionService.java src/share/classes/java/util/concurrent/ConcurrentLinkedDeque.java src/share/classes/java/util/concurrent/ConcurrentLinkedQueue.java src/share/classes/java/util/concurrent/ConcurrentMap.java src/share/classes/java/util/concurrent/ConcurrentSkipListSet.java src/share/classes/java/util/concurrent/CountedCompleter.java src/share/classes/java/util/concurrent/CyclicBarrier.java src/share/classes/java/util/concurrent/DelayQueue.java src/share/classes/java/util/concurrent/Delayed.java src/share/classes/java/util/concurrent/DoubleAdder.java src/share/classes/java/util/concurrent/DoubleMaxUpdater.java src/share/classes/java/util/concurrent/Exchanger.java src/share/classes/java/util/concurrent/ExecutionException.java src/share/classes/java/util/concurrent/Executor.java src/share/classes/java/util/concurrent/ExecutorService.java src/share/classes/java/util/concurrent/Executors.java src/share/classes/java/util/concurrent/ForkJoinPool.java src/share/classes/java/util/concurrent/ForkJoinTask.java src/share/classes/java/util/concurrent/Future.java src/share/classes/java/util/concurrent/FutureTask.java src/share/classes/java/util/concurrent/LinkedTransferQueue.java src/share/classes/java/util/concurrent/LongAdder.java src/share/classes/java/util/concurrent/LongMaxUpdater.java src/share/classes/java/util/concurrent/Phaser.java src/share/classes/java/util/concurrent/PriorityBlockingQueue.java src/share/classes/java/util/concurrent/RecursiveAction.java src/share/classes/java/util/concurrent/RecursiveTask.java src/share/classes/java/util/concurrent/RejectedExecutionException.java src/share/classes/java/util/concurrent/RunnableFuture.java src/share/classes/java/util/concurrent/RunnableScheduledFuture.java src/share/classes/java/util/concurrent/ScheduledExecutorService.java src/share/classes/java/util/concurrent/ScheduledThreadPoolExecutor.java src/share/classes/java/util/concurrent/SequenceLock.java src/share/classes/java/util/concurrent/Striped64.java src/share/classes/java/util/concurrent/SynchronousQueue.java src/share/classes/java/util/concurrent/ThreadLocalRandom.java src/share/classes/java/util/concurrent/ThreadPoolExecutor.java src/share/classes/java/util/concurrent/TimeUnit.java src/share/classes/java/util/concurrent/TimeoutException.java src/share/classes/java/util/concurrent/atomic/AtomicInteger.java src/share/classes/java/util/concurrent/atomic/AtomicIntegerArray.java src/share/classes/java/util/concurrent/atomic/AtomicLong.java src/share/classes/java/util/concurrent/atomic/AtomicLongFieldUpdater.java src/share/classes/java/util/concurrent/atomic/AtomicReferenceArray.java src/share/classes/java/util/concurrent/atomic/AtomicReferenceFieldUpdater.java src/share/classes/java/util/concurrent/atomic/DoubleAccumulator.java src/share/classes/java/util/concurrent/atomic/DoubleAdder.java src/share/classes/java/util/concurrent/atomic/Fences.java src/share/classes/java/util/concurrent/atomic/LongAccumulator.java src/share/classes/java/util/concurrent/atomic/package-info.java src/share/classes/java/util/concurrent/extra/AtomicDouble.java src/share/classes/java/util/concurrent/extra/AtomicDoubleArray.java src/share/classes/java/util/concurrent/extra/ReadMostlyVector.java src/share/classes/java/util/concurrent/locks/AbstractOwnableSynchronizer.java src/share/classes/java/util/concurrent/locks/AbstractQueuedLongSynchronizer.java src/share/classes/java/util/concurrent/locks/AbstractQueuedSynchronizer.java src/share/classes/java/util/concurrent/locks/Lock.java src/share/classes/java/util/concurrent/locks/LockSupport.java src/share/classes/java/util/concurrent/locks/ReadWriteLock.java src/share/classes/java/util/concurrent/locks/ReentrantLock.java src/share/classes/java/util/concurrent/locks/ReentrantReadWriteLock.java src/share/classes/java/util/concurrent/locks/StampedLock.java src/share/classes/java/util/concurrent/package-info.java
diffstat 72 files changed, 5625 insertions(+), 5732 deletions(-) [+]
line wrap: on
line diff
--- a/src/share/classes/java/util/concurrent/AbstractExecutorService.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/AbstractExecutorService.java	Wed Feb 20 15:42:21 2013 -0800
@@ -38,19 +38,19 @@
 
 /**
  * Provides default implementations of {@link ExecutorService}
- * execution methods. This class implements the <tt>submit</tt>,
- * <tt>invokeAny</tt> and <tt>invokeAll</tt> methods using a
- * {@link RunnableFuture} returned by <tt>newTaskFor</tt>, which defaults
+ * execution methods. This class implements the {@code submit},
+ * {@code invokeAny} and {@code invokeAll} methods using a
+ * {@link RunnableFuture} returned by {@code newTaskFor}, which defaults
  * to the {@link FutureTask} class provided in this package.  For example,
- * the implementation of <tt>submit(Runnable)</tt> creates an
- * associated <tt>RunnableFuture</tt> that is executed and
- * returned. Subclasses may override the <tt>newTaskFor</tt> methods
- * to return <tt>RunnableFuture</tt> implementations other than
- * <tt>FutureTask</tt>.
+ * the implementation of {@code submit(Runnable)} creates an
+ * associated {@code RunnableFuture} that is executed and
+ * returned. Subclasses may override the {@code newTaskFor} methods
+ * to return {@code RunnableFuture} implementations other than
+ * {@code FutureTask}.
  *
  * <p> <b>Extension example</b>. Here is a sketch of a class
  * that customizes {@link ThreadPoolExecutor} to use
- * a <tt>CustomTask</tt> class instead of the default <tt>FutureTask</tt>:
+ * a {@code CustomTask} class instead of the default {@code FutureTask}:
  *  <pre> {@code
  * public class CustomThreadPoolExecutor extends ThreadPoolExecutor {
  *
@@ -71,15 +71,15 @@
 public abstract class AbstractExecutorService implements ExecutorService {
 
     /**
-     * Returns a <tt>RunnableFuture</tt> for the given runnable and default
+     * Returns a {@code RunnableFuture} for the given runnable and default
      * value.
      *
      * @param runnable the runnable task being wrapped
      * @param value the default value for the returned future
-     * @return a <tt>RunnableFuture</tt> which when run will run the
-     * underlying runnable and which, as a <tt>Future</tt>, will yield
+     * @return a {@code RunnableFuture} which, when run, will run the
+     * underlying runnable and which, as a {@code Future}, will yield
      * the given value as its result and provide for cancellation of
-     * the underlying task.
+     * the underlying task
      * @since 1.6
      */
     protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
@@ -87,13 +87,13 @@
     }
 
     /**
-     * Returns a <tt>RunnableFuture</tt> for the given callable task.
+     * Returns a {@code RunnableFuture} for the given callable task.
      *
      * @param callable the callable task being wrapped
-     * @return a <tt>RunnableFuture</tt> which when run will call the
-     * underlying callable and which, as a <tt>Future</tt>, will yield
+     * @return a {@code RunnableFuture} which, when run, will call the
+     * underlying callable and which, as a {@code Future}, will yield
      * the callable's result as its result and provide for
-     * cancellation of the underlying task.
+     * cancellation of the underlying task
      * @since 1.6
      */
     protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
@@ -144,7 +144,7 @@
         int ntasks = tasks.size();
         if (ntasks == 0)
             throw new IllegalArgumentException();
-        List<Future<T>> futures= new ArrayList<Future<T>>(ntasks);
+        ArrayList<Future<T>> futures = new ArrayList<Future<T>>(ntasks);
         ExecutorCompletionService<T> ecs =
             new ExecutorCompletionService<T>(this);
 
@@ -202,8 +202,8 @@
             throw ee;
 
         } finally {
-            for (Future<T> f : futures)
-                f.cancel(true);
+            for (int i = 0, size = futures.size(); i < size; i++)
+                futures.get(i).cancel(true);
         }
     }
 
@@ -227,7 +227,7 @@
         throws InterruptedException {
         if (tasks == null)
             throw new NullPointerException();
-        List<Future<T>> futures = new ArrayList<Future<T>>(tasks.size());
+        ArrayList<Future<T>> futures = new ArrayList<Future<T>>(tasks.size());
         boolean done = false;
         try {
             for (Callable<T> t : tasks) {
@@ -235,7 +235,8 @@
                 futures.add(f);
                 execute(f);
             }
-            for (Future<T> f : futures) {
+            for (int i = 0, size = futures.size(); i < size; i++) {
+                Future<T> f = futures.get(i);
                 if (!f.isDone()) {
                     try {
                         f.get();
@@ -248,8 +249,8 @@
             return futures;
         } finally {
             if (!done)
-                for (Future<T> f : futures)
-                    f.cancel(true);
+                for (int i = 0, size = futures.size(); i < size; i++)
+                    futures.get(i).cancel(true);
         }
     }
 
@@ -259,25 +260,26 @@
         if (tasks == null)
             throw new NullPointerException();
         long nanos = unit.toNanos(timeout);
-        List<Future<T>> futures = new ArrayList<Future<T>>(tasks.size());
+        ArrayList<Future<T>> futures = new ArrayList<Future<T>>(tasks.size());
         boolean done = false;
         try {
             for (Callable<T> t : tasks)
                 futures.add(newTaskFor(t));
 
             final long deadline = System.nanoTime() + nanos;
+            final int size = futures.size();
 
             // Interleave time checks and calls to execute in case
             // executor doesn't have any/much parallelism.
-            Iterator<Future<T>> it = futures.iterator();
-            while (it.hasNext()) {
-                execute((Runnable)(it.next()));
+            for (int i = 0; i < size; i++) {
+                execute((Runnable)futures.get(i));
                 nanos = deadline - System.nanoTime();
                 if (nanos <= 0L)
                     return futures;
             }
 
-            for (Future<T> f : futures) {
+            for (int i = 0; i < size; i++) {
+                Future<T> f = futures.get(i);
                 if (!f.isDone()) {
                     if (nanos <= 0L)
                         return futures;
@@ -295,8 +297,8 @@
             return futures;
         } finally {
             if (!done)
-                for (Future<T> f : futures)
-                    f.cancel(true);
+                for (int i = 0, size = futures.size(); i < size; i++)
+                    futures.get(i).cancel(true);
         }
     }
 
--- a/src/share/classes/java/util/concurrent/ArrayBlockingQueue.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/ArrayBlockingQueue.java	Wed Feb 20 15:42:21 2013 -0800
@@ -45,6 +45,7 @@
 import java.util.Spliterator;
 import java.util.stream.Stream;
 import java.util.stream.Streams;
+import java.util.function.Consumer;
 
 /**
  * A bounded {@linkplain BlockingQueue blocking queue} backed by an
--- a/src/share/classes/java/util/concurrent/BlockingDeque.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/BlockingDeque.java	Wed Feb 20 15:42:21 2013 -0800
@@ -41,17 +41,18 @@
  * for the deque to become non-empty when retrieving an element, and wait for
  * space to become available in the deque when storing an element.
  *
- * <p><tt>BlockingDeque</tt> methods come in four forms, with different ways
+ * <p>{@code BlockingDeque} methods come in four forms, with different ways
  * of handling operations that cannot be satisfied immediately, but may be
  * satisfied at some point in the future:
  * one throws an exception, the second returns a special value (either
- * <tt>null</tt> or <tt>false</tt>, depending on the operation), the third
+ * {@code null} or {@code false}, depending on the operation), the third
  * blocks the current thread indefinitely until the operation can succeed,
  * and the fourth blocks for only a given maximum time limit before giving
  * up.  These methods are summarized in the following table:
  *
  * <p>
  * <table BORDER CELLPADDING=3 CELLSPACING=1>
+ * <caption>Summary of BlockingDeque methods</caption>
  *  <tr>
  *    <td ALIGN=CENTER COLSPAN = 5> <b>First Element (Head)</b></td>
  *  </tr>
@@ -116,20 +117,21 @@
  *  </tr>
  * </table>
  *
- * <p>Like any {@link BlockingQueue}, a <tt>BlockingDeque</tt> is thread safe,
+ * <p>Like any {@link BlockingQueue}, a {@code BlockingDeque} is thread safe,
  * does not permit null elements, and may (or may not) be
  * capacity-constrained.
  *
- * <p>A <tt>BlockingDeque</tt> implementation may be used directly as a FIFO
- * <tt>BlockingQueue</tt>. The methods inherited from the
- * <tt>BlockingQueue</tt> interface are precisely equivalent to
- * <tt>BlockingDeque</tt> methods as indicated in the following table:
+ * <p>A {@code BlockingDeque} implementation may be used directly as a FIFO
+ * {@code BlockingQueue}. The methods inherited from the
+ * {@code BlockingQueue} interface are precisely equivalent to
+ * {@code BlockingDeque} methods as indicated in the following table:
  *
  * <p>
  * <table BORDER CELLPADDING=3 CELLSPACING=1>
+ * <caption>Comparison of BlockingQueue and BlockingDeque methods</caption>
  *  <tr>
- *    <td ALIGN=CENTER> <b><tt>BlockingQueue</tt> Method</b></td>
- *    <td ALIGN=CENTER> <b>Equivalent <tt>BlockingDeque</tt> Method</b></td>
+ *    <td ALIGN=CENTER> <b>{@code BlockingQueue} Method</b></td>
+ *    <td ALIGN=CENTER> <b>Equivalent {@code BlockingDeque} Method</b></td>
  *  </tr>
  *  <tr>
  *    <td ALIGN=CENTER COLSPAN = 2> <b>Insert</b></td>
@@ -208,7 +210,7 @@
     /**
      * Inserts the specified element at the front of this deque if it is
      * possible to do so immediately without violating capacity restrictions,
-     * throwing an <tt>IllegalStateException</tt> if no space is currently
+     * throwing an {@code IllegalStateException} if no space is currently
      * available.  When using a capacity-restricted deque, it is generally
      * preferable to use {@link #offerFirst(Object) offerFirst}.
      *
@@ -223,7 +225,7 @@
     /**
      * Inserts the specified element at the end of this deque if it is
      * possible to do so immediately without violating capacity restrictions,
-     * throwing an <tt>IllegalStateException</tt> if no space is currently
+     * throwing an {@code IllegalStateException} if no space is currently
      * available.  When using a capacity-restricted deque, it is generally
      * preferable to use {@link #offerLast(Object) offerLast}.
      *
@@ -238,7 +240,7 @@
     /**
      * Inserts the specified element at the front of this deque if it is
      * possible to do so immediately without violating capacity restrictions,
-     * returning <tt>true</tt> upon success and <tt>false</tt> if no space is
+     * returning {@code true} upon success and {@code false} if no space is
      * currently available.
      * When using a capacity-restricted deque, this method is generally
      * preferable to the {@link #addFirst(Object) addFirst} method, which can
@@ -254,7 +256,7 @@
     /**
      * Inserts the specified element at the end of this deque if it is
      * possible to do so immediately without violating capacity restrictions,
-     * returning <tt>true</tt> upon success and <tt>false</tt> if no space is
+     * returning {@code true} upon success and {@code false} if no space is
      * currently available.
      * When using a capacity-restricted deque, this method is generally
      * preferable to the {@link #addLast(Object) addLast} method, which can
@@ -302,10 +304,10 @@
      *
      * @param e the element to add
      * @param timeout how long to wait before giving up, in units of
-     *        <tt>unit</tt>
-     * @param unit a <tt>TimeUnit</tt> determining how to interpret the
-     *        <tt>timeout</tt> parameter
-     * @return <tt>true</tt> if successful, or <tt>false</tt> if
+     *        {@code unit}
+     * @param unit a {@code TimeUnit} determining how to interpret the
+     *        {@code timeout} parameter
+     * @return {@code true} if successful, or {@code false} if
      *         the specified waiting time elapses before space is available
      * @throws InterruptedException if interrupted while waiting
      * @throws ClassCastException if the class of the specified element
@@ -324,10 +326,10 @@
      *
      * @param e the element to add
      * @param timeout how long to wait before giving up, in units of
-     *        <tt>unit</tt>
-     * @param unit a <tt>TimeUnit</tt> determining how to interpret the
-     *        <tt>timeout</tt> parameter
-     * @return <tt>true</tt> if successful, or <tt>false</tt> if
+     *        {@code unit}
+     * @param unit a {@code TimeUnit} determining how to interpret the
+     *        {@code timeout} parameter
+     * @return {@code true} if successful, or {@code false} if
      *         the specified waiting time elapses before space is available
      * @throws InterruptedException if interrupted while waiting
      * @throws ClassCastException if the class of the specified element
@@ -363,10 +365,10 @@
      * become available.
      *
      * @param timeout how long to wait before giving up, in units of
-     *        <tt>unit</tt>
-     * @param unit a <tt>TimeUnit</tt> determining how to interpret the
-     *        <tt>timeout</tt> parameter
-     * @return the head of this deque, or <tt>null</tt> if the specified
+     *        {@code unit}
+     * @param unit a {@code TimeUnit} determining how to interpret the
+     *        {@code timeout} parameter
+     * @return the head of this deque, or {@code null} if the specified
      *         waiting time elapses before an element is available
      * @throws InterruptedException if interrupted while waiting
      */
@@ -379,10 +381,10 @@
      * become available.
      *
      * @param timeout how long to wait before giving up, in units of
-     *        <tt>unit</tt>
-     * @param unit a <tt>TimeUnit</tt> determining how to interpret the
-     *        <tt>timeout</tt> parameter
-     * @return the tail of this deque, or <tt>null</tt> if the specified
+     *        {@code unit}
+     * @param unit a {@code TimeUnit} determining how to interpret the
+     *        {@code timeout} parameter
+     * @return the tail of this deque, or {@code null} if the specified
      *         waiting time elapses before an element is available
      * @throws InterruptedException if interrupted while waiting
      */
@@ -392,13 +394,13 @@
     /**
      * Removes the first occurrence of the specified element from this deque.
      * If the deque does not contain the element, it is unchanged.
-     * More formally, removes the first element <tt>e</tt> such that
-     * <tt>o.equals(e)</tt> (if such an element exists).
-     * Returns <tt>true</tt> if this deque contained the specified element
+     * More formally, removes the first element {@code e} such that
+     * {@code o.equals(e)} (if such an element exists).
+     * Returns {@code true} if this deque contained the specified element
      * (or equivalently, if this deque changed as a result of the call).
      *
      * @param o element to be removed from this deque, if present
-     * @return <tt>true</tt> if an element was removed as a result of this call
+     * @return {@code true} if an element was removed as a result of this call
      * @throws ClassCastException if the class of the specified element
      *         is incompatible with this deque
      *         (<a href="../Collection.html#optional-restrictions">optional</a>)
@@ -410,13 +412,13 @@
     /**
      * Removes the last occurrence of the specified element from this deque.
      * If the deque does not contain the element, it is unchanged.
-     * More formally, removes the last element <tt>e</tt> such that
-     * <tt>o.equals(e)</tt> (if such an element exists).
-     * Returns <tt>true</tt> if this deque contained the specified element
+     * More formally, removes the last element {@code e} such that
+     * {@code o.equals(e)} (if such an element exists).
+     * Returns {@code true} if this deque contained the specified element
      * (or equivalently, if this deque changed as a result of the call).
      *
      * @param o element to be removed from this deque, if present
-     * @return <tt>true</tt> if an element was removed as a result of this call
+     * @return {@code true} if an element was removed as a result of this call
      * @throws ClassCastException if the class of the specified element
      *         is incompatible with this deque
      *         (<a href="../Collection.html#optional-restrictions">optional</a>)
@@ -431,8 +433,8 @@
      * Inserts the specified element into the queue represented by this deque
      * (in other words, at the tail of this deque) if it is possible to do so
      * immediately without violating capacity restrictions, returning
-     * <tt>true</tt> upon success and throwing an
-     * <tt>IllegalStateException</tt> if no space is currently available.
+     * {@code true} upon success and throwing an
+     * {@code IllegalStateException} if no space is currently available.
      * When using a capacity-restricted deque, it is generally preferable to
      * use {@link #offer(Object) offer}.
      *
@@ -452,7 +454,7 @@
      * Inserts the specified element into the queue represented by this deque
      * (in other words, at the tail of this deque) if it is possible to do so
      * immediately without violating capacity restrictions, returning
-     * <tt>true</tt> upon success and <tt>false</tt> if no space is currently
+     * {@code true} upon success and {@code false} if no space is currently
      * available.  When using a capacity-restricted deque, this method is
      * generally preferable to the {@link #add} method, which can fail to
      * insert an element only by throwing an exception.
@@ -494,8 +496,8 @@
      * {@link #offerLast(Object,long,TimeUnit) offerLast}.
      *
      * @param e the element to add
-     * @return <tt>true</tt> if the element was added to this deque, else
-     *         <tt>false</tt>
+     * @return {@code true} if the element was added to this deque, else
+     *         {@code false}
      * @throws InterruptedException {@inheritDoc}
      * @throws ClassCastException if the class of the specified element
      *         prevents it from being added to this deque
@@ -522,11 +524,11 @@
     /**
      * Retrieves and removes the head of the queue represented by this deque
      * (in other words, the first element of this deque), or returns
-     * <tt>null</tt> if this deque is empty.
+     * {@code null} if this deque is empty.
      *
      * <p>This method is equivalent to {@link #pollFirst()}.
      *
-     * @return the head of this deque, or <tt>null</tt> if this deque is empty
+     * @return the head of this deque, or {@code null} if this deque is empty
      */
     E poll();
 
@@ -550,7 +552,7 @@
      * <p>This method is equivalent to
      * {@link #pollFirst(long,TimeUnit) pollFirst}.
      *
-     * @return the head of this deque, or <tt>null</tt> if the
+     * @return the head of this deque, or {@code null} if the
      *         specified waiting time elapses before an element is available
      * @throws InterruptedException if interrupted while waiting
      */
@@ -573,27 +575,27 @@
     /**
      * Retrieves, but does not remove, the head of the queue represented by
      * this deque (in other words, the first element of this deque), or
-     * returns <tt>null</tt> if this deque is empty.
+     * returns {@code null} if this deque is empty.
      *
      * <p>This method is equivalent to {@link #peekFirst() peekFirst}.
      *
-     * @return the head of this deque, or <tt>null</tt> if this deque is empty
+     * @return the head of this deque, or {@code null} if this deque is empty
      */
     E peek();
 
     /**
      * Removes the first occurrence of the specified element from this deque.
      * If the deque does not contain the element, it is unchanged.
-     * More formally, removes the first element <tt>e</tt> such that
-     * <tt>o.equals(e)</tt> (if such an element exists).
-     * Returns <tt>true</tt> if this deque contained the specified element
+     * More formally, removes the first element {@code e} such that
+     * {@code o.equals(e)} (if such an element exists).
+     * Returns {@code true} if this deque contained the specified element
      * (or equivalently, if this deque changed as a result of the call).
      *
      * <p>This method is equivalent to
      * {@link #removeFirstOccurrence(Object) removeFirstOccurrence}.
      *
      * @param o element to be removed from this deque, if present
-     * @return <tt>true</tt> if this deque changed as a result of the call
+     * @return {@code true} if this deque changed as a result of the call
      * @throws ClassCastException if the class of the specified element
      *         is incompatible with this deque
      *         (<a href="../Collection.html#optional-restrictions">optional</a>)
@@ -603,12 +605,12 @@
     boolean remove(Object o);
 
     /**
-     * Returns <tt>true</tt> if this deque contains the specified element.
-     * More formally, returns <tt>true</tt> if and only if this deque contains
-     * at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>.
+     * Returns {@code true} if this deque contains the specified element.
+     * More formally, returns {@code true} if and only if this deque contains
+     * at least one element {@code e} such that {@code o.equals(e)}.
      *
      * @param o object to be checked for containment in this deque
-     * @return <tt>true</tt> if this deque contains the specified element
+     * @return {@code true} if this deque contains the specified element
      * @throws ClassCastException if the class of the specified element
      *         is incompatible with this deque
      *         (<a href="../Collection.html#optional-restrictions">optional</a>)
--- a/src/share/classes/java/util/concurrent/BlockingQueue.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/BlockingQueue.java	Wed Feb 20 15:42:21 2013 -0800
@@ -44,17 +44,18 @@
  * element, and wait for space to become available in the queue when
  * storing an element.
  *
- * <p><tt>BlockingQueue</tt> methods come in four forms, with different ways
+ * <p>{@code BlockingQueue} methods come in four forms, with different ways
  * of handling operations that cannot be satisfied immediately, but may be
  * satisfied at some point in the future:
  * one throws an exception, the second returns a special value (either
- * <tt>null</tt> or <tt>false</tt>, depending on the operation), the third
+ * {@code null} or {@code false}, depending on the operation), the third
  * blocks the current thread indefinitely until the operation can succeed,
  * and the fourth blocks for only a given maximum time limit before giving
  * up.  These methods are summarized in the following table:
  *
  * <p>
  * <table BORDER CELLPADDING=3 CELLSPACING=1>
+ * <caption>Summary of BlockingQueue methods</caption>
  *  <tr>
  *    <td></td>
  *    <td ALIGN=CENTER><em>Throws exception</em></td>
@@ -85,37 +86,37 @@
  *  </tr>
  * </table>
  *
- * <p>A <tt>BlockingQueue</tt> does not accept <tt>null</tt> elements.
- * Implementations throw <tt>NullPointerException</tt> on attempts
- * to <tt>add</tt>, <tt>put</tt> or <tt>offer</tt> a <tt>null</tt>.  A
- * <tt>null</tt> is used as a sentinel value to indicate failure of
- * <tt>poll</tt> operations.
+ * <p>A {@code BlockingQueue} does not accept {@code null} elements.
+ * Implementations throw {@code NullPointerException} on attempts
+ * to {@code add}, {@code put} or {@code offer} a {@code null}.  A
+ * {@code null} is used as a sentinel value to indicate failure of
+ * {@code poll} operations.
  *
- * <p>A <tt>BlockingQueue</tt> may be capacity bounded. At any given
- * time it may have a <tt>remainingCapacity</tt> beyond which no
- * additional elements can be <tt>put</tt> without blocking.
- * A <tt>BlockingQueue</tt> without any intrinsic capacity constraints always
- * reports a remaining capacity of <tt>Integer.MAX_VALUE</tt>.
+ * <p>A {@code BlockingQueue} may be capacity bounded. At any given
+ * time it may have a {@code remainingCapacity} beyond which no
+ * additional elements can be {@code put} without blocking.
+ * A {@code BlockingQueue} without any intrinsic capacity constraints always
+ * reports a remaining capacity of {@code Integer.MAX_VALUE}.
  *
- * <p> <tt>BlockingQueue</tt> implementations are designed to be used
+ * <p> {@code BlockingQueue} implementations are designed to be used
  * primarily for producer-consumer queues, but additionally support
  * the {@link java.util.Collection} interface.  So, for example, it is
  * possible to remove an arbitrary element from a queue using
- * <tt>remove(x)</tt>. However, such operations are in general
+ * {@code remove(x)}. However, such operations are in general
  * <em>not</em> performed very efficiently, and are intended for only
  * occasional use, such as when a queued message is cancelled.
  *
- * <p> <tt>BlockingQueue</tt> implementations are thread-safe.  All
+ * <p> {@code BlockingQueue} implementations are thread-safe.  All
  * queuing methods achieve their effects atomically using internal
  * locks or other forms of concurrency control. However, the
- * <em>bulk</em> Collection operations <tt>addAll</tt>,
- * <tt>containsAll</tt>, <tt>retainAll</tt> and <tt>removeAll</tt> are
+ * <em>bulk</em> Collection operations {@code addAll},
+ * {@code containsAll}, {@code retainAll} and {@code removeAll} are
  * <em>not</em> necessarily performed atomically unless specified
  * otherwise in an implementation. So it is possible, for example, for
- * <tt>addAll(c)</tt> to fail (throwing an exception) after adding
- * only some of the elements in <tt>c</tt>.
+ * {@code addAll(c)} to fail (throwing an exception) after adding
+ * only some of the elements in {@code c}.
  *
- * <p>A <tt>BlockingQueue</tt> does <em>not</em> intrinsically support
+ * <p>A {@code BlockingQueue} does <em>not</em> intrinsically support
  * any kind of &quot;close&quot; or &quot;shutdown&quot; operation to
  * indicate that no more items will be added.  The needs and usage of
  * such features tend to be implementation-dependent. For example, a
@@ -125,7 +126,7 @@
  *
  * <p>
  * Usage example, based on a typical producer-consumer scenario.
- * Note that a <tt>BlockingQueue</tt> can safely be used with multiple
+ * Note that a {@code BlockingQueue} can safely be used with multiple
  * producers and multiple consumers.
  *  <pre> {@code
  * class Producer implements Runnable {
@@ -181,13 +182,13 @@
     /**
      * Inserts the specified element into this queue if it is possible to do
      * so immediately without violating capacity restrictions, returning
-     * <tt>true</tt> upon success and throwing an
-     * <tt>IllegalStateException</tt> if no space is currently available.
+     * {@code true} upon success and throwing an
+     * {@code IllegalStateException} if no space is currently available.
      * When using a capacity-restricted queue, it is generally preferable to
      * use {@link #offer(Object) offer}.
      *
      * @param e the element to add
-     * @return <tt>true</tt> (as specified by {@link Collection#add})
+     * @return {@code true} (as specified by {@link Collection#add})
      * @throws IllegalStateException if the element cannot be added at this
      *         time due to capacity restrictions
      * @throws ClassCastException if the class of the specified element
@@ -201,14 +202,14 @@
     /**
      * Inserts the specified element into this queue if it is possible to do
      * so immediately without violating capacity restrictions, returning
-     * <tt>true</tt> upon success and <tt>false</tt> if no space is currently
+     * {@code true} upon success and {@code false} if no space is currently
      * available.  When using a capacity-restricted queue, this method is
      * generally preferable to {@link #add}, which can fail to insert an
      * element only by throwing an exception.
      *
      * @param e the element to add
-     * @return <tt>true</tt> if the element was added to this queue, else
-     *         <tt>false</tt>
+     * @return {@code true} if the element was added to this queue, else
+     *         {@code false}
      * @throws ClassCastException if the class of the specified element
      *         prevents it from being added to this queue
      * @throws NullPointerException if the specified element is null
@@ -237,10 +238,10 @@
      *
      * @param e the element to add
      * @param timeout how long to wait before giving up, in units of
-     *        <tt>unit</tt>
-     * @param unit a <tt>TimeUnit</tt> determining how to interpret the
-     *        <tt>timeout</tt> parameter
-     * @return <tt>true</tt> if successful, or <tt>false</tt> if
+     *        {@code unit}
+     * @param unit a {@code TimeUnit} determining how to interpret the
+     *        {@code timeout} parameter
+     * @return {@code true} if successful, or {@code false} if
      *         the specified waiting time elapses before space is available
      * @throws InterruptedException if interrupted while waiting
      * @throws ClassCastException if the class of the specified element
@@ -266,10 +267,10 @@
      * specified wait time if necessary for an element to become available.
      *
      * @param timeout how long to wait before giving up, in units of
-     *        <tt>unit</tt>
-     * @param unit a <tt>TimeUnit</tt> determining how to interpret the
-     *        <tt>timeout</tt> parameter
-     * @return the head of this queue, or <tt>null</tt> if the
+     *        {@code unit}
+     * @param unit a {@code TimeUnit} determining how to interpret the
+     *        {@code timeout} parameter
+     * @return the head of this queue, or {@code null} if the
      *         specified waiting time elapses before an element is available
      * @throws InterruptedException if interrupted while waiting
      */
@@ -279,11 +280,11 @@
     /**
      * Returns the number of additional elements that this queue can ideally
      * (in the absence of memory or resource constraints) accept without
-     * blocking, or <tt>Integer.MAX_VALUE</tt> if there is no intrinsic
+     * blocking, or {@code Integer.MAX_VALUE} if there is no intrinsic
      * limit.
      *
      * <p>Note that you <em>cannot</em> always tell if an attempt to insert
-     * an element will succeed by inspecting <tt>remainingCapacity</tt>
+     * an element will succeed by inspecting {@code remainingCapacity}
      * because it may be the case that another thread is about to
      * insert or remove an element.
      *
@@ -293,14 +294,14 @@
 
     /**
      * Removes a single instance of the specified element from this queue,
-     * if it is present.  More formally, removes an element <tt>e</tt> such
-     * that <tt>o.equals(e)</tt>, if this queue contains one or more such
+     * if it is present.  More formally, removes an element {@code e} such
+     * that {@code o.equals(e)}, if this queue contains one or more such
      * elements.
-     * Returns <tt>true</tt> if this queue contained the specified element
+     * Returns {@code true} if this queue contained the specified element
      * (or equivalently, if this queue changed as a result of the call).
      *
      * @param o element to be removed from this queue, if present
-     * @return <tt>true</tt> if this queue changed as a result of the call
+     * @return {@code true} if this queue changed as a result of the call
      * @throws ClassCastException if the class of the specified element
      *         is incompatible with this queue
      *         (<a href="../Collection.html#optional-restrictions">optional</a>)
@@ -310,12 +311,12 @@
     boolean remove(Object o);
 
     /**
-     * Returns <tt>true</tt> if this queue contains the specified element.
-     * More formally, returns <tt>true</tt> if and only if this queue contains
-     * at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>.
+     * Returns {@code true} if this queue contains the specified element.
+     * More formally, returns {@code true} if and only if this queue contains
+     * at least one element {@code e} such that {@code o.equals(e)}.
      *
      * @param o object to be checked for containment in this queue
-     * @return <tt>true</tt> if this queue contains the specified element
+     * @return {@code true} if this queue contains the specified element
      * @throws ClassCastException if the class of the specified element
      *         is incompatible with this queue
      *         (<a href="../Collection.html#optional-restrictions">optional</a>)
@@ -329,10 +330,10 @@
      * to the given collection.  This operation may be more
      * efficient than repeatedly polling this queue.  A failure
      * encountered while attempting to add elements to
-     * collection <tt>c</tt> may result in elements being in neither,
+     * collection {@code c} may result in elements being in neither,
      * either or both collections when the associated exception is
      * thrown.  Attempts to drain a queue to itself result in
-     * <tt>IllegalArgumentException</tt>. Further, the behavior of
+     * {@code IllegalArgumentException}. Further, the behavior of
      * this operation is undefined if the specified collection is
      * modified while the operation is in progress.
      *
@@ -353,10 +354,10 @@
      * Removes at most the given number of available elements from
      * this queue and adds them to the given collection.  A failure
      * encountered while attempting to add elements to
-     * collection <tt>c</tt> may result in elements being in neither,
+     * collection {@code c} may result in elements being in neither,
      * either or both collections when the associated exception is
      * thrown.  Attempts to drain a queue to itself result in
-     * <tt>IllegalArgumentException</tt>. Further, the behavior of
+     * {@code IllegalArgumentException}. Further, the behavior of
      * this operation is undefined if the specified collection is
      * modified while the operation is in progress.
      *
--- a/src/share/classes/java/util/concurrent/BrokenBarrierException.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/BrokenBarrierException.java	Wed Feb 20 15:42:21 2013 -0800
@@ -49,13 +49,13 @@
     private static final long serialVersionUID = 7117394618823254244L;
 
     /**
-     * Constructs a <tt>BrokenBarrierException</tt> with no specified detail
+     * Constructs a {@code BrokenBarrierException} with no specified detail
      * message.
      */
     public BrokenBarrierException() {}
 
     /**
-     * Constructs a <tt>BrokenBarrierException</tt> with the specified
+     * Constructs a {@code BrokenBarrierException} with the specified
      * detail message.
      *
      * @param message the detail message
--- a/src/share/classes/java/util/concurrent/Callable.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/Callable.java	Wed Feb 20 15:42:21 2013 -0800
@@ -38,21 +38,21 @@
 /**
  * A task that returns a result and may throw an exception.
  * Implementors define a single method with no arguments called
- * <tt>call</tt>.
+ * {@code call}.
  *
- * <p>The <tt>Callable</tt> interface is similar to {@link
+ * <p>The {@code Callable} interface is similar to {@link
  * java.lang.Runnable}, in that both are designed for classes whose
  * instances are potentially executed by another thread.  A
- * <tt>Runnable</tt>, however, does not return a result and cannot
+ * {@code Runnable}, however, does not return a result and cannot
  * throw a checked exception.
  *
  * <p> The {@link Executors} class contains utility methods to
- * convert from other common forms to <tt>Callable</tt> classes.
+ * convert from other common forms to {@code Callable} classes.
  *
  * @see Executor
  * @since 1.5
  * @author Doug Lea
- * @param <V> the result type of method <tt>call</tt>
+ * @param <V> the result type of method {@code call}
  */
 public interface Callable<V> {
     /**
--- a/src/share/classes/java/util/concurrent/CancellationException.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/CancellationException.java	Wed Feb 20 15:42:21 2013 -0800
@@ -47,12 +47,12 @@
     private static final long serialVersionUID = -9202173006928992231L;
 
     /**
-     * Constructs a <tt>CancellationException</tt> with no detail message.
+     * Constructs a {@code CancellationException} with no detail message.
      */
     public CancellationException() {}
 
     /**
-     * Constructs a <tt>CancellationException</tt> with the specified detail
+     * Constructs a {@code CancellationException} with the specified detail
      * message.
      *
      * @param message the detail message
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/java/util/concurrent/CompletableFuture.java	Wed Feb 20 15:42:21 2013 -0800
@@ -0,0 +1,3146 @@
+/*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * This file is available under and governed by the GNU General Public
+ * License version 2 only, as published by the Free Software Foundation.
+ * However, the following notice accompanied the original version of this
+ * file:
+ *
+ * Written by Doug Lea with assistance from members of JCP JSR-166
+ * Expert Group and released to the public domain, as explained at
+ * http://creativecommons.org/publicdomain/zero/1.0/
+ */
+
+package java.util.concurrent;
+import java.util.function.Supplier;
+import java.util.function.Consumer;
+import java.util.function.BiConsumer;
+import java.util.function.Function;
+import java.util.function.BiFunction;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.ForkJoinPool;
+import java.util.concurrent.ForkJoinTask;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.LockSupport;
+
+/**
+ * A {@link Future} that may be explicitly completed (setting its
+ * value and status), and may include dependent functions and actions
+ * that trigger upon its completion.
+ *
+ * <p>When two or more threads attempt to
+ * {@link #complete complete},
+ * {@link #completeExceptionally completeExceptionally}, or
+ * {@link #cancel cancel}
+ * a CompletableFuture, only one of them succeeds.
+ *
+ * <p>Methods are available for adding dependents based on Functions,
+ * Consumers, and Runnables. The appropriate form to use depends on
+ * whether actions require arguments and/or produce results. Actions
+ * may also be triggered after either or both the current and another
+ * CompletableFuture complete.  Multiple CompletableFutures may also
+ * be grouped as one using {@link #anyOf(CompletableFuture...)} and
+ * {@link #allOf(CompletableFuture...)}.
+ *
+ * <p>Actions supplied for dependent completions (mainly using methods
+ * with prefix {@code then}) may be performed by the thread that
+ * completes the current CompletableFuture, or by any other caller of
+ * these methods.  There are no guarantees about the order of
+ * processing completions unless constrained by these methods.
+ *
+ * <p>Since (unlike {@link FutureTask}) this class has no direct
+ * control over the computation that causes it to be completed,
+ * cancellation is treated as just another form of exceptional completion.
+ * Method {@link #cancel cancel} has the same effect as
+ * {@code completeExceptionally(new CancellationException())}.
+ *
+ * <p>Upon exceptional completion (including cancellation), or when a
+ * completion entails an additional computation which terminates
+ * abruptly with an (unchecked) exception or error, then all of their
+ * dependent completions (and their dependents in turn) generally act
+ * as {@code completeExceptionally} with a {@link CompletionException}
+ * holding that exception as its cause.  However, the {@link
+ * #exceptionally exceptionally} and {@link #handle handle}
+ * completions <em>are</em> able to handle exceptional completions of
+ * the CompletableFutures they depend on.
+ *
+ * <p>In case of exceptional completion with a CompletionException,
+ * methods {@link #get()} and {@link #get(long, TimeUnit)} throw an
+ * {@link ExecutionException} with the same cause as held in the
+ * corresponding CompletionException.  However, in these cases,
+ * methods {@link #join()} and {@link #getNow} throw the
+ * CompletionException, which simplifies usage.
+ *
+ * <p>CompletableFutures themselves do not execute asynchronously.
+ * However, the {@code async} methods provide commonly useful ways to
+ * commence asynchronous processing, using either a given {@link
+ * Executor} or by default the {@link ForkJoinPool#commonPool()}, of a
+ * function or action that will result in the completion of a new
+ * CompletableFuture. To simplify monitoring, debugging, and tracking,
+ * all generated asynchronous tasks are instances of the tagging
+ * interface {@link AsynchronousCompletionTask}.
+ *
+ * @author Doug Lea
+ * @since 1.8
+ */
+public class CompletableFuture<T> implements Future<T> {
+
+    /*
+     * Overview:
+     *
+     * 1. Non-nullness of field result (set via CAS) indicates done.
+     * An AltResult is used to box null as a result, as well as to
+     * hold exceptions.  Using a single field makes completion fast
+     * and simple to detect and trigger, at the expense of a lot of
+     * encoding and decoding that infiltrates many methods. One minor
+     * simplification relies on the (static) NIL (to box null results)
+     * being the only AltResult with a null exception field, so we
+     * don't usually need explicit comparisons with NIL. The CF
+     * exception propagation mechanics surrounding decoding rely on
+     * unchecked casts of decoded results really being unchecked,
+     * where user type errors are caught at point of use, as is
+     * currently the case in Java. These are highlighted by using
+     * SuppressWarnings-annotated temporaries.
+     *
+     * 2. Waiters are held in a Treiber stack similar to the one used
+     * in FutureTask, Phaser, and SynchronousQueue. See their
+     * internal documentation for algorithmic details.
+     *
+     * 3. Completions are also kept in a list/stack, and pulled off
+     * and run when completion is triggered. (We could even use the
+     * same stack as for waiters, but would give up the potential
+     * parallelism obtained because woken waiters help release/run
+     * others -- see method postComplete).  Because post-processing
+     * may race with direct calls, class Completion opportunistically
+     * extends AtomicInteger so callers can claim the action via
+     * compareAndSet(0, 1).  The Completion.run methods are all
+     * written a boringly similar uniform way (that sometimes includes
+     * unnecessary-looking checks, kept to maintain uniformity).
+     * There are enough dimensions upon which they differ that
+     * attempts to factor commonalities while maintaining efficiency
+     * require more lines of code than they would save.
+     *
+     * 4. The exported then/and/or methods do support a bit of
+     * factoring (see doThenApply etc). They must cope with the
+     * intrinsic races surrounding addition of a dependent action
+     * versus performing the action directly because the task is
+     * already complete.  For example, a CF may not be complete upon
+     * entry, so a dependent completion is added, but by the time it
+     * is added, the target CF is complete, so must be directly
+     * executed. This is all done while avoiding unnecessary object
+     * construction in safe-bypass cases.
+     */
+
+    // preliminaries
+
+    static final class AltResult {
+        final Throwable ex; // null only for NIL
+        AltResult(Throwable ex) { this.ex = ex; }
+    }
+
+    static final AltResult NIL = new AltResult(null);
+
+    // Fields
+
+    volatile Object result;    // Either the result or boxed AltResult
+    volatile WaitNode waiters; // Treiber stack of threads blocked on get()
+    volatile CompletionNode completions; // list (Treiber stack) of completions
+
+    // Basic utilities for triggering and processing completions
+
+    /**
+     * Removes and signals all waiting threads and runs all completions.
+     */
+    final void postComplete() {
+        WaitNode q; Thread t;
+        while ((q = waiters) != null) {
+            if (UNSAFE.compareAndSwapObject(this, WAITERS, q, q.next) &&
+                (t = q.thread) != null) {
+                q.thread = null;
+                LockSupport.unpark(t);
+            }
+        }
+
+        CompletionNode h; Completion c;
+        while ((h = completions) != null) {
+            if (UNSAFE.compareAndSwapObject(this, COMPLETIONS, h, h.next) &&
+                (c = h.completion) != null)
+                c.run();
+        }
+    }
+
+    /**
+     * Triggers completion with the encoding of the given arguments:
+     * if the exception is non-null, encodes it as a wrapped
+     * CompletionException unless it is one already.  Otherwise uses
+     * the given result, boxed as NIL if null.
+     */
+    final void internalComplete(Object v, Throwable ex) {
+        if (result == null)
+            UNSAFE.compareAndSwapObject
+                (this, RESULT, null,
+                 (ex == null) ? (v == null) ? NIL : v :
+                 new AltResult((ex instanceof CompletionException) ? ex :
+                               new CompletionException(ex)));
+        postComplete(); // help out even if not triggered
+    }
+
+    /**
+     * If triggered, helps release and/or process completions.
+     */
+    final void helpPostComplete() {
+        if (result != null)
+            postComplete();
+    }
+
+    /* ------------- waiting for completions -------------- */
+
+    /** Number of processors, for spin control */
+    static final int NCPU = Runtime.getRuntime().availableProcessors();
+
+    /**
+     * Heuristic spin value for waitingGet() before blocking on
+     * multiprocessors
+     */
+    static final int SPINS = (NCPU > 1) ? 1 << 8 : 0;
+
+    /**
+     * Linked nodes to record waiting threads in a Treiber stack.  See
+     * other classes such as Phaser and SynchronousQueue for more
+     * detailed explanation. This class implements ManagedBlocker to
+     * avoid starvation when blocking actions pile up in
+     * ForkJoinPools.
+     */
+    static final class WaitNode implements ForkJoinPool.ManagedBlocker {
+        long nanos;          // wait time if timed
+        final long deadline; // non-zero if timed
+        volatile int interruptControl; // > 0: interruptible, < 0: interrupted
+        volatile Thread thread;
+        volatile WaitNode next;
+        WaitNode(boolean interruptible, long nanos, long deadline) {
+            this.thread = Thread.currentThread();
+            this.interruptControl = interruptible ? 1 : 0;
+            this.nanos = nanos;
+            this.deadline = deadline;
+        }
+        public boolean isReleasable() {
+            if (thread == null)
+                return true;
+            if (Thread.interrupted()) {
+                int i = interruptControl;
+                interruptControl = -1;
+                if (i > 0)
+                    return true;
+            }
+            if (deadline != 0L &&
+                (nanos <= 0L || (nanos = deadline - System.nanoTime()) <= 0L)) {
+                thread = null;
+                return true;
+            }
+            return false;
+        }
+        public boolean block() {
+            if (isReleasable())
+                return true;
+            else if (deadline == 0L)
+                LockSupport.park(this);
+            else if (nanos > 0L)
+                LockSupport.parkNanos(this, nanos);
+            return isReleasable();
+        }
+    }
+
+    /**
+     * Returns raw result after waiting, or null if interruptible and
+     * interrupted.
+     */
+    private Object waitingGet(boolean interruptible) {
+        WaitNode q = null;
+        boolean queued = false;
+        int spins = SPINS;
+        for (Object r;;) {
+            if ((r = result) != null) {
+                if (q != null) { // suppress unpark
+                    q.thread = null;
+                    if (q.interruptControl < 0) {
+                        if (interruptible) {
+                            removeWaiter(q);
+                            return null;
+                        }
+                        Thread.currentThread().interrupt();
+                    }
+                }
+                postComplete(); // help release others
+                return r;
+            }
+            else if (spins > 0) {
+                int rnd = ThreadLocalRandom.nextSecondarySeed();
+                if (rnd == 0)
+                    rnd = ThreadLocalRandom.current().nextInt();
+                if (rnd >= 0)
+                    --spins;
+            }
+            else if (q == null)
+                q = new WaitNode(interruptible, 0L, 0L);
+            else if (!queued)
+                queued = UNSAFE.compareAndSwapObject(this, WAITERS,
+                                                     q.next = waiters, q);
+            else if (interruptible && q.interruptControl < 0) {
+                removeWaiter(q);
+                return null;
+            }
+            else if (q.thread != null && result == null) {
+                try {
+                    ForkJoinPool.managedBlock(q);
+                } catch (InterruptedException ex) {
+                    q.interruptControl = -1;
+                }
+            }
+        }
+    }
+
+    /**
+     * Awaits completion or aborts on interrupt or timeout.
+     *
+     * @param nanos time to wait
+     * @return raw result
+     */
+    private Object timedAwaitDone(long nanos)
+        throws InterruptedException, TimeoutException {
+        WaitNode q = null;
+        boolean queued = false;
+        for (Object r;;) {
+            if ((r = result) != null) {
+                if (q != null) {
+                    q.thread = null;
+                    if (q.interruptControl < 0) {
+                        removeWaiter(q);
+                        throw new InterruptedException();
+                    }
+                }
+                postComplete();
+                return r;
+            }
+            else if (q == null) {
+                if (nanos <= 0L)
+                    throw new TimeoutException();
+                long d = System.nanoTime() + nanos;
+                q = new WaitNode(true, nanos, d == 0L ? 1L : d); // avoid 0
+            }
+            else if (!queued)
+                queued = UNSAFE.compareAndSwapObject(this, WAITERS,
+                                                     q.next = waiters, q);
+            else if (q.interruptControl < 0) {
+                removeWaiter(q);
+                throw new InterruptedException();
+            }
+            else if (q.nanos <= 0L) {
+                if (result == null) {
+                    removeWaiter(q);
+                    throw new TimeoutException();
+                }
+            }
+            else if (q.thread != null && result == null) {
+                try {
+                    ForkJoinPool.managedBlock(q);
+                } catch (InterruptedException ex) {
+                    q.interruptControl = -1;
+                }
+            }
+        }
+    }
+
+    /**
+     * Tries to unlink a timed-out or interrupted wait node to avoid
+     * accumulating garbage.  Internal nodes are simply unspliced
+     * without CAS since it is harmless if they are traversed anyway
+     * by releasers.  To avoid effects of unsplicing from already
+     * removed nodes, the list is retraversed in case of an apparent
+     * race.  This is slow when there are a lot of nodes, but we don't
+     * expect lists to be long enough to outweigh higher-overhead
+     * schemes.
+     */
+    private void removeWaiter(WaitNode node) {
+        if (node != null) {
+            node.thread = null;
+            retry:
+            for (;;) {          // restart on removeWaiter race
+                for (WaitNode pred = null, q = waiters, s; q != null; q = s) {
+                    s = q.next;
+                    if (q.thread != null)
+                        pred = q;
+                    else if (pred != null) {
+                        pred.next = s;
+                        if (pred.thread == null) // check for race
+                            continue retry;
+                    }
+                    else if (!UNSAFE.compareAndSwapObject(this, WAITERS, q, s))
+                        continue retry;
+                }
+                break;
+            }
+        }
+    }
+
+    /* ------------- Async tasks -------------- */
+
+    /**
+     * A tagging interface identifying asynchronous tasks produced by
+     * {@code async} methods. This may be useful for monitoring,
+     * debugging, and tracking asynchronous activities.
+     */
+    public static interface AsynchronousCompletionTask {
+    }
+
+    /** Base class can act as either FJ or plain Runnable */
+    abstract static class Async extends ForkJoinTask<Void>
+        implements Runnable, AsynchronousCompletionTask {
+        public final Void getRawResult() { return null; }
+        public final void setRawResult(Void v) { }
+        public final void run() { exec(); }
+    }
+
+    static final class AsyncRun extends Async {
+        final Runnable fn;
+        final CompletableFuture<Void> dst;
+        AsyncRun(Runnable fn, CompletableFuture<Void> dst) {
+            this.fn = fn; this.dst = dst;
+        }
+        public final boolean exec() {
+            CompletableFuture<Void> d; Throwable ex;
+            if ((d = this.dst) != null && d.result == null) {
+                try {
+                    fn.run();
+                    ex = null;
+                } catch (Throwable rex) {
+                    ex = rex;
+                }
+                d.internalComplete(null, ex);
+            }
+            return true;
+        }
+        private static final long serialVersionUID = 5232453952276885070L;
+    }
+
+    static final class AsyncSupply<U> extends Async {
+        final Supplier<U> fn;
+        final CompletableFuture<U> dst;
+        AsyncSupply(Supplier<U> fn, CompletableFuture<U> dst) {
+            this.fn = fn; this.dst = dst;
+        }
+        public final boolean exec() {
+            CompletableFuture<U> d; U u; Throwable ex;
+            if ((d = this.dst) != null && d.result == null) {
+                try {
+                    u = fn.get();
+                    ex = null;
+                } catch (Throwable rex) {
+                    ex = rex;
+                    u = null;
+                }
+                d.internalComplete(u, ex);
+            }
+            return true;
+        }
+        private static final long serialVersionUID = 5232453952276885070L;
+    }
+
+    static final class AsyncApply<T,U> extends Async {
+        final Function<? super T,? extends U> fn;
+        final T arg;
+        final CompletableFuture<U> dst;
+        AsyncApply(T arg, Function<? super T,? extends U> fn,
+                   CompletableFuture<U> dst) {
+            this.arg = arg; this.fn = fn; this.dst = dst;
+        }
+        public final boolean exec() {
+            CompletableFuture<U> d; U u; Throwable ex;
+            if ((d = this.dst) != null && d.result == null) {
+                try {
+                    u = fn.apply(arg);
+                    ex = null;
+                } catch (Throwable rex) {
+                    ex = rex;
+                    u = null;
+                }
+                d.internalComplete(u, ex);
+            }
+            return true;
+        }
+        private static final long serialVersionUID = 5232453952276885070L;
+    }
+
+    static final class AsyncBiApply<T,U,V> extends Async {
+        final BiFunction<? super T,? super U,? extends V> fn;
+        final T arg1;
+        final U arg2;
+        final CompletableFuture<V> dst;
+        AsyncBiApply(T arg1, U arg2,
+                     BiFunction<? super T,? super U,? extends V> fn,
+                     CompletableFuture<V> dst) {
+            this.arg1 = arg1; this.arg2 = arg2; this.fn = fn; this.dst = dst;
+        }
+        public final boolean exec() {
+            CompletableFuture<V> d; V v; Throwable ex;
+            if ((d = this.dst) != null && d.result == null) {
+                try {
+                    v = fn.apply(arg1, arg2);
+                    ex = null;
+                } catch (Throwable rex) {
+                    ex = rex;
+                    v = null;
+                }
+                d.internalComplete(v, ex);
+            }
+            return true;
+        }
+        private static final long serialVersionUID = 5232453952276885070L;
+    }
+
+    static final class AsyncAccept<T> extends Async {
+        final Consumer<? super T> fn;
+        final T arg;
+        final CompletableFuture<Void> dst;
+        AsyncAccept(T arg, Consumer<? super T> fn,
+                    CompletableFuture<Void> dst) {
+            this.arg = arg; this.fn = fn; this.dst = dst;
+        }
+        public final boolean exec() {
+            CompletableFuture<Void> d; Throwable ex;
+            if ((d = this.dst) != null && d.result == null) {
+                try {
+                    fn.accept(arg);
+                    ex = null;
+                } catch (Throwable rex) {
+                    ex = rex;
+                }
+                d.internalComplete(null, ex);
+            }
+            return true;
+        }
+        private static final long serialVersionUID = 5232453952276885070L;
+    }
+
+    static final class AsyncBiAccept<T,U> extends Async {
+        final BiConsumer<? super T,? super U> fn;
+        final T arg1;
+        final U arg2;
+        final CompletableFuture<Void> dst;
+        AsyncBiAccept(T arg1, U arg2,
+                      BiConsumer<? super T,? super U> fn,
+                      CompletableFuture<Void> dst) {
+            this.arg1 = arg1; this.arg2 = arg2; this.fn = fn; this.dst = dst;
+        }
+        public final boolean exec() {
+            CompletableFuture<Void> d; Throwable ex;
+            if ((d = this.dst) != null && d.result == null) {
+                try {
+                    fn.accept(arg1, arg2);
+                    ex = null;
+                } catch (Throwable rex) {
+                    ex = rex;
+                }
+                d.internalComplete(null, ex);
+            }
+            return true;
+        }
+        private static final long serialVersionUID = 5232453952276885070L;
+    }
+
+    static final class AsyncCompose<T,U> extends Async {
+        final Function<? super T, CompletableFuture<U>> fn;
+        final T arg;
+        final CompletableFuture<U> dst;
+        AsyncCompose(T arg,
+                     Function<? super T, CompletableFuture<U>> fn,
+                     CompletableFuture<U> dst) {
+            this.arg = arg; this.fn = fn; this.dst = dst;
+        }
+        public final boolean exec() {
+            CompletableFuture<U> d, fr; U u; Throwable ex;
+            if ((d = this.dst) != null && d.result == null) {
+                try {
+                    fr = fn.apply(arg);
+                    ex = null;
+                } catch (Throwable rex) {
+                    ex = rex;
+                    fr = null;
+                }
+                if (ex != null)
+                    u = null;
+                else if (fr == null) {
+                    ex = new NullPointerException();
+                    u = null;
+                }
+                else {
+                    Object r = fr.result;
+                    if (r instanceof AltResult) {
+                        ex = ((AltResult)r).ex;
+                        u = null;
+                    }
+                    else {
+                        @SuppressWarnings("unchecked") U ur = (U) r;
+                        u = ur;
+                    }
+                }
+                d.internalComplete(u, ex);
+            }
+            return true;
+        }
+        private static final long serialVersionUID = 5232453952276885070L;
+    }
+
+    /* ------------- Completions -------------- */
+
+    /**
+     * Simple linked list nodes to record completions, used in
+     * basically the same way as WaitNodes. (We separate nodes from
+     * the Completions themselves mainly because for the And and Or
+     * methods, the same Completion object resides in two lists.)
+     */
+    static final class CompletionNode {
+        final Completion completion;
+        volatile CompletionNode next;
+        CompletionNode(Completion completion) { this.completion = completion; }
+    }
+
+    // Opportunistically subclass AtomicInteger to use compareAndSet to claim.
+    abstract static class Completion extends AtomicInteger implements Runnable {
+    }
+
+    static final class ApplyCompletion<T,U> extends Completion {
+        final CompletableFuture<? extends T> src;
+        final Function<? super T,? extends U> fn;
+        final CompletableFuture<U> dst;
+        final Executor executor;
+        ApplyCompletion(CompletableFuture<? extends T> src,
+                        Function<? super T,? extends U> fn,
+                        CompletableFuture<U> dst, Executor executor) {
+            this.src = src; this.fn = fn; this.dst = dst;
+            this.executor = executor;
+        }
+        public final void run() {
+            final CompletableFuture<? extends T> a;
+            final Function<? super T,? extends U> fn;
+            final CompletableFuture<U> dst;
+            Object r; T t; Throwable ex;
+            if ((dst = this.dst) != null &&
+                (fn = this.fn) != null &&
+                (a = this.src) != null &&
+                (r = a.result) != null &&
+                compareAndSet(0, 1)) {
+                if (r instanceof AltResult) {
+                    ex = ((AltResult)r).ex;
+                    t = null;
+                }
+                else {
+                    ex = null;
+                    @SuppressWarnings("unchecked") T tr = (T) r;
+                    t = tr;
+                }
+                Executor e = executor;
+                U u = null;
+                if (ex == null) {
+                    try {
+                        if (e != null)
+                            e.execute(new AsyncApply<T,U>(t, fn, dst));
+                        else
+                            u = fn.apply(t);
+                    } catch (Throwable rex) {
+                        ex = rex;
+                    }
+                }
+                if (e == null || ex != null)
+                    dst.internalComplete(u, ex);
+            }
+        }
+        private static final long serialVersionUID = 5232453952276885070L;
+    }
+
+    static final class AcceptCompletion<T> extends Completion {
+        final CompletableFuture<? extends T> src;
+        final Consumer<? super T> fn;
+        final CompletableFuture<Void> dst;
+        final Executor executor;
+        AcceptCompletion(CompletableFuture<? extends T> src,
+                         Consumer<? super T> fn,
+                         CompletableFuture<Void> dst, Executor executor) {
+            this.src = src; this.fn = fn; this.dst = dst;
+            this.executor = executor;
+        }
+        public final void run() {
+            final CompletableFuture<? extends T> a;
+            final Consumer<? super T> fn;
+            final CompletableFuture<Void> dst;
+            Object r; T t; Throwable ex;
+            if ((dst = this.dst) != null &&
+                (fn = this.fn) != null &&
+                (a = this.src) != null &&
+                (r = a.result) != null &&
+                compareAndSet(0, 1)) {
+                if (r instanceof AltResult) {
+                    ex = ((AltResult)r).ex;
+                    t = null;
+                }
+                else {
+                    ex = null;
+                    @SuppressWarnings("unchecked") T tr = (T) r;
+                    t = tr;
+                }
+                Executor e = executor;
+                if (ex == null) {
+                    try {
+                        if (e != null)
+                            e.execute(new AsyncAccept<T>(t, fn, dst));
+                        else
+                            fn.accept(t);
+                    } catch (Throwable rex) {
+                        ex = rex;
+                    }
+                }
+                if (e == null || ex != null)
+                    dst.internalComplete(null, ex);
+            }
+        }
+        private static final long serialVersionUID = 5232453952276885070L;
+    }
+
+    static final class RunCompletion<T> extends Completion {
+        final CompletableFuture<? extends T> src;
+        final Runnable fn;
+        final CompletableFuture<Void> dst;
+        final Executor executor;
+        RunCompletion(CompletableFuture<? extends T> src,
+                      Runnable fn,
+                      CompletableFuture<Void> dst,
+                      Executor executor) {
+            this.src = src; this.fn = fn; this.dst = dst;
+            this.executor = executor;
+        }
+        public final void run() {
+            final CompletableFuture<? extends T> a;
+            final Runnable fn;
+            final CompletableFuture<Void> dst;
+            Object r; Throwable ex;
+            if ((dst = this.dst) != null &&
+                (fn = this.fn) != null &&
+                (a = this.src) != null &&
+                (r = a.result) != null &&
+                compareAndSet(0, 1)) {
+                if (r instanceof AltResult)
+                    ex = ((AltResult)r).ex;
+                else
+                    ex = null;
+                Executor e = executor;
+                if (ex == null) {
+                    try {
+                        if (e != null)
+                            e.execute(new AsyncRun(fn, dst));
+                        else
+                            fn.run();
+                    } catch (Throwable rex) {
+                        ex = rex;
+                    }
+                }
+                if (e == null || ex != null)
+                    dst.internalComplete(null, ex);
+            }
+        }
+        private static final long serialVersionUID = 5232453952276885070L;
+    }
+
+    static final class BiApplyCompletion<T,U,V> extends Completion {
+        final CompletableFuture<? extends T> src;
+        final CompletableFuture<? extends U> snd;
+        final BiFunction<? super T,? super U,? extends V> fn;
+        final CompletableFuture<V> dst;
+        final Executor executor;
+        BiApplyCompletion(CompletableFuture<? extends T> src,
+                          CompletableFuture<? extends U> snd,
+                          BiFunction<? super T,? super U,? extends V> fn,
+                          CompletableFuture<V> dst, Executor executor) {
+            this.src = src; this.snd = snd;
+            this.fn = fn; this.dst = dst;
+            this.executor = executor;
+        }
+        public final void run() {
+            final CompletableFuture<? extends T> a;
+            final CompletableFuture<? extends U> b;
+            final BiFunction<? super T,? super U,? extends V> fn;
+            final CompletableFuture<V> dst;
+            Object r, s; T t; U u; Throwable ex;
+            if ((dst = this.dst) != null &&
+                (fn = this.fn) != null &&
+                (a = this.src) != null &&
+                (r = a.result) != null &&
+                (b = this.snd) != null &&
+                (s = b.result) != null &&
+                compareAndSet(0, 1)) {
+                if (r instanceof AltResult) {
+                    ex = ((AltResult)r).ex;
+                    t = null;
+                }
+                else {
+                    ex = null;
+                    @SuppressWarnings("unchecked") T tr = (T) r;
+                    t = tr;
+                }
+                if (ex != null)
+                    u = null;
+                else if (s instanceof AltResult) {
+                    ex = ((AltResult)s).ex;
+                    u = null;
+                }
+                else {
+                    @SuppressWarnings("unchecked") U us = (U) s;
+                    u = us;
+                }
+                Executor e = executor;
+                V v = null;
+                if (ex == null) {
+                    try {
+                        if (e != null)
+                            e.execute(new AsyncBiApply<T,U,V>(t, u, fn, dst));
+                        else
+                            v = fn.apply(t, u);
+                    } catch (Throwable rex) {
+                        ex = rex;
+                    }
+                }
+                if (e == null || ex != null)
+                    dst.internalComplete(v, ex);
+            }
+        }
+        private static final long serialVersionUID = 5232453952276885070L;
+    }
+
+    static final class BiAcceptCompletion<T,U> extends Completion {
+        final CompletableFuture<? extends T> src;
+        final CompletableFuture<? extends U> snd;
+        final BiConsumer<? super T,? super U> fn;
+        final CompletableFuture<Void> dst;
+        final Executor executor;
+        BiAcceptCompletion(CompletableFuture<? extends T> src,
+                           CompletableFuture<? extends U> snd,
+                           BiConsumer<? super T,? super U> fn,
+                           CompletableFuture<Void> dst, Executor executor) {
+            this.src = src; this.snd = snd;
+            this.fn = fn; this.dst = dst;
+            this.executor = executor;
+        }
+        public final void run() {
+            final CompletableFuture<? extends T> a;
+            final CompletableFuture<? extends U> b;
+            final BiConsumer<? super T,? super U> fn;
+            final CompletableFuture<Void> dst;
+            Object r, s; T t; U u; Throwable ex;
+            if ((dst = this.dst) != null &&
+                (fn = this.fn) != null &&
+                (a = this.src) != null &&
+                (r = a.result) != null &&
+                (b = this.snd) != null &&
+                (s = b.result) != null &&
+                compareAndSet(0, 1)) {
+                if (r instanceof AltResult) {
+                    ex = ((AltResult)r).ex;
+                    t = null;
+                }
+                else {
+                    ex = null;
+                    @SuppressWarnings("unchecked") T tr = (T) r;
+                    t = tr;
+                }
+                if (ex != null)
+                    u = null;
+                else if (s instanceof AltResult) {
+                    ex = ((AltResult)s).ex;
+                    u = null;
+                }
+                else {
+                    @SuppressWarnings("unchecked") U us = (U) s;
+                    u = us;
+                }
+                Executor e = executor;
+                if (ex == null) {
+                    try {
+                        if (e != null)
+                            e.execute(new AsyncBiAccept<T,U>(t, u, fn, dst));
+                        else
+                            fn.accept(t, u);
+                    } catch (Throwable rex) {
+                        ex = rex;
+                    }
+                }
+                if (e == null || ex != null)
+                    dst.internalComplete(null, ex);
+            }
+        }
+        private static final long serialVersionUID = 5232453952276885070L;
+    }
+
+    static final class BiRunCompletion<T> extends Completion {
+        final CompletableFuture<? extends T> src;
+        final CompletableFuture<?> snd;
+        final Runnable fn;
+        final CompletableFuture<Void> dst;
+        final Executor executor;
+        BiRunCompletion(CompletableFuture<? extends T> src,
+                        CompletableFuture<?> snd,
+                        Runnable fn,
+                        CompletableFuture<Void> dst, Executor executor) {
+            this.src = src; this.snd = snd;
+            this.fn = fn; this.dst = dst;
+            this.executor = executor;
+        }
+        public final void run() {
+            final CompletableFuture<? extends T> a;
+            final CompletableFuture<?> b;
+            final Runnable fn;
+            final CompletableFuture<Void> dst;
+            Object r, s; Throwable ex;
+            if ((dst = this.dst) != null &&
+                (fn = this.fn) != null &&
+                (a = this.src) != null &&
+                (r = a.result) != null &&
+                (b = this.snd) != null &&
+                (s = b.result) != null &&
+                compareAndSet(0, 1)) {
+                if (r instanceof AltResult)
+                    ex = ((AltResult)r).ex;
+                else
+                    ex = null;
+                if (ex == null && (s instanceof AltResult))
+                    ex = ((AltResult)s).ex;
+                Executor e = executor;
+                if (ex == null) {
+                    try {
+                        if (e != null)
+                            e.execute(new AsyncRun(fn, dst));
+                        else
+                            fn.run();
+                    } catch (Throwable rex) {
+                        ex = rex;
+                    }
+                }
+                if (e == null || ex != null)
+                    dst.internalComplete(null, ex);
+            }
+        }
+        private static final long serialVersionUID = 5232453952276885070L;
+    }
+
+    static final class AndCompletion extends Completion {
+        final CompletableFuture<?> src;
+        final CompletableFuture<?> snd;
+        final CompletableFuture<Void> dst;
+        AndCompletion(CompletableFuture<?> src,
+                      CompletableFuture<?> snd,
+                      CompletableFuture<Void> dst) {
+            this.src = src; this.snd = snd; this.dst = dst;
+        }
+        public final void run() {
+            final CompletableFuture<?> a;
+            final CompletableFuture<?> b;
+            final CompletableFuture<Void> dst;
+            Object r, s; Throwable ex;
+            if ((dst = this.dst) != null &&
+                (a = this.src) != null &&
+                (r = a.result) != null &&
+                (b = this.snd) != null &&
+                (s = b.result) != null &&
+                compareAndSet(0, 1)) {
+                if (r instanceof AltResult)
+                    ex = ((AltResult)r).ex;
+                else
+                    ex = null;
+                if (ex == null && (s instanceof AltResult))
+                    ex = ((AltResult)s).ex;
+                dst.internalComplete(null, ex);
+            }
+        }
+        private static final long serialVersionUID = 5232453952276885070L;
+    }
+
+    static final class OrApplyCompletion<T,U> extends Completion {
+        final CompletableFuture<? extends T> src;
+        final CompletableFuture<? extends T> snd;
+        final Function<? super T,? extends U> fn;
+        final CompletableFuture<U> dst;
+        final Executor executor;
+        OrApplyCompletion(CompletableFuture<? extends T> src,
+                          CompletableFuture<? extends T> snd,
+                          Function<? super T,? extends U> fn,
+                          CompletableFuture<U> dst, Executor executor) {
+            this.src = src; this.snd = snd;
+            this.fn = fn; this.dst = dst;
+            this.executor = executor;
+        }
+        public final void run() {
+            final CompletableFuture<? extends T> a;
+            final CompletableFuture<? extends T> b;
+            final Function<? super T,? extends U> fn;
+            final CompletableFuture<U> dst;
+            Object r; T t; Throwable ex;
+            if ((dst = this.dst) != null &&
+                (fn = this.fn) != null &&
+                (((a = this.src) != null && (r = a.result) != null) ||
+                 ((b = this.snd) != null && (r = b.result) != null)) &&
+                compareAndSet(0, 1)) {
+                if (r instanceof AltResult) {
+                    ex = ((AltResult)r).ex;
+                    t = null;
+                }
+                else {
+                    ex = null;
+                    @SuppressWarnings("unchecked") T tr = (T) r;
+                    t = tr;
+                }
+                Executor e = executor;
+                U u = null;
+                if (ex == null) {
+                    try {
+                        if (e != null)
+                            e.execute(new AsyncApply<T,U>(t, fn, dst));
+                        else
+                            u = fn.apply(t);
+                    } catch (Throwable rex) {
+                        ex = rex;
+                    }
+                }
+                if (e == null || ex != null)
+                    dst.internalComplete(u, ex);
+            }
+        }
+        private static final long serialVersionUID = 5232453952276885070L;
+    }
+
+    static final class OrAcceptCompletion<T> extends Completion {
+        final CompletableFuture<? extends T> src;
+        final CompletableFuture<? extends T> snd;
+        final Consumer<? super T> fn;
+        final CompletableFuture<Void> dst;
+        final Executor executor;
+        OrAcceptCompletion(CompletableFuture<? extends T> src,
+                           CompletableFuture<? extends T> snd,
+                           Consumer<? super T> fn,
+                           CompletableFuture<Void> dst, Executor executor) {
+            this.src = src; this.snd = snd;
+            this.fn = fn; this.dst = dst;
+            this.executor = executor;
+        }
+        public final void run() {
+            final CompletableFuture<? extends T> a;
+            final CompletableFuture<? extends T> b;
+            final Consumer<? super T> fn;
+            final CompletableFuture<Void> dst;
+            Object r; T t; Throwable ex;
+            if ((dst = this.dst) != null &&
+                (fn = this.fn) != null &&
+                (((a = this.src) != null && (r = a.result) != null) ||
+                 ((b = this.snd) != null && (r = b.result) != null)) &&
+                compareAndSet(0, 1)) {
+                if (r instanceof AltResult) {
+                    ex = ((AltResult)r).ex;
+                    t = null;
+                }
+                else {
+                    ex = null;
+                    @SuppressWarnings("unchecked") T tr = (T) r;
+                    t = tr;
+                }
+                Executor e = executor;
+                if (ex == null) {
+                    try {
+                        if (e != null)
+                            e.execute(new AsyncAccept<T>(t, fn, dst));
+                        else
+                            fn.accept(t);
+                    } catch (Throwable rex) {
+                        ex = rex;
+                    }
+                }
+                if (e == null || ex != null)
+                    dst.internalComplete(null, ex);
+            }
+        }
+        private static final long serialVersionUID = 5232453952276885070L;
+    }
+
+    static final class OrRunCompletion<T> extends Completion {
+        final CompletableFuture<? extends T> src;
+        final CompletableFuture<?> snd;
+        final Runnable fn;
+        final CompletableFuture<Void> dst;
+        final Executor executor;
+        OrRunCompletion(CompletableFuture<? extends T> src,
+                        CompletableFuture<?> snd,
+                        Runnable fn,
+                        CompletableFuture<Void> dst, Executor executor) {
+            this.src = src; this.snd = snd;
+            this.fn = fn; this.dst = dst;
+            this.executor = executor;
+        }
+        public final void run() {
+            final CompletableFuture<? extends T> a;
+            final CompletableFuture<?> b;
+            final Runnable fn;
+            final CompletableFuture<Void> dst;
+            Object r; Throwable ex;
+            if ((dst = this.dst) != null &&
+                (fn = this.fn) != null &&
+                (((a = this.src) != null && (r = a.result) != null) ||
+                 ((b = this.snd) != null && (r = b.result) != null)) &&
+                compareAndSet(0, 1)) {
+                if (r instanceof AltResult)
+                    ex = ((AltResult)r).ex;
+                else
+                    ex = null;
+                Executor e = executor;
+                if (ex == null) {
+                    try {
+                        if (e != null)
+                            e.execute(new AsyncRun(fn, dst));
+                        else
+                            fn.run();
+                    } catch (Throwable rex) {
+                        ex = rex;
+                    }
+                }
+                if (e == null || ex != null)
+                    dst.internalComplete(null, ex);
+            }
+        }
+        private static final long serialVersionUID = 5232453952276885070L;
+    }
+
+    static final class OrCompletion extends Completion {
+        final CompletableFuture<?> src;
+        final CompletableFuture<?> snd;
+        final CompletableFuture<?> dst;
+        OrCompletion(CompletableFuture<?> src,
+                     CompletableFuture<?> snd,
+                     CompletableFuture<?> dst) {
+            this.src = src; this.snd = snd; this.dst = dst;
+        }
+        public final void run() {
+            final CompletableFuture<?> a;
+            final CompletableFuture<?> b;
+            final CompletableFuture<?> dst;
+            Object r, t; Throwable ex;
+            if ((dst = this.dst) != null &&
+                (((a = this.src) != null && (r = a.result) != null) ||
+                 ((b = this.snd) != null && (r = b.result) != null)) &&
+                compareAndSet(0, 1)) {
+                if (r instanceof AltResult) {
+                    ex = ((AltResult)r).ex;
+                    t = null;
+                }
+                else {
+                    ex = null;
+                    t = r;
+                }
+                dst.internalComplete(t, ex);
+            }
+        }
+        private static final long serialVersionUID = 5232453952276885070L;
+    }
+
+    static final class ExceptionCompletion<T> extends Completion {
+        final CompletableFuture<? extends T> src;
+        final Function<? super Throwable, ? extends T> fn;
+        final CompletableFuture<T> dst;
+        ExceptionCompletion(CompletableFuture<? extends T> src,
+                            Function<? super Throwable, ? extends T> fn,
+                            CompletableFuture<T> dst) {
+            this.src = src; this.fn = fn; this.dst = dst;
+        }
+        public final void run() {
+            final CompletableFuture<? extends T> a;
+            final Function<? super Throwable, ? extends T> fn;
+            final CompletableFuture<T> dst;
+            Object r; T t = null; Throwable ex, dx = null;
+            if ((dst = this.dst) != null &&
+                (fn = this.fn) != null &&
+                (a = this.src) != null &&
+                (r = a.result) != null &&
+                compareAndSet(0, 1)) {
+                if ((r instanceof AltResult) &&
+                    (ex = ((AltResult)r).ex) != null)  {
+                    try {
+                        t = fn.apply(ex);
+                    } catch (Throwable rex) {
+                        dx = rex;
+                    }
+                }
+                else {
+                    @SuppressWarnings("unchecked") T tr = (T) r;
+                    t = tr;
+                }
+                dst.internalComplete(t, dx);
+            }
+        }
+        private static final long serialVersionUID = 5232453952276885070L;
+    }
+
+    static final class ThenCopy extends Completion {
+        final CompletableFuture<?> src;
+        final CompletableFuture<?> dst;
+        ThenCopy(CompletableFuture<?> src,
+                 CompletableFuture<?> dst) {
+            this.src = src; this.dst = dst;
+        }
+        public final void run() {
+            final CompletableFuture<?> a;
+            final CompletableFuture<?> dst;
+            Object r; Object t; Throwable ex;
+            if ((dst = this.dst) != null &&
+                (a = this.src) != null &&
+                (r = a.result) != null &&
+                compareAndSet(0, 1)) {
+                if (r instanceof AltResult) {
+                    ex = ((AltResult)r).ex;
+                    t = null;
+                }
+                else {
+                    ex = null;
+                    t = r;
+                }
+                dst.internalComplete(t, ex);
+            }
+        }
+        private static final long serialVersionUID = 5232453952276885070L;
+    }
+
+    static final class HandleCompletion<T,U> extends Completion {
+        final CompletableFuture<? extends T> src;
+        final BiFunction<? super T, Throwable, ? extends U> fn;
+        final CompletableFuture<U> dst;
+        HandleCompletion(CompletableFuture<? extends T> src,
+                         BiFunction<? super T, Throwable, ? extends U> fn,
+                         final CompletableFuture<U> dst) {
+            this.src = src; this.fn = fn; this.dst = dst;
+        }
+        public final void run() {
+            final CompletableFuture<? extends T> a;
+            final BiFunction<? super T, Throwable, ? extends U> fn;
+            final CompletableFuture<U> dst;
+            Object r; T t; Throwable ex;
+            if ((dst = this.dst) != null &&
+                (fn = this.fn) != null &&
+                (a = this.src) != null &&
+                (r = a.result) != null &&
+                compareAndSet(0, 1)) {
+                if (r instanceof AltResult) {
+                    ex = ((AltResult)r).ex;
+                    t = null;
+                }
+                else {
+                    ex = null;
+                    @SuppressWarnings("unchecked") T tr = (T) r;
+                    t = tr;
+                }
+                U u = null; Throwable dx = null;
+                try {
+                    u = fn.apply(t, ex);
+                } catch (Throwable rex) {
+                    dx = rex;
+                }
+                dst.internalComplete(u, dx);
+            }
+        }
+        private static final long serialVersionUID = 5232453952276885070L;
+    }
+
+    static final class ComposeCompletion<T,U> extends Completion {
+        final CompletableFuture<? extends T> src;
+        final Function<? super T, CompletableFuture<U>> fn;
+        final CompletableFuture<U> dst;
+        final Executor executor;
+        ComposeCompletion(CompletableFuture<? extends T> src,
+                          Function<? super T, CompletableFuture<U>> fn,
+                          final CompletableFuture<U> dst, Executor executor) {
+            this.src = src; this.fn = fn; this.dst = dst;
+            this.executor = executor;
+        }
+        public final void run() {
+            final CompletableFuture<? extends T> a;
+            final Function<? super T, CompletableFuture<U>> fn;
+            final CompletableFuture<U> dst;
+            Object r; T t; Throwable ex; Executor e;
+            if ((dst = this.dst) != null &&
+                (fn = this.fn) != null &&
+                (a = this.src) != null &&
+                (r = a.result) != null &&
+                compareAndSet(0, 1)) {
+                if (r instanceof AltResult) {
+                    ex = ((AltResult)r).ex;
+                    t = null;
+                }
+                else {
+                    ex = null;
+                    @SuppressWarnings("unchecked") T tr = (T) r;
+                    t = tr;
+                }
+                CompletableFuture<U> c = null;
+                U u = null;
+                boolean complete = false;
+                if (ex == null) {
+                    if ((e = executor) != null)
+                        e.execute(new AsyncCompose<T,U>(t, fn, dst));
+                    else {
+                        try {
+                            if ((c = fn.apply(t)) == null)
+                                ex = new NullPointerException();
+                        } catch (Throwable rex) {
+                            ex = rex;
+                        }
+                    }
+                }
+                if (c != null) {
+                    ThenCopy d = null;
+                    Object s;
+                    if ((s = c.result) == null) {
+                        CompletionNode p = new CompletionNode
+                            (d = new ThenCopy(c, dst));
+                        while ((s = c.result) == null) {
+                            if (UNSAFE.compareAndSwapObject
+                                (c, COMPLETIONS, p.next = c.completions, p))
+                                break;
+                        }
+                    }
+                    if (s != null && (d == null || d.compareAndSet(0, 1))) {
+                        complete = true;
+                        if (s instanceof AltResult) {
+                            ex = ((AltResult)s).ex;  // no rewrap
+                            u = null;
+                        }
+                        else {
+                            @SuppressWarnings("unchecked") U us = (U) s;
+                            u = us;
+                        }
+                    }
+                }
+                if (complete || ex != null)
+                    dst.internalComplete(u, ex);
+                if (c != null)
+                    c.helpPostComplete();
+            }
+        }
+        private static final long serialVersionUID = 5232453952276885070L;
+    }
+
+    // public methods
+
+    /**
+     * Creates a new incomplete CompletableFuture.
+     */
+    public CompletableFuture() {
+    }
+
+    /**
+     * Asynchronously executes in the {@link
+     * ForkJoinPool#commonPool()}, a task that completes the returned
+     * CompletableFuture with the result of the given Supplier.
+     *
+     * @param supplier a function returning the value to be used
+     * to complete the returned CompletableFuture
+     * @return the CompletableFuture
+     */
+    public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
+        if (supplier == null) throw new NullPointerException();
+        CompletableFuture<U> f = new CompletableFuture<U>();
+        ForkJoinPool.commonPool().
+            execute((ForkJoinTask<?>)new AsyncSupply<U>(supplier, f));
+        return f;
+    }
+
+    /**
+     * Asynchronously executes using the given executor, a task that
+     * completes the returned CompletableFuture with the result of the
+     * given Supplier.
+     *
+     * @param supplier a function returning the value to be used
+     * to complete the returned CompletableFuture
+     * @param executor the executor to use for asynchronous execution
+     * @return the CompletableFuture
+     */
+    public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,
+                                                       Executor executor) {
+        if (executor == null || supplier == null)
+            throw new NullPointerException();
+        CompletableFuture<U> f = new CompletableFuture<U>();
+        executor.execute(new AsyncSupply<U>(supplier, f));
+        return f;
+    }
+
+    /**
+     * Asynchronously executes in the {@link
+     * ForkJoinPool#commonPool()} a task that runs the given action,
+     * and then completes the returned CompletableFuture.
+     *
+     * @param runnable the action to run before completing the
+     * returned CompletableFuture
+     * @return the CompletableFuture
+     */
+    public static CompletableFuture<Void> runAsync(Runnable runnable) {
+        if (runnable == null) throw new NullPointerException();
+        CompletableFuture<Void> f = new CompletableFuture<Void>();
+        ForkJoinPool.commonPool().
+            execute((ForkJoinTask<?>)new AsyncRun(runnable, f));
+        return f;
+    }
+
+    /**
+     * Asynchronously executes using the given executor, a task that
+     * runs the given action, and then completes the returned
+     * CompletableFuture.
+     *
+     * @param runnable the action to run before completing the
+     * returned CompletableFuture
+     * @param executor the executor to use for asynchronous execution
+     * @return the CompletableFuture
+     */
+    public static CompletableFuture<Void> runAsync(Runnable runnable,
+                                                   Executor executor) {
+        if (executor == null || runnable == null)
+            throw new NullPointerException();
+        CompletableFuture<Void> f = new CompletableFuture<Void>();
+        executor.execute(new AsyncRun(runnable, f));
+        return f;
+    }
+
+    /**
+     * Returns {@code true} if completed in any fashion: normally,
+     * exceptionally, or via cancellation.
+     *
+     * @return {@code true} if completed
+     */
+    public boolean isDone() {
+        return result != null;
+    }
+
+    /**
+     * Waits if necessary for this future to complete, and then
+     * returns its result.
+     *
+     * @return the result value
+     * @throws CancellationException if this future was cancelled
+     * @throws ExecutionException if this future completed exceptionally
+     * @throws InterruptedException if the current thread was interrupted
+     * while waiting
+     */
+    public T get() throws InterruptedException, ExecutionException {
+        Object r; Throwable ex, cause;
+        if ((r = result) == null && (r = waitingGet(true)) == null)
+            throw new InterruptedException();
+        if (!(r instanceof AltResult)) {
+            @SuppressWarnings("unchecked") T tr = (T) r;
+            return tr;
+        }
+        if ((ex = ((AltResult)r).ex) == null)
+            return null;
+        if (ex instanceof CancellationException)
+            throw (CancellationException)ex;
+        if ((ex instanceof CompletionException) &&
+            (cause = ex.getCause()) != null)
+            ex = cause;
+        throw new ExecutionException(ex);
+    }
+
+    /**
+     * Waits if necessary for at most the given time for this future
+     * to complete, and then returns its result, if available.
+     *
+     * @param timeout the maximum time to wait
+     * @param unit the time unit of the timeout argument
+     * @return the result value
+     * @throws CancellationException if this future was cancelled
+     * @throws ExecutionException if this future completed exceptionally
+     * @throws InterruptedException if the current thread was interrupted
+     * while waiting
+     * @throws TimeoutException if the wait timed out
+     */
+    public T get(long timeout, TimeUnit unit)
+        throws InterruptedException, ExecutionException, TimeoutException {
+        Object r; Throwable ex, cause;
+        long nanos = unit.toNanos(timeout);
+        if (Thread.interrupted())
+            throw new InterruptedException();
+        if ((r = result) == null)
+            r = timedAwaitDone(nanos);
+        if (!(r instanceof AltResult)) {
+            @SuppressWarnings("unchecked") T tr = (T) r;
+            return tr;
+        }
+        if ((ex = ((AltResult)r).ex) == null)
+            return null;
+        if (ex instanceof CancellationException)
+            throw (CancellationException)ex;
+        if ((ex instanceof CompletionException) &&
+            (cause = ex.getCause()) != null)
+            ex = cause;
+        throw new ExecutionException(ex);
+    }
+
+    /**
+     * Returns the result value when complete, or throws an
+     * (unchecked) exception if completed exceptionally. To better
+     * conform with the use of common functional forms, if a
+     * computation involved in the completion of this
+     * CompletableFuture threw an exception, this method throws an
+     * (unchecked) {@link CompletionException} with the underlying
+     * exception as its cause.
+     *
+     * @return the result value
+     * @throws CancellationException if the computation was cancelled
+     * @throws CompletionException if this future completed
+     * exceptionally or a completion computation threw an exception
+     */
+    public T join() {
+        Object r; Throwable ex;
+        if ((r = result) == null)
+            r = waitingGet(false);
+        if (!(r instanceof AltResult)) {
+            @SuppressWarnings("unchecked") T tr = (T) r;
+            return tr;
+        }
+        if ((ex = ((AltResult)r).ex) == null)
+            return null;
+        if (ex instanceof CancellationException)
+            throw (CancellationException)ex;
+        if (ex instanceof CompletionException)
+            throw (CompletionException)ex;
+        throw new CompletionException(ex);
+    }
+
+    /**
+     * Returns the result value (or throws any encountered exception)
+     * if completed, else returns the given valueIfAbsent.
+     *
+     * @param valueIfAbsent the value to return if not completed
+     * @return the result value, if completed, else the given valueIfAbsent
+     * @throws CancellationException if the computation was cancelled
+     * @throws CompletionException if this future completed
+     * exceptionally or a completion computation threw an exception
+     */
+    public T getNow(T valueIfAbsent) {
+        Object r; Throwable ex;
+        if ((r = result) == null)
+            return valueIfAbsent;
+        if (!(r instanceof AltResult)) {
+            @SuppressWarnings("unchecked") T tr = (T) r;
+            return tr;
+        }
+        if ((ex = ((AltResult)r).ex) == null)
+            return null;
+        if (ex instanceof CancellationException)
+            throw (CancellationException)ex;
+        if (ex instanceof CompletionException)
+            throw (CompletionException)ex;
+        throw new CompletionException(ex);
+    }
+
+    /**
+     * If not already completed, sets the value returned by {@link
+     * #get()} and related methods to the given value.
+     *
+     * @param value the result value
+     * @return {@code true} if this invocation caused this CompletableFuture
+     * to transition to a completed state, else {@code false}
+     */
+    public boolean complete(T value) {
+        boolean triggered = result == null &&
+            UNSAFE.compareAndSwapObject(this, RESULT, null,
+                                        value == null ? NIL : value);
+        postComplete();
+        return triggered;
+    }
+
+    /**
+     * If not already completed, causes invocations of {@link #get()}
+     * and related methods to throw the given exception.
+     *
+     * @param ex the exception
+     * @return {@code true} if this invocation caused this CompletableFuture
+     * to transition to a completed state, else {@code false}
+     */
+    public boolean completeExceptionally(Throwable ex) {
+        if (ex == null) throw new NullPointerException();
+        boolean triggered = result == null &&
+            UNSAFE.compareAndSwapObject(this, RESULT, null, new AltResult(ex));
+        postComplete();
+        return triggered;
+    }
+
+    /**
+     * Creates and returns a CompletableFuture that is completed with
+     * the result of the given function of this CompletableFuture.
+     * If this CompletableFuture completes exceptionally,
+     * then the returned CompletableFuture also does so,
+     * with a CompletionException holding this exception as
+     * its cause.
+     *
+     * @param fn the function to use to compute the value of
+     * the returned CompletableFuture
+     * @return the new CompletableFuture
+     */
+    public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn) {
+        return doThenApply(fn, null);
+    }
+
+    /**
+     * Creates and returns a CompletableFuture that is asynchronously
+     * completed using the {@link ForkJoinPool#commonPool()} with the
+     * result of the given function of this CompletableFuture.  If
+     * this CompletableFuture completes exceptionally, then the
+     * returned CompletableFuture also does so, with a
+     * CompletionException holding this exception as its cause.
+     *
+     * @param fn the function to use to compute the value of
+     * the returned CompletableFuture
+     * @return the new CompletableFuture
+     */
+    public <U> CompletableFuture<U> thenApplyAsync
+        (Function<? super T,? extends U> fn) {
+        return doThenApply(fn, ForkJoinPool.commonPool());
+    }
+
+    /**
+     * Creates and returns a CompletableFuture that is asynchronously
+     * completed using the given executor with the result of the given
+     * function of this CompletableFuture.  If this CompletableFuture
+     * completes exceptionally, then the returned CompletableFuture
+     * also does so, with a CompletionException holding this exception as
+     * its cause.
+     *
+     * @param fn the function to use to compute the value of
+     * the returned CompletableFuture
+     * @param executor the executor to use for asynchronous execution
+     * @return the new CompletableFuture
+     */
+    public <U> CompletableFuture<U> thenApplyAsync
+        (Function<? super T,? extends U> fn,
+         Executor executor) {
+        if (executor == null) throw new NullPointerException();
+        return doThenApply(fn, executor);
+    }
+
+    private <U> CompletableFuture<U> doThenApply
+        (Function<? super T,? extends U> fn,
+         Executor e) {
+        if (fn == null) throw new NullPointerException();
+        CompletableFuture<U> dst = new CompletableFuture<U>();
+        ApplyCompletion<T,U> d = null;
+        Object r;
+        if ((r = result) == null) {
+            CompletionNode p = new CompletionNode
+                (d = new ApplyCompletion<T,U>(this, fn, dst, e));
+            while ((r = result) == null) {
+                if (UNSAFE.compareAndSwapObject
+                    (this, COMPLETIONS, p.next = completions, p))
+                    break;
+            }
+        }
+        if (r != null && (d == null || d.compareAndSet(0, 1))) {
+            T t; Throwable ex;
+            if (r instanceof AltResult) {
+                ex = ((AltResult)r).ex;
+                t = null;
+            }
+            else {
+                ex = null;
+                @SuppressWarnings("unchecked") T tr = (T) r;
+                t = tr;
+            }
+            U u = null;
+            if (ex == null) {
+                try {
+                    if (e != null)
+                        e.execute(new AsyncApply<T,U>(t, fn, dst));
+                    else
+                        u = fn.apply(t);
+                } catch (Throwable rex) {
+                    ex = rex;
+                }
+            }
+            if (e == null || ex != null)
+                dst.internalComplete(u, ex);
+        }
+        helpPostComplete();
+        return dst;
+    }
+
+    /**
+     * Creates and returns a CompletableFuture that is completed after
+     * performing the given action with this CompletableFuture's
+     * result when it completes.  If this CompletableFuture
+     * completes exceptionally, then the returned CompletableFuture
+     * also does so, with a CompletionException holding this exception as
+     * its cause.
+     *
+     * @param block the action to perform before completing the
+     * returned CompletableFuture
+     * @return the new CompletableFuture
+     */
+    public CompletableFuture<Void> thenAccept(Consumer<? super T> block) {
+        return doThenAccept(block, null);
+    }
+
+    /**
+     * Creates and returns a CompletableFuture that is asynchronously
+     * completed using the {@link ForkJoinPool#commonPool()} with this
+     * CompletableFuture's result when it completes.  If this
+     * CompletableFuture completes exceptionally, then the returned
+     * CompletableFuture also does so, with a CompletionException holding
+     * this exception as its cause.
+     *
+     * @param block the action to perform before completing the
+     * returned CompletableFuture
+     * @return the new CompletableFuture
+     */
+    public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> block) {
+        return doThenAccept(block, ForkJoinPool.commonPool());
+    }
+
+    /**
+     * Creates and returns a CompletableFuture that is asynchronously
+     * completed using the given executor with this
+     * CompletableFuture's result when it completes.  If this
+     * CompletableFuture completes exceptionally, then the returned
+     * CompletableFuture also does so, with a CompletionException holding
+     * this exception as its cause.
+     *
+     * @param block the action to perform before completing the
+     * returned CompletableFuture
+     * @param executor the executor to use for asynchronous execution
+     * @return the new CompletableFuture
+     */
+    public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> block,
+                                                   Executor executor) {
+        if (executor == null) throw new NullPointerException();
+        return doThenAccept(block, executor);
+    }
+
+    private CompletableFuture<Void> doThenAccept(Consumer<? super T> fn,
+                                                 Executor e) {
+        if (fn == null) throw new NullPointerException();
+        CompletableFuture<Void> dst = new CompletableFuture<Void>();
+        AcceptCompletion<T> d = null;
+        Object r;
+        if ((r = result) == null) {
+            CompletionNode p = new CompletionNode
+                (d = new AcceptCompletion<T>(this, fn, dst, e));
+            while ((r = result) == null) {
+                if (UNSAFE.compareAndSwapObject
+                    (this, COMPLETIONS, p.next = completions, p))
+                    break;
+            }
+        }
+        if (r != null && (d == null || d.compareAndSet(0, 1))) {
+            T t; Throwable ex;
+            if (r instanceof AltResult) {
+                ex = ((AltResult)r).ex;
+                t = null;
+            }
+            else {
+                ex = null;
+                @SuppressWarnings("unchecked") T tr = (T) r;
+                t = tr;
+            }
+            if (ex == null) {
+                try {
+                    if (e != null)
+                        e.execute(new AsyncAccept<T>(t, fn, dst));
+                    else
+                        fn.accept(t);
+                } catch (Throwable rex) {
+                    ex = rex;
+                }
+            }
+            if (e == null || ex != null)
+                dst.internalComplete(null, ex);
+        }
+        helpPostComplete();
+        return dst;
+    }
+
+    /**
+     * Creates and returns a CompletableFuture that is completed after
+     * performing the given action when this CompletableFuture
+     * completes.  If this CompletableFuture completes exceptionally,
+     * then the returned CompletableFuture also does so, with a
+     * CompletionException holding this exception as its cause.
+     *
+     * @param action the action to perform before completing the
+     * returned CompletableFuture
+     * @return the new CompletableFuture
+     */
+    public CompletableFuture<Void> thenRun(Runnable action) {
+        return doThenRun(action, null);
+    }
+
+    /**
+     * Creates and returns a CompletableFuture that is asynchronously
+     * completed using the {@link ForkJoinPool#commonPool()} after
+     * performing the given action when this CompletableFuture
+     * completes.  If this CompletableFuture completes exceptionally,
+     * then the returned CompletableFuture also does so, with a
+     * CompletionException holding this exception as its cause.
+     *
+     * @param action the action to perform before completing the
+     * returned CompletableFuture
+     * @return the new CompletableFuture
+     */
+    public CompletableFuture<Void> thenRunAsync(Runnable action) {
+        return doThenRun(action, ForkJoinPool.commonPool());
+    }
+
+    /**
+     * Creates and returns a CompletableFuture that is asynchronously
+     * completed using the given executor after performing the given
+     * action when this CompletableFuture completes.  If this
+     * CompletableFuture completes exceptionally, then the returned
+     * CompletableFuture also does so, with a CompletionException holding
+     * this exception as its cause.
+     *
+     * @param action the action to perform before completing the
+     * returned CompletableFuture
+     * @param executor the executor to use for asynchronous execution
+     * @return the new CompletableFuture
+     */
+    public CompletableFuture<Void> thenRunAsync(Runnable action,
+                                                Executor executor) {
+        if (executor == null) throw new NullPointerException();
+        return doThenRun(action, executor);
+    }
+
+    private CompletableFuture<Void> doThenRun(Runnable action,
+                                              Executor e) {
+        if (action == null) throw new NullPointerException();
+        CompletableFuture<Void> dst = new CompletableFuture<Void>();
+        RunCompletion<T> d = null;
+        Object r;
+        if ((r = result) == null) {
+            CompletionNode p = new CompletionNode
+                (d = new RunCompletion<T>(this, action, dst, e));
+            while ((r = result) == null) {
+                if (UNSAFE.compareAndSwapObject
+                    (this, COMPLETIONS, p.next = completions, p))
+                    break;
+            }
+        }
+        if (r != null && (d == null || d.compareAndSet(0, 1))) {
+            Throwable ex;
+            if (r instanceof AltResult)
+                ex = ((AltResult)r).ex;
+            else
+                ex = null;
+            if (ex == null) {
+                try {
+                    if (e != null)
+                        e.execute(new AsyncRun(action, dst));
+                    else
+                        action.run();
+                } catch (Throwable rex) {
+                    ex = rex;
+                }
+            }
+            if (e == null || ex != null)
+                dst.internalComplete(null, ex);
+        }
+        helpPostComplete();
+        return dst;
+    }
+
+    /**
+     * Creates and returns a CompletableFuture that is completed with
+     * the result of the given function of this and the other given
+     * CompletableFuture's results when both complete.  If this or
+     * the other CompletableFuture complete exceptionally, then the
+     * returned CompletableFuture also does so, with a
+     * CompletionException holding the exception as its cause.
+     *
+     * @param other the other CompletableFuture
+     * @param fn the function to use to compute the value of
+     * the returned CompletableFuture
+     * @return the new CompletableFuture
+     */
+    public <U,V> CompletableFuture<V> thenCombine
+        (CompletableFuture<? extends U> other,
+         BiFunction<? super T,? super U,? extends V> fn) {
+        return doThenBiApply(other, fn, null);
+    }
+
+    /**
+     * Creates and returns a CompletableFuture that is asynchronously
+     * completed using the {@link ForkJoinPool#commonPool()} with
+     * the result of the given function of this and the other given
+     * CompletableFuture's results when both complete.  If this or
+     * the other CompletableFuture complete exceptionally, then the
+     * returned CompletableFuture also does so, with a
+     * CompletionException holding the exception as its cause.
+     *
+     * @param other the other CompletableFuture
+     * @param fn the function to use to compute the value of
+     * the returned CompletableFuture
+     * @return the new CompletableFuture
+     */
+    public <U,V> CompletableFuture<V> thenCombineAsync
+        (CompletableFuture<? extends U> other,
+         BiFunction<? super T,? super U,? extends V> fn) {
+        return doThenBiApply(other, fn, ForkJoinPool.commonPool());
+    }
+
+    /**
+     * Creates and returns a CompletableFuture that is
+     * asynchronously completed using the given executor with the
+     * result of the given function of this and the other given
+     * CompletableFuture's results when both complete.  If this or
+     * the other CompletableFuture complete exceptionally, then the
+     * returned CompletableFuture also does so, with a
+     * CompletionException holding the exception as its cause.
+     *
+     * @param other the other CompletableFuture
+     * @param fn the function to use to compute the value of
+     * the returned CompletableFuture
+     * @param executor the executor to use for asynchronous execution
+     * @return the new CompletableFuture
+     */
+    public <U,V> CompletableFuture<V> thenCombineAsync
+        (CompletableFuture<? extends U> other,
+         BiFunction<? super T,? super U,? extends V> fn,
+         Executor executor) {
+        if (executor == null) throw new NullPointerException();
+        return doThenBiApply(other, fn, executor);
+    }
+
+    private <U,V> CompletableFuture<V> doThenBiApply
+        (CompletableFuture<? extends U> other,
+         BiFunction<? super T,? super U,? extends V> fn,
+         Executor e) {
+        if (other == null || fn == null) throw new NullPointerException();
+        CompletableFuture<V> dst = new CompletableFuture<V>();
+        BiApplyCompletion<T,U,V> d = null;
+        Object r, s = null;
+        if ((r = result) == null || (s = other.result) == null) {
+            d = new BiApplyCompletion<T,U,V>(this, other, fn, dst, e);
+            CompletionNode q = null, p = new CompletionNode(d);
+            while ((r == null && (r = result) == null) ||
+                   (s == null && (s = other.result) == null)) {
+                if (q != null) {
+                    if (s != null ||
+                        UNSAFE.compareAndSwapObject
+                        (other, COMPLETIONS, q.next = other.completions, q))
+                        break;
+                }
+                else if (r != null ||
+                         UNSAFE.compareAndSwapObject
+                         (this, COMPLETIONS, p.next = completions, p)) {
+                    if (s != null)
+                        break;
+                    q = new CompletionNode(d);
+                }
+            }
+        }
+        if (r != null && s != null && (d == null || d.compareAndSet(0, 1))) {
+            T t; U u; Throwable ex;
+            if (r instanceof AltResult) {
+                ex = ((AltResult)r).ex;
+                t = null;
+            }
+            else {
+                ex = null;
+                @SuppressWarnings("unchecked") T tr = (T) r;
+                t = tr;
+            }
+            if (ex != null)
+                u = null;
+            else if (s instanceof AltResult) {
+                ex = ((AltResult)s).ex;
+                u = null;
+            }
+            else {
+                @SuppressWarnings("unchecked") U us = (U) s;
+                u = us;
+            }
+            V v = null;
+            if (ex == null) {
+                try {
+                    if (e != null)
+                        e.execute(new AsyncBiApply<T,U,V>(t, u, fn, dst));
+                    else
+                        v = fn.apply(t, u);
+                } catch (Throwable rex) {
+                    ex = rex;
+                }
+            }
+            if (e == null || ex != null)
+                dst.internalComplete(v, ex);
+        }
+        helpPostComplete();
+        other.helpPostComplete();
+        return dst;
+    }
+
+    /**
+     * Creates and returns a CompletableFuture that is completed with
+     * the results of this and the other given CompletableFuture if
+     * both complete.  If this and/or the other CompletableFuture
+     * complete exceptionally, then the returned CompletableFuture
+     * also does so, with a CompletionException holding one of these
+     * exceptions as its cause.
+     *
+     * @param other the other CompletableFuture
+     * @param block the action to perform before completing the
+     * returned CompletableFuture
+     * @return the new CompletableFuture
+     */
+    public <U> CompletableFuture<Void> thenAcceptBoth
+        (CompletableFuture<? extends U> other,
+         BiConsumer<? super T, ? super U> block) {
+        return doThenBiAccept(other, block, null);
+    }
+
+    /**
+     * Creates and returns a CompletableFuture that is completed
+     * asynchronously using the {@link ForkJoinPool#commonPool()} with
+     * the results of this and the other given CompletableFuture when
+     * both complete.  If this and/or the other CompletableFuture
+     * complete exceptionally, then the returned CompletableFuture
+     * also does so, with a CompletionException holding one of these
+     * exceptions as its cause.
+     *
+     * @param other the other CompletableFuture
+     * @param block the action to perform before completing the
+     * returned CompletableFuture
+     * @return the new CompletableFuture
+     */
+    public <U> CompletableFuture<Void> thenAcceptBothAsync
+        (CompletableFuture<? extends U> other,
+         BiConsumer<? super T, ? super U> block) {
+        return doThenBiAccept(other, block, ForkJoinPool.commonPool());
+    }
+
+    /**
+     * Creates and returns a CompletableFuture that is completed
+     * asynchronously using the given executor with the results of
+     * this and the other given CompletableFuture when both complete.
+     * If this and/or the other CompletableFuture complete exceptionally,
+     * then the returned CompletableFuture also does so, with a
+     * CompletionException holding one of these exceptions as its cause.
+     *
+     * @param other the other CompletableFuture
+     * @param block the action to perform before completing the
+     * returned CompletableFuture
+     * @param executor the executor to use for asynchronous execution
+     * @return the new CompletableFuture
+     */
+    public <U> CompletableFuture<Void> thenAcceptBothAsync
+        (CompletableFuture<? extends U> other,
+         BiConsumer<? super T, ? super U> block,
+         Executor executor) {
+        if (executor == null) throw new NullPointerException();
+        return doThenBiAccept(other, block, executor);
+    }
+
+    private <U> CompletableFuture<Void> doThenBiAccept
+        (CompletableFuture<? extends U> other,
+         BiConsumer<? super T,? super U> fn,
+         Executor e) {
+        if (other == null || fn == null) throw new NullPointerException();
+        CompletableFuture<Void> dst = new CompletableFuture<Void>();
+        BiAcceptCompletion<T,U> d = null;
+        Object r, s = null;
+        if ((r = result) == null || (s = other.result) == null) {
+            d = new BiAcceptCompletion<T,U>(this, other, fn, dst, e);
+            CompletionNode q = null, p = new CompletionNode(d);
+            while ((r == null && (r = result) == null) ||
+                   (s == null && (s = other.result) == null)) {
+                if (q != null) {
+                    if (s != null ||
+                        UNSAFE.compareAndSwapObject
+                        (other, COMPLETIONS, q.next = other.completions, q))
+                        break;
+                }
+                else if (r != null ||
+                         UNSAFE.compareAndSwapObject
+                         (this, COMPLETIONS, p.next = completions, p)) {
+                    if (s != null)
+                        break;
+                    q = new CompletionNode(d);
+                }
+            }
+        }
+        if (r != null && s != null && (d == null || d.compareAndSet(0, 1))) {
+            T t; U u; Throwable ex;
+            if (r instanceof AltResult) {
+                ex = ((AltResult)r).ex;
+                t = null;
+            }
+            else {
+                ex = null;
+                @SuppressWarnings("unchecked") T tr = (T) r;
+                t = tr;
+            }
+            if (ex != null)
+                u = null;
+            else if (s instanceof AltResult) {
+                ex = ((AltResult)s).ex;
+                u = null;
+            }
+            else {
+                @SuppressWarnings("unchecked") U us = (U) s;
+                u = us;
+            }
+            if (ex == null) {
+                try {
+                    if (e != null)
+                        e.execute(new AsyncBiAccept<T,U>(t, u, fn, dst));
+                    else
+                        fn.accept(t, u);
+                } catch (Throwable rex) {
+                    ex = rex;
+                }
+            }
+            if (e == null || ex != null)
+                dst.internalComplete(null, ex);
+        }
+        helpPostComplete();
+        other.helpPostComplete();
+        return dst;
+    }
+
+    /**
+     * Creates and returns a CompletableFuture that is completed when
+     * this and the other given CompletableFuture both complete.
+     * If this and/or the other CompletableFuture complete exceptionally,
+     * then the returned CompletableFuture also does so, with a
+     * CompletionException holding one of these exceptions as its cause.
+     *
+     * @param other the other CompletableFuture
+     * @param action the action to perform before completing the
+     * returned CompletableFuture
+     * @return the new CompletableFuture
+     */
+    public CompletableFuture<Void> runAfterBoth(CompletableFuture<?> other,
+                                                Runnable action) {
+        return doThenBiRun(other, action, null);
+    }
+
+    /**
+     * Creates and returns a CompletableFuture that is completed
+     * asynchronously using the {@link ForkJoinPool#commonPool()}
+     * when this and the other given CompletableFuture both complete.
+     * If this and/or the other CompletableFuture complete exceptionally,
+     * then the returned CompletableFuture also does so, with a
+     * CompletionException holding one of these exceptions as its cause.
+     *
+     * @param other the other CompletableFuture
+     * @param action the action to perform before completing the
+     * returned CompletableFuture
+     * @return the new CompletableFuture
+     */
+    public CompletableFuture<Void> runAfterBothAsync(CompletableFuture<?> other,
+                                                     Runnable action) {
+        return doThenBiRun(other, action, ForkJoinPool.commonPool());
+    }
+
+    /**
+     * Creates and returns a CompletableFuture that is completed
+     * asynchronously using the given executor when this and the
+     * other given CompletableFuture both complete.
+     * If this and/or the other CompletableFuture complete exceptionally,
+     * then the returned CompletableFuture also does so, with a
+     * CompletionException holding one of these exceptions as its cause.
+     *
+     * @param other the other CompletableFuture
+     * @param action the action to perform before completing the
+     * returned CompletableFuture
+     * @param executor the executor to use for asynchronous execution
+     * @return the new CompletableFuture
+     */
+    public CompletableFuture<Void> runAfterBothAsync(CompletableFuture<?> other,
+                                                     Runnable action,
+                                                     Executor executor) {
+        if (executor == null) throw new NullPointerException();
+        return doThenBiRun(other, action, executor);
+    }
+
+    private CompletableFuture<Void> doThenBiRun(CompletableFuture<?> other,
+                                                Runnable action,
+                                                Executor e) {
+        if (other == null || action == null) throw new NullPointerException();
+        CompletableFuture<Void> dst = new CompletableFuture<Void>();
+        BiRunCompletion<T> d = null;
+        Object r, s = null;
+        if ((r = result) == null || (s = other.result) == null) {
+            d = new BiRunCompletion<T>(this, other, action, dst, e);
+            CompletionNode q = null, p = new CompletionNode(d);
+            while ((r == null && (r = result) == null) ||
+                   (s == null && (s = other.result) == null)) {
+                if (q != null) {
+                    if (s != null ||
+                        UNSAFE.compareAndSwapObject
+                        (other, COMPLETIONS, q.next = other.completions, q))
+                        break;
+                }
+                else if (r != null ||
+                         UNSAFE.compareAndSwapObject
+                         (this, COMPLETIONS, p.next = completions, p)) {
+                    if (s != null)
+                        break;
+                    q = new CompletionNode(d);
+                }
+            }
+        }
+        if (r != null && s != null && (d == null || d.compareAndSet(0, 1))) {
+            Throwable ex;
+            if (r instanceof AltResult)
+                ex = ((AltResult)r).ex;
+            else
+                ex = null;
+            if (ex == null && (s instanceof AltResult))
+                ex = ((AltResult)s).ex;
+            if (ex == null) {
+                try {
+                    if (e != null)
+                        e.execute(new AsyncRun(action, dst));
+                    else
+                        action.run();
+                } catch (Throwable rex) {
+                    ex = rex;
+                }
+            }
+            if (e == null || ex != null)
+                dst.internalComplete(null, ex);
+        }
+        helpPostComplete();
+        other.helpPostComplete();
+        return dst;
+    }
+
+    /**
+     * Creates and returns a CompletableFuture that is completed with
+     * the result of the given function of either this or the other
+     * given CompletableFuture's results when either complete.
+     * If this and/or the other CompletableFuture complete exceptionally,
+     * then the returned CompletableFuture may also do so, with a
+     * CompletionException holding one of these exceptions as its cause.
+     * No guarantees are made about which result or exception is used
+     * in the returned CompletableFuture.
+     *
+     * @param other the other CompletableFuture
+     * @param fn the function to use to compute the value of
+     * the returned CompletableFuture
+     * @return the new CompletableFuture
+     */
+    public <U> CompletableFuture<U> applyToEither
+        (CompletableFuture<? extends T> other,
+         Function<? super T, U> fn) {
+        return doOrApply(other, fn, null);
+    }
+
+    /**
+     * Creates and returns a CompletableFuture that is completed
+     * asynchronously using the {@link ForkJoinPool#commonPool()} with
+     * the result of the given function of either this or the other
+     * given CompletableFuture's results when either complete.
+     * If this and/or the other CompletableFuture complete exceptionally,
+     * then the returned CompletableFuture may also do so, with a
+     * CompletionException holding one of these exceptions as its cause.
+     * No guarantees are made about which result or exception is used
+     * in the returned CompletableFuture.
+     *
+     * @param other the other CompletableFuture
+     * @param fn the function to use to compute the value of
+     * the returned CompletableFuture
+     * @return the new CompletableFuture
+     */
+    public <U> CompletableFuture<U> applyToEitherAsync
+        (CompletableFuture<? extends T> other,
+         Function<? super T, U> fn) {
+        return doOrApply(other, fn, ForkJoinPool.commonPool());
+    }
+
+    /**
+     * Creates and returns a CompletableFuture that is completed
+     * asynchronously using the given executor with the result of the
+     * given function of either this or the other given
+     * CompletableFuture's results when either complete.  If this
+     * and/or the other CompletableFuture complete exceptionally, then
+     * the returned CompletableFuture may also do so, with a
+     * CompletionException holding one of these exceptions as its cause.
+     * No guarantees are made about which result or exception is used
+     * in the returned CompletableFuture.
+     *
+     * @param other the other CompletableFuture
+     * @param fn the function to use to compute the value of
+     * the returned CompletableFuture
+     * @param executor the executor to use for asynchronous execution
+     * @return the new CompletableFuture
+     */
+    public <U> CompletableFuture<U> applyToEitherAsync
+        (CompletableFuture<? extends T> other,
+         Function<? super T, U> fn,
+         Executor executor) {
+        if (executor == null) throw new NullPointerException();
+        return doOrApply(other, fn, executor);
+    }
+
+    private <U> CompletableFuture<U> doOrApply
+        (CompletableFuture<? extends T> other,
+         Function<? super T, U> fn,
+         Executor e) {
+        if (other == null || fn == null) throw new NullPointerException();
+        CompletableFuture<U> dst = new CompletableFuture<U>();
+        OrApplyCompletion<T,U> d = null;
+        Object r;
+        if ((r = result) == null && (r = other.result) == null) {
+            d = new OrApplyCompletion<T,U>(this, other, fn, dst, e);
+            CompletionNode q = null, p = new CompletionNode(d);
+            while ((r = result) == null && (r = other.result) == null) {
+                if (q != null) {
+                    if (UNSAFE.compareAndSwapObject
+                        (other, COMPLETIONS, q.next = other.completions, q))
+                        break;
+                }
+                else if (UNSAFE.compareAndSwapObject
+                         (this, COMPLETIONS, p.next = completions, p))
+                    q = new CompletionNode(d);
+            }
+        }
+        if (r != null && (d == null || d.compareAndSet(0, 1))) {
+            T t; Throwable ex;
+            if (r instanceof AltResult) {
+                ex = ((AltResult)r).ex;
+                t = null;
+            }
+            else {
+                ex = null;
+                @SuppressWarnings("unchecked") T tr = (T) r;
+                t = tr;
+            }
+            U u = null;
+            if (ex == null) {
+                try {
+                    if (e != null)
+                        e.execute(new AsyncApply<T,U>(t, fn, dst));
+                    else
+                        u = fn.apply(t);
+                } catch (Throwable rex) {
+                    ex = rex;
+                }
+            }
+            if (e == null || ex != null)
+                dst.internalComplete(u, ex);
+        }
+        helpPostComplete();
+        other.helpPostComplete();
+        return dst;
+    }
+
+    /**
+     * Creates and returns a CompletableFuture that is completed after
+     * performing the given action with the result of either this or the
+     * other given CompletableFuture's result, when either complete.
+     * If this and/or the other CompletableFuture complete exceptionally,
+     * then the returned CompletableFuture may also do so, with a
+     * CompletionException holding one of these exceptions as its cause.
+     * No guarantees are made about which exception is used in the
+     * returned CompletableFuture.
+     *
+     * @param other the other CompletableFuture
+     * @param block the action to perform before completing the
+     * returned CompletableFuture
+     * @return the new CompletableFuture
+     */
+    public CompletableFuture<Void> acceptEither
+        (CompletableFuture<? extends T> other,
+         Consumer<? super T> block) {
+        return doOrAccept(other, block, null);
+    }
+
+    /**
+     * Creates and returns a CompletableFuture that is completed
+     * asynchronously using the {@link ForkJoinPool#commonPool()},
+     * performing the given action with the result of either this or
+     * the other given CompletableFuture's result, when either complete.
+     * If this and/or the other CompletableFuture complete exceptionally,
+     * then the returned CompletableFuture may also do so, with a
+     * CompletionException holding one of these exceptions as its cause.
+     * No guarantees are made about which exception is used in the
+     * returned CompletableFuture.
+     *
+     * @param other the other CompletableFuture
+     * @param block the action to perform before completing the
+     * returned CompletableFuture
+     * @return the new CompletableFuture
+     */
+    public CompletableFuture<Void> acceptEitherAsync
+        (CompletableFuture<? extends T> other,
+         Consumer<? super T> block) {
+        return doOrAccept(other, block, ForkJoinPool.commonPool());
+    }
+
+    /**
+     * Creates and returns a CompletableFuture that is completed
+     * asynchronously using the given executor, performing the given
+     * action with the result of either this or the other given
+     * CompletableFuture's result, when either complete.
+     * If this and/or the other CompletableFuture complete exceptionally,
+     * then the returned CompletableFuture may also do so, with a
+     * CompletionException holding one of these exceptions as its cause.
+     * No guarantees are made about which exception is used in the
+     * returned CompletableFuture.
+     *
+     * @param other the other CompletableFuture
+     * @param block the action to perform before completing the
+     * returned CompletableFuture
+     * @param executor the executor to use for asynchronous execution
+     * @return the new CompletableFuture
+     */
+    public CompletableFuture<Void> acceptEitherAsync
+        (CompletableFuture<? extends T> other,
+         Consumer<? super T> block,
+         Executor executor) {
+        if (executor == null) throw new NullPointerException();
+        return doOrAccept(other, block, executor);
+    }
+
+    private CompletableFuture<Void> doOrAccept
+        (CompletableFuture<? extends T> other,
+         Consumer<? super T> fn,
+         Executor e) {
+        if (other == null || fn == null) throw new NullPointerException();
+        CompletableFuture<Void> dst = new CompletableFuture<Void>();
+        OrAcceptCompletion<T> d = null;
+        Object r;
+        if ((r = result) == null && (r = other.result) == null) {
+            d = new OrAcceptCompletion<T>(this, other, fn, dst, e);
+            CompletionNode q = null, p = new CompletionNode(d);
+            while ((r = result) == null && (r = other.result) == null) {
+                if (q != null) {
+                    if (UNSAFE.compareAndSwapObject
+                        (other, COMPLETIONS, q.next = other.completions, q))
+                        break;
+                }
+                else if (UNSAFE.compareAndSwapObject
+                         (this, COMPLETIONS, p.next = completions, p))
+                    q = new CompletionNode(d);
+            }
+        }
+        if (r != null && (d == null || d.compareAndSet(0, 1))) {
+            T t; Throwable ex;
+            if (r instanceof AltResult) {
+                ex = ((AltResult)r).ex;
+                t = null;
+            }
+            else {
+                ex = null;
+                @SuppressWarnings("unchecked") T tr = (T) r;
+                t = tr;
+            }
+            if (ex == null) {
+                try {
+                    if (e != null)
+                        e.execute(new AsyncAccept<T>(t, fn, dst));
+                    else
+                        fn.accept(t);
+                } catch (Throwable rex) {
+                    ex = rex;
+                }
+            }
+            if (e == null || ex != null)
+                dst.internalComplete(null, ex);
+        }
+        helpPostComplete();
+        other.helpPostComplete();
+        return dst;
+    }
+
+    /**
+     * Creates and returns a CompletableFuture that is completed
+     * after this or the other given CompletableFuture complete.
+     * If this and/or the other CompletableFuture complete exceptionally,
+     * then the returned CompletableFuture may also do so, with a
+     * CompletionException holding one of these exceptions as its cause.
+     * No guarantees are made about which exception is used in the
+     * returned CompletableFuture.
+     *
+     * @param other the other CompletableFuture
+     * @param action the action to perform before completing the
+     * returned CompletableFuture
+     * @return the new CompletableFuture
+     */
+    public CompletableFuture<Void> runAfterEither(CompletableFuture<?> other,
+                                                  Runnable action) {
+        return doOrRun(other, action, null);
+    }
+
+    /**
+     * Creates and returns a CompletableFuture that is completed
+     * asynchronously using the {@link ForkJoinPool#commonPool()}
+     * after this or the other given CompletableFuture complete.
+     * If this and/or the other CompletableFuture complete exceptionally,
+     * then the returned CompletableFuture may also do so, with a
+     * CompletionException holding one of these exceptions as its cause.
+     * No guarantees are made about which exception is used in the
+     * returned CompletableFuture.
+     *
+     * @param other the other CompletableFuture
+     * @param action the action to perform before completing the
+     * returned CompletableFuture
+     * @return the new CompletableFuture
+     */
+    public CompletableFuture<Void> runAfterEitherAsync
+        (CompletableFuture<?> other,
+         Runnable action) {
+        return doOrRun(other, action, ForkJoinPool.commonPool());
+    }
+
+    /**
+     * Creates and returns a CompletableFuture that is completed
+     * asynchronously using the given executor after this or the other
+     * given CompletableFuture complete.
+     * If this and/or the other CompletableFuture complete exceptionally,
+     * then the returned CompletableFuture may also do so, with a
+     * CompletionException holding one of these exceptions as its cause.
+     * No guarantees are made about which exception is used in the
+     * returned CompletableFuture.
+     *
+     * @param other the other CompletableFuture
+     * @param action the action to perform before completing the
+     * returned CompletableFuture
+     * @param executor the executor to use for asynchronous execution
+     * @return the new CompletableFuture
+     */
+    public CompletableFuture<Void> runAfterEitherAsync
+        (CompletableFuture<?> other,
+         Runnable action,
+         Executor executor) {
+        if (executor == null) throw new NullPointerException();
+        return doOrRun(other, action, executor);
+    }
+
+    private CompletableFuture<Void> doOrRun(CompletableFuture<?> other,
+                                            Runnable action,
+                                            Executor e) {
+        if (other == null || action == null) throw new NullPointerException();
+        CompletableFuture<Void> dst = new CompletableFuture<Void>();
+        OrRunCompletion<T> d = null;
+        Object r;
+        if ((r = result) == null && (r = other.result) == null) {
+            d = new OrRunCompletion<T>(this, other, action, dst, e);
+            CompletionNode q = null, p = new CompletionNode(d);
+            while ((r = result) == null && (r = other.result) == null) {
+                if (q != null) {
+                    if (UNSAFE.compareAndSwapObject
+                        (other, COMPLETIONS, q.next = other.completions, q))
+                        break;
+                }
+                else if (UNSAFE.compareAndSwapObject
+                         (this, COMPLETIONS, p.next = completions, p))
+                    q = new CompletionNode(d);
+            }
+        }
+        if (r != null && (d == null || d.compareAndSet(0, 1))) {
+            Throwable ex;
+            if (r instanceof AltResult)
+                ex = ((AltResult)r).ex;
+            else
+                ex = null;
+            if (ex == null) {
+                try {
+                    if (e != null)
+                        e.execute(new AsyncRun(action, dst));
+                    else
+                        action.run();
+                } catch (Throwable rex) {
+                    ex = rex;
+                }
+            }
+            if (e == null || ex != null)
+                dst.internalComplete(null, ex);
+        }
+        helpPostComplete();
+        other.helpPostComplete();
+        return dst;
+    }
+
+    /**
+     * Returns a CompletableFuture (or an equivalent one) produced by
+     * the given function of the result of this CompletableFuture when
+     * completed.  If this CompletableFuture completes exceptionally,
+     * then the returned CompletableFuture also does so, with a
+     * CompletionException holding this exception as its cause.
+     *
+     * @param fn the function returning a new CompletableFuture
+     * @return the CompletableFuture, that {@code isDone()} upon
+     * return if completed by the given function, or an exception
+     * occurs
+     */
+    public <U> CompletableFuture<U> thenCompose
+        (Function<? super T, CompletableFuture<U>> fn) {
+        return doCompose(fn, null);
+    }
+
+    /**
+     * Returns a CompletableFuture (or an equivalent one) produced
+     * asynchronously using the {@link ForkJoinPool#commonPool()} by
+     * the given function of the result of this CompletableFuture when
+     * completed.  If this CompletableFuture completes exceptionally,
+     * then the returned CompletableFuture also does so, with a
+     * CompletionException holding this exception as its cause.
+     *
+     * @param fn the function returning a new CompletableFuture
+     * @return the CompletableFuture, that {@code isDone()} upon
+     * return if completed by the given function, or an exception
+     * occurs
+     */
+    public <U> CompletableFuture<U> thenComposeAsync
+        (Function<? super T, CompletableFuture<U>> fn) {
+        return doCompose(fn, ForkJoinPool.commonPool());
+    }
+
+    /**
+     * Returns a CompletableFuture (or an equivalent one) produced
+     * asynchronously using the given executor by the given function
+     * of the result of this CompletableFuture when completed.
+     * If this CompletableFuture completes exceptionally, then the
+     * returned CompletableFuture also does so, with a
+     * CompletionException holding this exception as its cause.
+     *
+     * @param fn the function returning a new CompletableFuture
+     * @param executor the executor to use for asynchronous execution
+     * @return the CompletableFuture, that {@code isDone()} upon
+     * return if completed by the given function, or an exception
+     * occurs
+     */
+    public <U> CompletableFuture<U> thenComposeAsync
+        (Function<? super T, CompletableFuture<U>> fn,
+         Executor executor) {
+        if (executor == null) throw new NullPointerException();
+        return doCompose(fn, executor);
+    }
+
+    private <U> CompletableFuture<U> doCompose
+        (Function<? super T, CompletableFuture<U>> fn,
+         Executor e) {
+        if (fn == null) throw new NullPointerException();
+        CompletableFuture<U> dst = null;
+        ComposeCompletion<T,U> d = null;
+        Object r;
+        if ((r = result) == null) {
+            dst = new CompletableFuture<U>();
+            CompletionNode p = new CompletionNode
+                (d = new ComposeCompletion<T,U>(this, fn, dst, e));
+            while ((r = result) == null) {
+                if (UNSAFE.compareAndSwapObject
+                    (this, COMPLETIONS, p.next = completions, p))
+                    break;
+            }
+        }
+        if (r != null && (d == null || d.compareAndSet(0, 1))) {
+            T t; Throwable ex;
+            if (r instanceof AltResult) {
+                ex = ((AltResult)r).ex;
+                t = null;
+            }
+            else {
+                ex = null;
+                @SuppressWarnings("unchecked") T tr = (T) r;
+                t = tr;
+            }
+            if (ex == null) {
+                if (e != null) {
+                    if (dst == null)
+                        dst = new CompletableFuture<U>();
+                    e.execute(new AsyncCompose<T,U>(t, fn, dst));
+                }
+                else {
+                    try {
+                        dst = fn.apply(t);
+                    } catch (Throwable rex) {
+                        ex = rex;
+                    }
+                    if (dst == null) {
+                        dst = new CompletableFuture<U>();
+                        if (ex == null)
+                            ex = new NullPointerException();
+                    }
+                }
+            }
+            if (e == null && ex != null)
+                dst.internalComplete(null, ex);
+        }
+        helpPostComplete();
+        dst.helpPostComplete();
+        return dst;
+    }
+
+    /**
+     * Creates and returns a CompletableFuture that is completed with
+     * the result of the given function of the exception triggering
+     * this CompletableFuture's completion when it completes
+     * exceptionally; Otherwise, if this CompletableFuture completes
+     * normally, then the returned CompletableFuture also completes
+     * normally with the same value.
+     *
+     * @param fn the function to use to compute the value of the
+     * returned CompletableFuture if this CompletableFuture completed
+     * exceptionally
+     * @return the new CompletableFuture
+     */
+    public CompletableFuture<T> exceptionally
+        (Function<Throwable, ? extends T> fn) {
+        if (fn == null) throw new NullPointerException();
+        CompletableFuture<T> dst = new CompletableFuture<T>();
+        ExceptionCompletion<T> d = null;
+        Object r;
+        if ((r = result) == null) {
+            CompletionNode p =
+                new CompletionNode(d = new ExceptionCompletion<T>(this, fn, dst));
+            while ((r = result) == null) {
+                if (UNSAFE.compareAndSwapObject(this, COMPLETIONS,
+                                                p.next = completions, p))
+                    break;
+            }
+        }
+        if (r != null && (d == null || d.compareAndSet(0, 1))) {
+            T t = null; Throwable ex, dx = null;
+            if (r instanceof AltResult) {
+                if ((ex = ((AltResult)r).ex) != null)  {
+                    try {
+                        t = fn.apply(ex);
+                    } catch (Throwable rex) {
+                        dx = rex;
+                    }
+                }
+            }
+            else {
+                @SuppressWarnings("unchecked") T tr = (T) r;
+                t = tr;
+            }
+            dst.internalComplete(t, dx);
+        }
+        helpPostComplete();
+        return dst;
+    }
+
+    /**
+     * Creates and returns a CompletableFuture that is completed with
+     * the result of the given function of the result and exception of
+     * this CompletableFuture's completion when it completes.  The
+     * given function is invoked with the result (or {@code null} if
+     * none) and the exception (or {@code null} if none) of this
+     * CompletableFuture when complete.
+     *
+     * @param fn the function to use to compute the value of the
+     * returned CompletableFuture
+     * @return the new CompletableFuture
+     */
+    public <U> CompletableFuture<U> handle
+        (BiFunction<? super T, Throwable, ? extends U> fn) {
+        if (fn == null) throw new NullPointerException();
+        CompletableFuture<U> dst = new CompletableFuture<U>();
+        HandleCompletion<T,U> d = null;
+        Object r;
+        if ((r = result) == null) {
+            CompletionNode p =
+                new CompletionNode(d = new HandleCompletion<T,U>(this, fn, dst));
+            while ((r = result) == null) {
+                if (UNSAFE.compareAndSwapObject(this, COMPLETIONS,
+                                                p.next = completions, p))
+                    break;
+            }
+        }
+        if (r != null && (d == null || d.compareAndSet(0, 1))) {
+            T t; Throwable ex;
+            if (r instanceof AltResult) {
+                ex = ((AltResult)r).ex;
+                t = null;
+            }
+            else {
+                ex = null;
+                @SuppressWarnings("unchecked") T tr = (T) r;
+                t = tr;
+            }
+            U u; Throwable dx;
+            try {
+                u = fn.apply(t, ex);
+                dx = null;
+            } catch (Throwable rex) {
+                dx = rex;
+                u = null;
+            }
+            dst.internalComplete(u, dx);
+        }
+        helpPostComplete();
+        return dst;
+    }
+
+
+    /* ------------- Arbitrary-arity constructions -------------- */
+
+    /*
+     * The basic plan of attack is to recursively form binary
+     * completion trees of elements. This can be overkill for small
+     * sets, but scales nicely. The And/All vs Or/Any forms use the
+     * same idea, but details differ.
+     */
+
+    /**
+     * Returns a new CompletableFuture that is completed when all of
+     * the given CompletableFutures complete.  If any of the component
+     * CompletableFutures complete exceptionally, then so does the
+     * returned CompletableFuture. Otherwise, the results, if any, of
+     * the component CompletableFutures are not reflected in the
+     * returned CompletableFuture, but may be obtained by inspecting
+     * them individually. If the number of components is zero, returns
+     * a CompletableFuture completed with the value {@code null}.
+     *
+     * <p>Among the applications of this method is to await completion
+     * of a set of independent CompletableFutures before continuing a
+     * program, as in: {@code CompletableFuture.allOf(c1, c2,
+     * c3).join();}.
+     *
+     * @param cfs the CompletableFutures
+     * @return a CompletableFuture that is complete when all of the
+     * given CompletableFutures complete
+     * @throws NullPointerException if the array or any of its elements are
+     * {@code null}
+     */
+    public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs) {
+        int len = cfs.length; // Directly handle empty and singleton cases
+        if (len > 1)
+            return allTree(cfs, 0, len - 1);
+        else {
+            CompletableFuture<Void> dst = new CompletableFuture<Void>();
+            CompletableFuture<?> f;
+            if (len == 0)
+                dst.result = NIL;
+            else if ((f = cfs[0]) == null)
+                throw new NullPointerException();
+            else {
+                ThenCopy d = null;
+                CompletionNode p = null;
+                Object r;
+                while ((r = f.result) == null) {
+                    if (d == null)
+                        d = new ThenCopy(f, dst);
+                    else if (p == null)
+                        p = new CompletionNode(d);
+                    else if (UNSAFE.compareAndSwapObject
+                             (f, COMPLETIONS, p.next = f.completions, p))
+                        break;
+                }
+                if (r != null && (d == null || d.compareAndSet(0, 1)))
+                    dst.internalComplete(null, (r instanceof AltResult) ?
+                                         ((AltResult)r).ex : null);
+                f.helpPostComplete();
+            }
+            return dst;
+        }
+    }
+
+    /**
+     * Recursively constructs an And'ed tree of CompletableFutures.
+     * Called only when array known to have at least two elements.
+     */
+    private static CompletableFuture<Void> allTree(CompletableFuture<?>[] cfs,
+                                                   int lo, int hi) {
+        CompletableFuture<?> fst, snd;
+        int mid = (lo + hi) >>> 1;
+        if ((fst = (lo == mid   ? cfs[lo] : allTree(cfs, lo,    mid))) == null ||
+            (snd = (hi == mid+1 ? cfs[hi] : allTree(cfs, mid+1, hi))) == null)
+            throw new NullPointerException();
+        CompletableFuture<Void> dst = new CompletableFuture<Void>();
+        AndCompletion d = null;
+        CompletionNode p = null, q = null;
+        Object r = null, s = null;
+        while ((r = fst.result) == null || (s = snd.result) == null) {
+            if (d == null)
+                d = new AndCompletion(fst, snd, dst);
+            else if (p == null)
+                p = new CompletionNode(d);
+            else if (q == null) {
+                if (UNSAFE.compareAndSwapObject
+                    (fst, COMPLETIONS, p.next = fst.completions, p))
+                    q = new CompletionNode(d);
+            }
+            else if (UNSAFE.compareAndSwapObject
+                     (snd, COMPLETIONS, q.next = snd.completions, q))
+                break;
+        }
+        if ((r != null || (r = fst.result) != null) &&
+            (s != null || (s = snd.result) != null) &&
+            (d == null || d.compareAndSet(0, 1))) {
+            Throwable ex;
+            if (r instanceof AltResult)
+                ex = ((AltResult)r).ex;
+            else
+                ex = null;
+            if (ex == null && (s instanceof AltResult))
+                ex = ((AltResult)s).ex;
+            dst.internalComplete(null, ex);
+        }
+        fst.helpPostComplete();
+        snd.helpPostComplete();
+        return dst;
+    }
+
+    /**
+     * Returns a new CompletableFuture that is completed when any of
+     * the component CompletableFutures complete; with the same result if
+     * it completed normally, otherwise exceptionally. If the number
+     * of components is zero, returns an incomplete CompletableFuture.
+     *
+     * @param cfs the CompletableFutures
+     * @return a CompletableFuture that is complete when any of the
+     * given CompletableFutures complete
+     * @throws NullPointerException if the array or any of its elements are
+     * {@code null}
+     */
+    public static CompletableFuture<?> anyOf(CompletableFuture<?>... cfs) {
+        int len = cfs.length; // Same idea as allOf
+        if (len > 1)
+            return anyTree(cfs, 0, len - 1);
+        else {
+            CompletableFuture<?> dst = new CompletableFuture<Object>();
+            CompletableFuture<?> f;
+            if (len == 0)
+                ; // skip
+            else if ((f = cfs[0]) == null)
+                throw new NullPointerException();
+            else {
+                ThenCopy d = null;
+                CompletionNode p = null;
+                Object r;
+                while ((r = f.result) == null) {
+                    if (d == null)
+                        d = new ThenCopy(f, dst);
+                    else if (p == null)
+                        p = new CompletionNode(d);
+                    else if (UNSAFE.compareAndSwapObject
+                             (f, COMPLETIONS, p.next = f.completions, p))
+                        break;
+                }
+                if (r != null && (d == null || d.compareAndSet(0, 1))) {
+                    Throwable ex; Object t;
+                    if (r instanceof AltResult) {
+                        ex = ((AltResult)r).ex;
+                        t = null;
+                    }
+                    else {
+                        ex = null;
+                        t = r;
+                    }
+                    dst.internalComplete(t, ex);
+                }
+                f.helpPostComplete();
+            }
+            return dst;
+        }
+    }
+
+    /**
+     * Recursively constructs an Or'ed tree of CompletableFutures.
+     */
+    private static CompletableFuture<?> anyTree(CompletableFuture<?>[] cfs,
+                                                int lo, int hi) {
+        CompletableFuture<?> fst, snd;
+        int mid = (lo + hi) >>> 1;
+        if ((fst = (lo == mid   ? cfs[lo] : anyTree(cfs, lo,    mid))) == null ||
+            (snd = (hi == mid+1 ? cfs[hi] : anyTree(cfs, mid+1, hi))) == null)
+            throw new NullPointerException();
+        CompletableFuture<?> dst = new CompletableFuture<Object>();
+        OrCompletion d = null;
+        CompletionNode p = null, q = null;
+        Object r;
+        while ((r = fst.result) == null && (r = snd.result) == null) {
+            if (d == null)
+                d = new OrCompletion(fst, snd, dst);
+            else if (p == null)
+                p = new CompletionNode(d);
+            else if (q == null) {
+                if (UNSAFE.compareAndSwapObject
+                    (fst, COMPLETIONS, p.next = fst.completions, p))
+                    q = new CompletionNode(d);
+            }
+            else if (UNSAFE.compareAndSwapObject
+                     (snd, COMPLETIONS, q.next = snd.completions, q))
+                break;
+        }
+        if ((r != null || (r = fst.result) != null ||
+             (r = snd.result) != null) &&
+            (d == null || d.compareAndSet(0, 1))) {
+            Throwable ex; Object t;
+            if (r instanceof AltResult) {
+                ex = ((AltResult)r).ex;
+                t = null;
+            }
+            else {
+                ex = null;
+                t = r;
+            }
+            dst.internalComplete(t, ex);
+        }
+        fst.helpPostComplete();
+        snd.helpPostComplete();
+        return dst;
+    }
+
+
+    /* ------------- Control and status methods -------------- */
+
+    /**
+     * If not already completed, completes this CompletableFuture with
+     * a {@link CancellationException}. Dependent CompletableFutures
+     * that have not already completed will also complete
+     * exceptionally, with a {@link CompletionException} caused by
+     * this {@code CancellationException}.
+     *
+     * @param mayInterruptIfRunning this value has no effect in this
+     * implementation because interrupts are not used to control
+     * processing.
+     *
+     * @return {@code true} if this task is now cancelled
+     */
+    public boolean cancel(boolean mayInterruptIfRunning) {
+        boolean cancelled = (result == null) &&
+            UNSAFE.compareAndSwapObject
+            (this, RESULT, null, new AltResult(new CancellationException()));
+        postComplete();
+        return cancelled || isCancelled();
+    }
+
+    /**
+     * Returns {@code true} if this CompletableFuture was cancelled
+     * before it completed normally.
+     *
+     * @return {@code true} if this CompletableFuture was cancelled
+     * before it completed normally
+     */
+    public boolean isCancelled() {
+        Object r;
+        return ((r = result) instanceof AltResult) &&
+            (((AltResult)r).ex instanceof CancellationException);
+    }
+
+    /**
+     * Forcibly sets or resets the value subsequently returned by
+     * method {@link #get()} and related methods, whether or not
+     * already completed. This method is designed for use only in
+     * error recovery actions, and even in such situations may result
+     * in ongoing dependent completions using established versus
+     * overwritten outcomes.
+     *
+     * @param value the completion value
+     */
+    public void obtrudeValue(T value) {
+        result = (value == null) ? NIL : value;
+        postComplete();
+    }
+
+    /**
+     * Forcibly causes subsequent invocations of method {@link #get()}
+     * and related methods to throw the given exception, whether or
+     * not already completed. This method is designed for use only in
+     * recovery actions, and even in such situations may result in
+     * ongoing dependent completions using established versus
+     * overwritten outcomes.
+     *
+     * @param ex the exception
+     */
+    public void obtrudeException(Throwable ex) {
+        if (ex == null) throw new NullPointerException();
+        result = new AltResult(ex);
+        postComplete();
+    }
+
+    /**
+     * Returns the estimated number of CompletableFutures whose
+     * completions are awaiting completion of this CompletableFuture.
+     * This method is designed for use in monitoring system state, not
+     * for synchronization control.
+     *
+     * @return the number of dependent CompletableFutures
+     */
+    public int getNumberOfDependents() {
+        int count = 0;
+        for (CompletionNode p = completions; p != null; p = p.next)
+            ++count;
+        return count;
+    }
+
+    /**
+     * Returns a string identifying this CompletableFuture, as well as
+     * its completion state.  The state, in brackets, contains the
+     * String {@code "Completed Normally"} or the String {@code
+     * "Completed Exceptionally"}, or the String {@code "Not
+     * completed"} followed by the number of CompletableFutures
+     * dependent upon its completion, if any.
+     *
+     * @return a string identifying this CompletableFuture, as well as its state
+     */
+    public String toString() {
+        Object r = result;
+        int count;
+        return super.toString() +
+            ((r == null) ?
+             (((count = getNumberOfDependents()) == 0) ?
+              "[Not completed]" :
+              "[Not completed, " + count + " dependents]") :
+             (((r instanceof AltResult) && ((AltResult)r).ex != null) ?
+              "[Completed exceptionally]" :
+              "[Completed normally]"));
+    }
+
+    // Unsafe mechanics
+    private static final sun.misc.Unsafe UNSAFE;
+    private static final long RESULT;
+    private static final long WAITERS;
+    private static final long COMPLETIONS;
+    static {
+        try {
+            UNSAFE = sun.misc.Unsafe.getUnsafe();
+            Class<?> k = CompletableFuture.class;
+            RESULT = UNSAFE.objectFieldOffset
+                (k.getDeclaredField("result"));
+            WAITERS = UNSAFE.objectFieldOffset
+                (k.getDeclaredField("waiters"));
+            COMPLETIONS = UNSAFE.objectFieldOffset
+                (k.getDeclaredField("completions"));
+        } catch (Exception e) {
+            throw new Error(e);
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/classes/java/util/concurrent/CompletionException.java	Wed Feb 20 15:42:21 2013 -0800
@@ -0,0 +1,90 @@
+/*
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * This file is available under and governed by the GNU General Public
+ * License version 2 only, as published by the Free Software Foundation.
+ * However, the following notice accompanied the original version of this
+ * file:
+ *
+ * Written by Doug Lea with assistance from members of JCP JSR-166
+ * Expert Group and released to the public domain, as explained at
+ * http://creativecommons.org/publicdomain/zero/1.0/
+ */
+
+package java.util.concurrent;
+
+/**
+ * Exception thrown when an error or other exception is encountered
+ * in the course of completing a result or task.
+ *
+ * @since 1.8
+ * @author Doug Lea
+ */
+public class CompletionException extends RuntimeException {
+    private static final long serialVersionUID = 7830266012832686185L;
+
+    /**
+     * Constructs a {@code CompletionException} with no detail message.
+     * The cause is not initialized, and may subsequently be
+     * initialized by a call to {@link #initCause(Throwable) initCause}.
+     */
+    protected CompletionException() { }
+
+    /**
+     * Constructs a {@code CompletionException} with the specified detail
+     * message. The cause is not initialized, and may subsequently be
+     * initialized by a call to {@link #initCause(Throwable) initCause}.
+     *
+     * @param message the detail message
+     */
+    protected CompletionException(String message) {
+        super(message);
+    }
+
+    /**
+     * Constructs a {@code CompletionException} with the specified detail
+     * message and cause.
+     *
+     * @param  message the detail message
+     * @param  cause the cause (which is saved for later retrieval by the
+     *         {@link #getCause()} method)
+     */
+    public CompletionException(String message, Throwable cause) {
+        super(message, cause);
+    }
+
+    /**
+     * Constructs a {@code CompletionException} with the specified cause.
+     * The detail message is set to {@code (cause == null ? null :
+     * cause.toString())} (which typically contains the class and
+     * detail message of {@code cause}).
+     *
+     * @param  cause the cause (which is saved for later retrieval by the
+     *         {@link #getCause()} method)
+     */
+    public CompletionException(Throwable cause) {
+        super(cause);
+    }
+}
--- a/src/share/classes/java/util/concurrent/CompletionService.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/CompletionService.java	Wed Feb 20 15:42:21 2013 -0800
@@ -38,17 +38,17 @@
 /**
  * A service that decouples the production of new asynchronous tasks
  * from the consumption of the results of completed tasks.  Producers
- * <tt>submit</tt> tasks for execution. Consumers <tt>take</tt>
+ * {@code submit} tasks for execution. Consumers {@code take}
  * completed tasks and process their results in the order they
- * complete.  A <tt>CompletionService</tt> can for example be used to
- * manage asynchronous IO, in which tasks that perform reads are
+ * complete.  A {@code CompletionService} can for example be used to
+ * manage asynchronous I/O, in which tasks that perform reads are
  * submitted in one part of a program or system, and then acted upon
  * in a different part of the program when the reads complete,
  * possibly in a different order than they were requested.
  *
- * <p>Typically, a <tt>CompletionService</tt> relies on a separate
+ * <p>Typically, a {@code CompletionService} relies on a separate
  * {@link Executor} to actually execute the tasks, in which case the
- * <tt>CompletionService</tt> only manages an internal completion
+ * {@code CompletionService} only manages an internal completion
  * queue. The {@link ExecutorCompletionService} class provides an
  * implementation of this approach.
  *
@@ -80,7 +80,7 @@
      * @param task the task to submit
      * @param result the result to return upon successful completion
      * @return a Future representing pending completion of the task,
-     *         and whose <tt>get()</tt> method will return the given
+     *         and whose {@code get()} method will return the given
      *         result value upon completion
      * @throws RejectedExecutionException if the task cannot be
      *         scheduled for execution
@@ -99,10 +99,10 @@
 
     /**
      * Retrieves and removes the Future representing the next
-     * completed task or <tt>null</tt> if none are present.
+     * completed task, or {@code null} if none are present.
      *
      * @return the Future representing the next completed task, or
-     *         <tt>null</tt> if none are present
+     *         {@code null} if none are present
      */
     Future<V> poll();
 
@@ -112,11 +112,11 @@
      * time if none are yet present.
      *
      * @param timeout how long to wait before giving up, in units of
-     *        <tt>unit</tt>
-     * @param unit a <tt>TimeUnit</tt> determining how to interpret the
-     *        <tt>timeout</tt> parameter
+     *        {@code unit}
+     * @param unit a {@code TimeUnit} determining how to interpret the
+     *        {@code timeout} parameter
      * @return the Future representing the next completed task or
-     *         <tt>null</tt> if the specified waiting time elapses
+     *         {@code null} if the specified waiting time elapses
      *         before one is present
      * @throws InterruptedException if interrupted while waiting
      */
--- a/src/share/classes/java/util/concurrent/ConcurrentLinkedDeque.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/ConcurrentLinkedDeque.java	Wed Feb 20 15:42:21 2013 -0800
@@ -46,6 +46,7 @@
 import java.util.Spliterator;
 import java.util.stream.Stream;
 import java.util.stream.Streams;
+import java.util.function.Consumer;
 
 /**
  * An unbounded concurrent {@linkplain Deque deque} based on linked nodes.
--- a/src/share/classes/java/util/concurrent/ConcurrentLinkedQueue.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/ConcurrentLinkedQueue.java	Wed Feb 20 15:42:21 2013 -0800
@@ -36,6 +36,7 @@
 package java.util.concurrent;
 
 import java.util.AbstractQueue;
+import java.util.Arrays;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
--- a/src/share/classes/java/util/concurrent/ConcurrentMap.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/ConcurrentMap.java	Wed Feb 20 15:42:21 2013 -0800
@@ -38,7 +38,7 @@
 
 /**
  * A {@link java.util.Map} providing additional atomic
- * <tt>putIfAbsent</tt>, <tt>remove</tt>, and <tt>replace</tt> methods.
+ * {@code putIfAbsent}, {@code remove}, and {@code replace} methods.
  *
  * <p>Memory consistency effects: As with other concurrent
  * collections, actions in a thread prior to placing an object into a
@@ -72,11 +72,11 @@
      * @param key key with which the specified value is to be associated
      * @param value value to be associated with the specified key
      * @return the previous value associated with the specified key, or
-     *         <tt>null</tt> if there was no mapping for the key.
-     *         (A <tt>null</tt> return can also indicate that the map
-     *         previously associated <tt>null</tt> with the key,
+     *         {@code null} if there was no mapping for the key.
+     *         (A {@code null} return can also indicate that the map
+     *         previously associated {@code null} with the key,
      *         if the implementation supports null values.)
-     * @throws UnsupportedOperationException if the <tt>put</tt> operation
+     * @throws UnsupportedOperationException if the {@code put} operation
      *         is not supported by this map
      * @throws ClassCastException if the class of the specified key or value
      *         prevents it from being stored in this map
@@ -101,8 +101,8 @@
      *
      * @param key key with which the specified value is associated
      * @param value value expected to be associated with the specified key
-     * @return <tt>true</tt> if the value was removed
-     * @throws UnsupportedOperationException if the <tt>remove</tt> operation
+     * @return {@code true} if the value was removed
+     * @throws UnsupportedOperationException if the {@code remove} operation
      *         is not supported by this map
      * @throws ClassCastException if the key or value is of an inappropriate
      *         type for this map
@@ -128,8 +128,8 @@
      * @param key key with which the specified value is associated
      * @param oldValue value expected to be associated with the specified key
      * @param newValue value to be associated with the specified key
-     * @return <tt>true</tt> if the value was replaced
-     * @throws UnsupportedOperationException if the <tt>put</tt> operation
+     * @return {@code true} if the value was replaced
+     * @throws UnsupportedOperationException if the {@code put} operation
      *         is not supported by this map
      * @throws ClassCastException if the class of a specified key or value
      *         prevents it from being stored in this map
@@ -154,11 +154,11 @@
      * @param key key with which the specified value is associated
      * @param value value to be associated with the specified key
      * @return the previous value associated with the specified key, or
-     *         <tt>null</tt> if there was no mapping for the key.
-     *         (A <tt>null</tt> return can also indicate that the map
-     *         previously associated <tt>null</tt> with the key,
+     *         {@code null} if there was no mapping for the key.
+     *         (A {@code null} return can also indicate that the map
+     *         previously associated {@code null} with the key,
      *         if the implementation supports null values.)
-     * @throws UnsupportedOperationException if the <tt>put</tt> operation
+     * @throws UnsupportedOperationException if the {@code put} operation
      *         is not supported by this map
      * @throws ClassCastException if the class of the specified key or value
      *         prevents it from being stored in this map
--- a/src/share/classes/java/util/concurrent/ConcurrentSkipListSet.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/ConcurrentSkipListSet.java	Wed Feb 20 15:42:21 2013 -0800
@@ -40,6 +40,7 @@
 import java.util.Comparator;
 import java.util.Iterator;
 import java.util.Map;
+import java.util.NavigableMap;
 import java.util.NavigableSet;
 import java.util.Set;
 import java.util.SortedSet;
--- a/src/share/classes/java/util/concurrent/CountedCompleter.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/CountedCompleter.java	Wed Feb 20 15:42:21 2013 -0800
@@ -44,7 +44,8 @@
  * CountedCompleter are similar to those of other completion based
  * components (such as {@link java.nio.channels.CompletionHandler})
  * except that multiple <em>pending</em> completions may be necessary
- * to trigger the completion action {@link #onCompletion}, not just one.
+ * to trigger the completion action {@link #onCompletion(CountedCompleter)},
+ * not just one.
  * Unless initialized otherwise, the {@linkplain #getPendingCount pending
  * count} starts at zero, but may be (atomically) changed using
  * methods {@link #setPendingCount}, {@link #addToPendingCount}, and
@@ -69,9 +70,10 @@
  * <p>A concrete CountedCompleter class must define method {@link
  * #compute}, that should in most cases (as illustrated below), invoke
  * {@code tryComplete()} once before returning. The class may also
- * optionally override method {@link #onCompletion} to perform an
- * action upon normal completion, and method {@link
- * #onExceptionalCompletion} to perform an action upon any exception.
+ * optionally override method {@link #onCompletion(CountedCompleter)}
+ * to perform an action upon normal completion, and method
+ * {@link #onExceptionalCompletion(Throwable, CountedCompleter)} to
+ * perform an action upon any exception.
  *
  * <p>CountedCompleters most often do not bear results, in which case
  * they are normally declared as {@code CountedCompleter<Void>}, and
@@ -92,13 +94,14 @@
  * only as an internal helper for other computations, so its own task
  * status (as reported in methods such as {@link ForkJoinTask#isDone})
  * is arbitrary; this status changes only upon explicit invocations of
- * {@link #complete}, {@link ForkJoinTask#cancel}, {@link
- * ForkJoinTask#completeExceptionally} or upon exceptional completion
- * of method {@code compute}. Upon any exceptional completion, the
- * exception may be relayed to a task's completer (and its completer,
- * and so on), if one exists and it has not otherwise already
- * completed. Similarly, cancelling an internal CountedCompleter has
- * only a local effect on that completer, so is not often useful.
+ * {@link #complete}, {@link ForkJoinTask#cancel},
+ * {@link ForkJoinTask#completeExceptionally(Throwable)} or upon
+ * exceptional completion of method {@code compute}. Upon any
+ * exceptional completion, the exception may be relayed to a task's
+ * completer (and its completer, and so on), if one exists and it has
+ * not otherwise already completed. Similarly, cancelling an internal
+ * CountedCompleter has only a local effect on that completer, so is
+ * not often useful.
  *
  * <p><b>Sample Usages.</b>
  *
@@ -181,12 +184,11 @@
  *   }
  * }</pre>
  *
- * As a further improvement, notice that the left task need not even
- * exist.  Instead of creating a new one, we can iterate using the
- * original task, and add a pending count for each fork. Additionally,
- * because no task in this tree implements an {@link #onCompletion}
- * method, {@code tryComplete()} can be replaced with {@link
- * #propagateCompletion}.
+ * As a further improvement, notice that the left task need not even exist.
+ * Instead of creating a new one, we can iterate using the original task,
+ * and add a pending count for each fork.  Additionally, because no task
+ * in this tree implements an {@link #onCompletion(CountedCompleter)} method,
+ * {@code tryComplete()} can be replaced with {@link #propagateCompletion}.
  *
  * <pre> {@code
  * class ForEach<E> ...
@@ -264,7 +266,7 @@
  *
  * <p><b>Recording subtasks.</b> CountedCompleter tasks that combine
  * results of multiple subtasks usually need to access these results
- * in method {@link #onCompletion}. As illustrated in the following
+ * in method {@link #onCompletion(CountedCompleter)}. As illustrated in the following
  * class (that performs a simplified form of map-reduce where mappings
  * and reductions are all of type {@code E}), one way to do this in
  * divide and conquer designs is to have each subtask record its
@@ -365,7 +367,7 @@
  *     while (h - l >= 2) {
  *       int mid = (l + h) >>> 1;
  *       addToPendingCount(1);
- *       (forks = new MapReducer(this, array, mapper, reducer, mid, h, forks)).fork;
+ *       (forks = new MapReducer(this, array, mapper, reducer, mid, h, forks)).fork();
  *       h = mid;
  *     }
  *     if (h > l)
@@ -460,13 +462,13 @@
      * (and/or links to other results) to combine.
      *
      * @param caller the task invoking this method (which may
-     * be this task itself).
+     * be this task itself)
      */
     public void onCompletion(CountedCompleter<?> caller) {
     }
 
     /**
-     * Performs an action when method {@link #completeExceptionally}
+     * Performs an action when method {@link #completeExceptionally(Throwable)}
      * is invoked or method {@link #compute} throws an exception, and
      * this task has not otherwise already completed normally. On
      * entry to this method, this task {@link
@@ -478,9 +480,9 @@
      *
      * @param ex the exception
      * @param caller the task invoking this method (which may
-     * be this task itself).
+     * be this task itself)
      * @return true if this exception should be propagated to this
-     * task's completer, if one exists.
+     * task's completer, if one exists
      */
     public boolean onExceptionalCompletion(Throwable ex, CountedCompleter<?> caller) {
         return true;
@@ -564,9 +566,9 @@
 
     /**
      * If the pending count is nonzero, decrements the count;
-     * otherwise invokes {@link #onCompletion} and then similarly
-     * tries to complete this task's completer, if one exists,
-     * else marks this task as complete.
+     * otherwise invokes {@link #onCompletion(CountedCompleter)}
+     * and then similarly tries to complete this task's completer,
+     * if one exists, else marks this task as complete.
      */
     public final void tryComplete() {
         CountedCompleter<?> a = this, s = a;
@@ -585,12 +587,12 @@
 
     /**
      * Equivalent to {@link #tryComplete} but does not invoke {@link
-     * #onCompletion} along the completion path: If the pending count
-     * is nonzero, decrements the count; otherwise, similarly tries to
-     * complete this task's completer, if one exists, else marks this
-     * task as complete. This method may be useful in cases where
-     * {@code onCompletion} should not, or need not, be invoked for
-     * each completer in a computation.
+     * #onCompletion(CountedCompleter)} along the completion path:
+     * If the pending count is nonzero, decrements the count;
+     * otherwise, similarly tries to complete this task's completer, if
+     * one exists, else marks this task as complete. This method may be
+     * useful in cases where {@code onCompletion} should not, or need
+     * not, be invoked for each completer in a computation.
      */
     public final void propagateCompletion() {
         CountedCompleter<?> a = this, s = a;
@@ -607,13 +609,14 @@
     }
 
     /**
-     * Regardless of pending count, invokes {@link #onCompletion},
-     * marks this task as complete and further triggers {@link
-     * #tryComplete} on this task's completer, if one exists.  The
-     * given rawResult is used as an argument to {@link #setRawResult}
-     * before invoking {@link #onCompletion} or marking this task as
-     * complete; its value is meaningful only for classes overriding
-     * {@code setRawResult}.
+     * Regardless of pending count, invokes
+     * {@link #onCompletion(CountedCompleter)}, marks this task as
+     * complete and further triggers {@link #tryComplete} on this
+     * task's completer, if one exists.  The given rawResult is
+     * used as an argument to {@link #setRawResult} before invoking
+     * {@link #onCompletion(CountedCompleter)} or marking this task
+     * as complete; its value is meaningful only for classes
+     * overriding {@code setRawResult}.
      *
      * <p>This method may be useful when forcing completion as soon as
      * any one (versus all) of several subtask results are obtained.
@@ -653,8 +656,8 @@
     /**
      * If this task does not have a completer, invokes {@link
      * ForkJoinTask#quietlyComplete} and returns {@code null}.  Or, if
-     * this task's pending count is non-zero, decrements its pending
-     * count and returns {@code null}.  Otherwise, returns the
+     * the completer's pending count is non-zero, decrements that
+     * pending count and returns {@code null}.  Otherwise, returns the
      * completer.  This method can be used as part of a completion
      * traversal loop for homogeneous task hierarchies:
      *
--- a/src/share/classes/java/util/concurrent/CyclicBarrier.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/CyclicBarrier.java	Wed Feb 20 15:42:21 2013 -0800
@@ -45,14 +45,14 @@
  * <em>cyclic</em> because it can be re-used after the waiting threads
  * are released.
  *
- * <p>A <tt>CyclicBarrier</tt> supports an optional {@link Runnable} command
+ * <p>A {@code CyclicBarrier} supports an optional {@link Runnable} command
  * that is run once per barrier point, after the last thread in the party
  * arrives, but before any threads are released.
  * This <em>barrier action</em> is useful
  * for updating shared-state before any of the parties continue.
  *
- * <p><b>Sample usage:</b> Here is an example of
- *  using a barrier in a parallel decomposition design:
+ * <p><b>Sample usage:</b> Here is an example of using a barrier in a
+ * parallel decomposition design:
  *
  *  <pre> {@code
  * class Solver {
@@ -81,16 +81,20 @@
  *   public Solver(float[][] matrix) {
  *     data = matrix;
  *     N = matrix.length;
- *     barrier = new CyclicBarrier(N,
- *                                 new Runnable() {
- *                                   public void run() {
- *                                     mergeRows(...);
+ *     Runnable barrierAction =
+ *       new Runnable() { public void run() { mergeRows(...); }};
+ *     barrier = new CyclicBarrier(N, barrierAction);
+ *
+ *     List<Thread> threads = new ArrayList<Thread>(N);
+ *     for (int i = 0; i < N; i++) {
+ *       Thread thread = new Thread(new Worker(i));
+ *       threads.add(thread);
+ *       thread.start();
  *                                   }
- *                                 });
- *     for (int i = 0; i < N; ++i)
- *       new Thread(new Worker(i)).start();
  *
- *     waitUntilDone();
+ *     // wait until done
+ *     for (Thread thread : threads)
+ *       thread.join();
  *   }
  * }}</pre>
  *
@@ -98,8 +102,8 @@
  * barrier until all rows have been processed. When all rows are processed
  * the supplied {@link Runnable} barrier action is executed and merges the
  * rows. If the merger
- * determines that a solution has been found then <tt>done()</tt> will return
- * <tt>true</tt> and each worker will terminate.
+ * determines that a solution has been found then {@code done()} will return
+ * {@code true} and each worker will terminate.
  *
  * <p>If the barrier action does not rely on the parties being suspended when
  * it is executed, then any of the threads in the party could execute that
@@ -112,7 +116,7 @@
  *   // log the completion of this iteration
  * }}</pre>
  *
- * <p>The <tt>CyclicBarrier</tt> uses an all-or-none breakage model
+ * <p>The {@code CyclicBarrier} uses an all-or-none breakage model
  * for failed synchronization attempts: If a thread leaves a barrier
  * point prematurely because of interruption, failure, or timeout, all
  * other threads waiting at that barrier point will also leave
@@ -139,7 +143,7 @@
      * is reset. There can be many generations associated with threads
      * using the barrier - due to the non-deterministic way the lock
      * may be allocated to waiting threads - but only one of these
-     * can be active at a time (the one to which <tt>count</tt> applies)
+     * can be active at a time (the one to which {@code count} applies)
      * and all the rest are either broken or tripped.
      * There need not be an active generation if there has been a break
      * but no subsequent reset.
@@ -259,7 +263,7 @@
     }
 
     /**
-     * Creates a new <tt>CyclicBarrier</tt> that will trip when the
+     * Creates a new {@code CyclicBarrier} that will trip when the
      * given number of parties (threads) are waiting upon it, and which
      * will execute the given barrier action when the barrier is tripped,
      * performed by the last thread entering the barrier.
@@ -278,7 +282,7 @@
     }
 
     /**
-     * Creates a new <tt>CyclicBarrier</tt> that will trip when the
+     * Creates a new {@code CyclicBarrier} that will trip when the
      * given number of parties (threads) are waiting upon it, and
      * does not perform a predefined action when the barrier is tripped.
      *
@@ -301,7 +305,7 @@
 
     /**
      * Waits until all {@linkplain #getParties parties} have invoked
-     * <tt>await</tt> on this barrier.
+     * {@code await} on this barrier.
      *
      * <p>If the current thread is not the last to arrive then it is
      * disabled for thread scheduling purposes and lies dormant until
@@ -326,7 +330,7 @@
      *
      * <p>If the barrier is {@link #reset} while any thread is waiting,
      * or if the barrier {@linkplain #isBroken is broken} when
-     * <tt>await</tt> is invoked, or while any thread is waiting, then
+     * {@code await} is invoked, or while any thread is waiting, then
      * {@link BrokenBarrierException} is thrown.
      *
      * <p>If any thread is {@linkplain Thread#interrupt interrupted} while waiting,
@@ -351,7 +355,7 @@
      *         interrupted or timed out while the current thread was
      *         waiting, or the barrier was reset, or the barrier was
      *         broken when {@code await} was called, or the barrier
-     *         action (if present) failed due an exception.
+     *         action (if present) failed due to an exception
      */
     public int await() throws InterruptedException, BrokenBarrierException {
         try {
@@ -363,7 +367,7 @@
 
     /**
      * Waits until all {@linkplain #getParties parties} have invoked
-     * <tt>await</tt> on this barrier, or the specified waiting time elapses.
+     * {@code await} on this barrier, or the specified waiting time elapses.
      *
      * <p>If the current thread is not the last to arrive then it is
      * disabled for thread scheduling purposes and lies dormant until
@@ -393,7 +397,7 @@
      *
      * <p>If the barrier is {@link #reset} while any thread is waiting,
      * or if the barrier {@linkplain #isBroken is broken} when
-     * <tt>await</tt> is invoked, or while any thread is waiting, then
+     * {@code await} is invoked, or while any thread is waiting, then
      * {@link BrokenBarrierException} is thrown.
      *
      * <p>If any thread is {@linkplain Thread#interrupt interrupted} while
@@ -421,7 +425,7 @@
      *         interrupted or timed out while the current thread was
      *         waiting, or the barrier was reset, or the barrier was broken
      *         when {@code await} was called, or the barrier action (if
-     *         present) failed due an exception
+     *         present) failed due to an exception
      */
     public int await(long timeout, TimeUnit unit)
         throws InterruptedException,
--- a/src/share/classes/java/util/concurrent/DelayQueue.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/DelayQueue.java	Wed Feb 20 15:42:21 2013 -0800
@@ -33,28 +33,31 @@
  * http://creativecommons.org/publicdomain/zero/1.0/
  */
 
-
 package java.util.concurrent;
-import java.util.concurrent.locks.*;
+import static java.util.concurrent.TimeUnit.NANOSECONDS;
+import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.ReentrantLock;
 import java.util.*;
 
 /**
  * An unbounded {@linkplain BlockingQueue blocking queue} of
- * <tt>Delayed</tt> elements, in which an element can only be taken
+ * {@code Delayed} elements, in which an element can only be taken
  * when its delay has expired.  The <em>head</em> of the queue is that
- * <tt>Delayed</tt> element whose delay expired furthest in the
- * past.  If no delay has expired there is no head and <tt>poll</tt>
- * will return <tt>null</tt>. Expiration occurs when an element's
- * <tt>getDelay(TimeUnit.NANOSECONDS)</tt> method returns a value less
+ * {@code Delayed} element whose delay expired furthest in the
+ * past.  If no delay has expired there is no head and {@code poll}
+ * will return {@code null}. Expiration occurs when an element's
+ * {@code getDelay(TimeUnit.NANOSECONDS)} method returns a value less
  * than or equal to zero.  Even though unexpired elements cannot be
- * removed using <tt>take</tt> or <tt>poll</tt>, they are otherwise
- * treated as normal elements. For example, the <tt>size</tt> method
+ * removed using {@code take} or {@code poll}, they are otherwise
+ * treated as normal elements. For example, the {@code size} method
  * returns the count of both expired and unexpired elements.
  * This queue does not permit null elements.
  *
  * <p>This class and its iterator implement all of the
  * <em>optional</em> methods of the {@link Collection} and {@link
- * Iterator} interfaces.
+ * Iterator} interfaces.  The Iterator provided in method {@link
+ * #iterator()} is <em>not</em> guaranteed to traverse the elements of
+ * the DelayQueue in any particular order.
  *
  * <p>This class is a member of the
  * <a href="{@docRoot}/../technotes/guides/collections/index.html">
@@ -64,11 +67,10 @@
  * @author Doug Lea
  * @param <E> the type of elements held in this collection
  */
-
 public class DelayQueue<E extends Delayed> extends AbstractQueue<E>
     implements BlockingQueue<E> {
 
-    private transient final ReentrantLock lock = new ReentrantLock();
+    private final transient ReentrantLock lock = new ReentrantLock();
     private final PriorityQueue<E> q = new PriorityQueue<E>();
 
     /**
@@ -97,12 +99,12 @@
     private final Condition available = lock.newCondition();
 
     /**
-     * Creates a new <tt>DelayQueue</tt> that is initially empty.
+     * Creates a new {@code DelayQueue} that is initially empty.
      */
     public DelayQueue() {}
 
     /**
-     * Creates a <tt>DelayQueue</tt> initially containing the elements of the
+     * Creates a {@code DelayQueue} initially containing the elements of the
      * given collection of {@link Delayed} instances.
      *
      * @param c the collection of elements to initially contain
@@ -117,7 +119,7 @@
      * Inserts the specified element into this delay queue.
      *
      * @param e the element to add
-     * @return <tt>true</tt> (as specified by {@link Collection#add})
+     * @return {@code true} (as specified by {@link Collection#add})
      * @throws NullPointerException if the specified element is null
      */
     public boolean add(E e) {
@@ -128,7 +130,7 @@
      * Inserts the specified element into this delay queue.
      *
      * @param e the element to add
-     * @return <tt>true</tt>
+     * @return {@code true}
      * @throws NullPointerException if the specified element is null
      */
     public boolean offer(E e) {
@@ -164,7 +166,7 @@
      * @param e the element to add
      * @param timeout This parameter is ignored as the method never blocks
      * @param unit This parameter is ignored as the method never blocks
-     * @return <tt>true</tt>
+     * @return {@code true}
      * @throws NullPointerException {@inheritDoc}
      */
     public boolean offer(E e, long timeout, TimeUnit unit) {
@@ -172,10 +174,10 @@
     }
 
     /**
-     * Retrieves and removes the head of this queue, or returns <tt>null</tt>
+     * Retrieves and removes the head of this queue, or returns {@code null}
      * if this queue has no elements with an expired delay.
      *
-     * @return the head of this queue, or <tt>null</tt> if this
+     * @return the head of this queue, or {@code null} if this
      *         queue has no elements with an expired delay
      */
     public E poll() {
@@ -183,7 +185,7 @@
         lock.lock();
         try {
             E first = q.peek();
-            if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0)
+            if (first == null || first.getDelay(NANOSECONDS) > 0)
                 return null;
             else
                 return q.poll();
@@ -208,7 +210,7 @@
                 if (first == null)
                     available.await();
                 else {
-                    long delay = first.getDelay(TimeUnit.NANOSECONDS);
+                    long delay = first.getDelay(NANOSECONDS);
                     if (delay <= 0)
                         return q.poll();
                     else if (leader != null)
@@ -237,7 +239,7 @@
      * until an element with an expired delay is available on this queue,
      * or the specified wait time expires.
      *
-     * @return the head of this queue, or <tt>null</tt> if the
+     * @return the head of this queue, or {@code null} if the
      *         specified waiting time elapses before an element with
      *         an expired delay becomes available
      * @throws InterruptedException {@inheritDoc}
@@ -255,7 +257,7 @@
                     else
                         nanos = available.awaitNanos(nanos);
                 } else {
-                    long delay = first.getDelay(TimeUnit.NANOSECONDS);
+                    long delay = first.getDelay(NANOSECONDS);
                     if (delay <= 0)
                         return q.poll();
                     if (nanos <= 0)
@@ -284,13 +286,13 @@
 
     /**
      * Retrieves, but does not remove, the head of this queue, or
-     * returns <tt>null</tt> if this queue is empty.  Unlike
-     * <tt>poll</tt>, if no expired elements are available in the queue,
+     * returns {@code null} if this queue is empty.  Unlike
+     * {@code poll}, if no expired elements are available in the queue,
      * this method returns the element that will expire next,
      * if one exists.
      *
-     * @return the head of this queue, or <tt>null</tt> if this
-     *         queue is empty.
+     * @return the head of this queue, or {@code null} if this
+     *         queue is empty
      */
     public E peek() {
         final ReentrantLock lock = this.lock;
@@ -313,6 +315,17 @@
     }
 
     /**
+     * Returns first element only if it is expired.
+     * Used only by drainTo.  Call only when holding lock.
+     */
+    private E peekExpired() {
+        // assert lock.isHeldByCurrentThread();
+        E first = q.peek();
+        return (first == null || first.getDelay(NANOSECONDS) > 0) ?
+            null : first;
+    }
+
+    /**
      * @throws UnsupportedOperationException {@inheritDoc}
      * @throws ClassCastException            {@inheritDoc}
      * @throws NullPointerException          {@inheritDoc}
@@ -327,11 +340,9 @@
         lock.lock();
         try {
             int n = 0;
-            for (;;) {
-                E first = q.peek();
-                if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0)
-                    break;
-                c.add(q.poll());
+            for (E e; (e = peekExpired()) != null;) {
+                c.add(e);       // In this order, in case add() throws.
+                q.poll();
                 ++n;
             }
             return n;
@@ -357,11 +368,9 @@
         lock.lock();
         try {
             int n = 0;
-            while (n < maxElements) {
-                E first = q.peek();
-                if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0)
-                    break;
-                c.add(q.poll());
+            for (E e; n < maxElements && (e = peekExpired()) != null;) {
+                c.add(e);       // In this order, in case add() throws.
+                q.poll();
                 ++n;
             }
             return n;
@@ -387,10 +396,10 @@
     }
 
     /**
-     * Always returns <tt>Integer.MAX_VALUE</tt> because
-     * a <tt>DelayQueue</tt> is not capacity constrained.
+     * Always returns {@code Integer.MAX_VALUE} because
+     * a {@code DelayQueue} is not capacity constrained.
      *
-     * @return <tt>Integer.MAX_VALUE</tt>
+     * @return {@code Integer.MAX_VALUE}
      */
     public int remainingCapacity() {
         return Integer.MAX_VALUE;
@@ -430,7 +439,7 @@
      * <p>If this queue fits in the specified array with room to spare
      * (i.e., the array has more elements than this queue), the element in
      * the array immediately following the end of the queue is set to
-     * <tt>null</tt>.
+     * {@code null}.
      *
      * <p>Like the {@link #toArray()} method, this method acts as bridge between
      * array-based and collection-based APIs.  Further, this method allows
@@ -438,13 +447,12 @@
      * under certain circumstances, be used to save allocation costs.
      *
      * <p>The following code can be used to dump a delay queue into a newly
-     * allocated array of <tt>Delayed</tt>:
+     * allocated array of {@code Delayed}:
      *
-     * <pre>
-     *     Delayed[] a = q.toArray(new Delayed[0]);</pre>
+     * <pre> {@code Delayed[] a = q.toArray(new Delayed[0]);}</pre>
      *
-     * Note that <tt>toArray(new Object[0])</tt> is identical in function to
-     * <tt>toArray()</tt>.
+     * Note that {@code toArray(new Object[0])} is identical in function to
+     * {@code toArray()}.
      *
      * @param a the array into which the elements of the queue are to
      *          be stored, if it is big enough; otherwise, a new array of the
@@ -480,6 +488,24 @@
     }
 
     /**
+     * Identity-based version for use in Itr.remove
+     */
+    void removeEQ(Object o) {
+        final ReentrantLock lock = this.lock;
+        lock.lock();
+        try {
+            for (Iterator<E> it = q.iterator(); it.hasNext(); ) {
+                if (o == it.next()) {
+                    it.remove();
+                    break;
+                }
+            }
+        } finally {
+            lock.unlock();
+        }
+    }
+
+    /**
      * Returns an iterator over all the elements (both expired and
      * unexpired) in this queue. The iterator does not return the
      * elements in any particular order.
@@ -502,7 +528,7 @@
      */
     private class Itr implements Iterator<E> {
         final Object[] array; // Array of all elements
-        int cursor;           // index of next element to return;
+        int cursor;           // index of next element to return
         int lastRet;          // index of last element, or -1 if no such
 
         Itr(Object[] array) {
@@ -525,21 +551,8 @@
         public void remove() {
             if (lastRet < 0)
                 throw new IllegalStateException();
-            Object x = array[lastRet];
+            removeEQ(array[lastRet]);
             lastRet = -1;
-            // Traverse underlying queue to find == element,
-            // not just a .equals element.
-            lock.lock();
-            try {
-                for (Iterator<E> it = q.iterator(); it.hasNext(); ) {
-                    if (it.next() == x) {
-                        it.remove();
-                        return;
-                    }
-                }
-            } finally {
-                lock.unlock();
-            }
         }
     }
 
--- a/src/share/classes/java/util/concurrent/Delayed.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/Delayed.java	Wed Feb 20 15:42:21 2013 -0800
@@ -40,8 +40,8 @@
  * acted upon after a given delay.
  *
  * <p>An implementation of this interface must define a
- * <tt>compareTo</tt> method that provides an ordering consistent with
- * its <tt>getDelay</tt> method.
+ * {@code compareTo} method that provides an ordering consistent with
+ * its {@code getDelay} method.
  *
  * @since 1.5
  * @author Doug Lea
--- a/src/share/classes/java/util/concurrent/DoubleAdder.java	Wed Feb 20 17:20:17 2013 -0500
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,201 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-package java.util.concurrent;
-import java.io.IOException;
-import java.io.Serializable;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-
-/**
- * One or more variables that together maintain an initially zero
- * {@code double} sum.  When updates (method {@link #add}) are
- * contended across threads, the set of variables may grow dynamically
- * to reduce contention.  Method {@link #sum} (or, equivalently {@link
- * #doubleValue}) returns the current total combined across the
- * variables maintaining the sum.
- *
- * <p>This class extends {@link Number}, but does <em>not</em> define
- * methods such as {@code hashCode} and {@code compareTo} because
- * instances are expected to be mutated, and so are not useful as
- * collection keys.
- *
- * <p><em>jsr166e note: This class is targeted to be placed in
- * java.util.concurrent.atomic<em>
- *
- * @since 1.8
- * @author Doug Lea
- */
-public class DoubleAdder extends Striped64 implements Serializable {
-    private static final long serialVersionUID = 7249069246863182397L;
-
-    /**
-     * Update function. Note that we must use "long" for underlying
-     * representations, because there is no compareAndSet for double,
-     * due to the fact that the bitwise equals used in any CAS
-     * implementation is not the same as double-precision equals.
-     * However, we use CAS only to detect and alleviate contention,
-     * for which bitwise equals works best anyway. In principle, the
-     * long/double conversions used here should be essentially free on
-     * most platforms since they just re-interpret bits.
-     *
-     * Similar conversions are used in other methods.
-     */
-    final long fn(long v, long x) {
-        return Double.doubleToRawLongBits
-            (Double.longBitsToDouble(v) +
-             Double.longBitsToDouble(x));
-    }
-
-    /**
-     * Creates a new adder with initial sum of zero.
-     */
-    public DoubleAdder() {
-    }
-
-    /**
-     * Adds the given value.
-     *
-     * @param x the value to add
-     */
-    public void add(double x) {
-        Cell[] as; long b, v; HashCode hc; Cell a; int n;
-        if ((as = cells) != null ||
-            !casBase(b = base,
-                     Double.doubleToRawLongBits
-                     (Double.longBitsToDouble(b) + x))) {
-            boolean uncontended = true;
-            int h = (hc = threadHashCode.get()).code;
-            if (as == null || (n = as.length) < 1 ||
-                (a = as[(n - 1) & h]) == null ||
-                !(uncontended = a.cas(v = a.value,
-                                      Double.doubleToRawLongBits
-                                      (Double.longBitsToDouble(v) + x))))
-                retryUpdate(Double.doubleToRawLongBits(x), hc, uncontended);
-        }
-    }
-
-    /**
-     * Returns the current sum.  The returned value is <em>NOT</em> an
-     * atomic snapshot: Invocation in the absence of concurrent
-     * updates returns an accurate result, but concurrent updates that
-     * occur while the sum is being calculated might not be
-     * incorporated.  Also, because double-precision arithmetic is not
-     * strictly associative, the returned result need not be identical
-     * to the value that would be obtained in a sequential series of
-     * updates to a single variable.
-     *
-     * @return the sum
-     */
-    public double sum() {
-        Cell[] as = cells;
-        double sum = Double.longBitsToDouble(base);
-        if (as != null) {
-            int n = as.length;
-            for (int i = 0; i < n; ++i) {
-                Cell a = as[i];
-                if (a != null)
-                    sum += Double.longBitsToDouble(a.value);
-            }
-        }
-        return sum;
-    }
-
-    /**
-     * Resets variables maintaining the sum to zero.  This method may
-     * be a useful alternative to creating a new adder, but is only
-     * effective if there are no concurrent updates.  Because this
-     * method is intrinsically racy, it should only be used when it is
-     * known that no threads are concurrently updating.
-     */
-    public void reset() {
-        internalReset(0L);
-    }
-
-    /**
-     * Equivalent in effect to {@link #sum} followed by {@link
-     * #reset}. This method may apply for example during quiescent
-     * points between multithreaded computations.  If there are
-     * updates concurrent with this method, the returned value is
-     * <em>not</em> guaranteed to be the final value occurring before
-     * the reset.
-     *
-     * @return the sum
-     */
-    public double sumThenReset() {
-        Cell[] as = cells;
-        double sum = Double.longBitsToDouble(base);
-        base = 0L;
-        if (as != null) {
-            int n = as.length;
-            for (int i = 0; i < n; ++i) {
-                Cell a = as[i];
-                if (a != null) {
-                    long v = a.value;
-                    a.value = 0L;
-                    sum += Double.longBitsToDouble(v);
-                }
-            }
-        }
-        return sum;
-    }
-
-    /**
-     * Returns the String representation of the {@link #sum}.
-     * @return the String representation of the {@link #sum}
-     */
-    public String toString() {
-        return Double.toString(sum());
-    }
-
-    /**
-     * Equivalent to {@link #sum}.
-     *
-     * @return the sum
-     */
-    public double doubleValue() {
-        return sum();
-    }
-
-    /**
-     * Returns the {@link #sum} as a {@code long} after a
-     * narrowing primitive conversion.
-     */
-    public long longValue() {
-        return (long)sum();
-    }
-
-    /**
-     * Returns the {@link #sum} as an {@code int} after a
-     * narrowing primitive conversion.
-     */
-    public int intValue() {
-        return (int)sum();
-    }
-
-    /**
-     * Returns the {@link #sum} as a {@code float}
-     * after a narrowing primitive conversion.
-     */
-    public float floatValue() {
-        return (float)sum();
-    }
-
-    private void writeObject(java.io.ObjectOutputStream s)
-        throws java.io.IOException {
-        s.defaultWriteObject();
-        s.writeDouble(sum());
-    }
-
-    private void readObject(ObjectInputStream s)
-        throws IOException, ClassNotFoundException {
-        s.defaultReadObject();
-        busy = 0;
-        cells = null;
-        base = Double.doubleToRawLongBits(s.readDouble());
-    }
-
-}
--- a/src/share/classes/java/util/concurrent/DoubleMaxUpdater.java	Wed Feb 20 17:20:17 2013 -0500
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,196 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-package java.util.concurrent;
-import java.io.IOException;
-import java.io.Serializable;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-
-/**
- * One or more variables that together maintain a running {@code double}
- * maximum with initial value {@code Double.NEGATIVE_INFINITY}.  When
- * updates (method {@link #update}) are contended across threads, the
- * set of variables may grow dynamically to reduce contention.  Method
- * {@link #max} (or, equivalently, {@link #doubleValue}) returns the
- * current maximum across the variables maintaining updates.
- *
- * <p>This class extends {@link Number}, but does <em>not</em> define
- * methods such as {@code hashCode} and {@code compareTo} because
- * instances are expected to be mutated, and so are not useful as
- * collection keys.
- *
- * <p><em>jsr166e note: This class is targeted to be placed in
- * java.util.concurrent.atomic<em>
- *
- * @since 1.8
- * @author Doug Lea
- */
-public class DoubleMaxUpdater extends Striped64 implements Serializable {
-    private static final long serialVersionUID = 7249069246863182397L;
-    /**
-     * Long representation of negative infinity. See class Double
-     * internal documentation for explanation.
-     */
-    private static final long MIN_AS_LONG = 0xfff0000000000000L;
-
-    /**
-     * Update function. See class DoubleAdder for rationale
-     * for using conversions from/to long.
-     */
-    final long fn(long v, long x) {
-        return Double.longBitsToDouble(v) > Double.longBitsToDouble(x) ? v : x;
-    }
-
-    /**
-     * Creates a new instance with initial value of {@code
-     * Double.NEGATIVE_INFINITY}.
-     */
-    public DoubleMaxUpdater() {
-        base = MIN_AS_LONG;
-    }
-
-    /**
-     * Updates the maximum to be at least the given value.
-     *
-     * @param x the value to update
-     */
-    public void update(double x) {
-        long lx = Double.doubleToRawLongBits(x);
-        Cell[] as; long b, v; HashCode hc; Cell a; int n;
-        if ((as = cells) != null ||
-            (Double.longBitsToDouble(b = base) < x && !casBase(b, lx))) {
-            boolean uncontended = true;
-            int h = (hc = threadHashCode.get()).code;
-            if (as == null || (n = as.length) < 1 ||
-                (a = as[(n - 1) & h]) == null ||
-                (Double.longBitsToDouble(v = a.value) < x &&
-                 !(uncontended = a.cas(v, lx))))
-                retryUpdate(lx, hc, uncontended);
-        }
-    }
-
-    /**
-     * Returns the current maximum.  The returned value is
-     * <em>NOT</em> an atomic snapshot: Invocation in the absence of
-     * concurrent updates returns an accurate result, but concurrent
-     * updates that occur while the value is being calculated might
-     * not be incorporated.
-     *
-     * @return the maximum
-     */
-    public double max() {
-        Cell[] as = cells;
-        double max = Double.longBitsToDouble(base);
-        if (as != null) {
-            int n = as.length;
-            double v;
-            for (int i = 0; i < n; ++i) {
-                Cell a = as[i];
-                if (a != null && (v = Double.longBitsToDouble(a.value)) > max)
-                    max = v;
-            }
-        }
-        return max;
-    }
-
-    /**
-     * Resets variables maintaining updates to {@code
-     * Double.NEGATIVE_INFINITY}.  This method may be a useful
-     * alternative to creating a new updater, but is only effective if
-     * there are no concurrent updates.  Because this method is
-     * intrinsically racy, it should only be used when it is known
-     * that no threads are concurrently updating.
-     */
-    public void reset() {
-        internalReset(MIN_AS_LONG);
-    }
-
-    /**
-     * Equivalent in effect to {@link #max} followed by {@link
-     * #reset}. This method may apply for example during quiescent
-     * points between multithreaded computations.  If there are
-     * updates concurrent with this method, the returned value is
-     * <em>not</em> guaranteed to be the final value occurring before
-     * the reset.
-     *
-     * @return the maximum
-     */
-    public double maxThenReset() {
-        Cell[] as = cells;
-        double max = Double.longBitsToDouble(base);
-        base = MIN_AS_LONG;
-        if (as != null) {
-            int n = as.length;
-            for (int i = 0; i < n; ++i) {
-                Cell a = as[i];
-                if (a != null) {
-                    double v = Double.longBitsToDouble(a.value);
-                    a.value = MIN_AS_LONG;
-                    if (v > max)
-                        max = v;
-                }
-            }
-        }
-        return max;
-    }
-
-    /**
-     * Returns the String representation of the {@link #max}.
-     * @return the String representation of the {@link #max}
-     */
-    public String toString() {
-        return Double.toString(max());
-    }
-
-    /**
-     * Equivalent to {@link #max}.
-     *
-     * @return the max
-     */
-    public double doubleValue() {
-        return max();
-    }
-
-    /**
-     * Returns the {@link #max} as a {@code long} after a
-     * narrowing primitive conversion.
-     */
-    public long longValue() {
-        return (long)max();
-    }
-
-    /**
-     * Returns the {@link #max} as an {@code int} after a
-     * narrowing primitive conversion.
-     */
-    public int intValue() {
-        return (int)max();
-    }
-
-    /**
-     * Returns the {@link #max} as a {@code float}
-     * after a narrowing primitive conversion.
-     */
-    public float floatValue() {
-        return (float)max();
-    }
-
-    private void writeObject(java.io.ObjectOutputStream s)
-        throws java.io.IOException {
-        s.defaultWriteObject();
-        s.writeDouble(max());
-    }
-
-    private void readObject(ObjectInputStream s)
-        throws IOException, ClassNotFoundException {
-        s.defaultReadObject();
-        busy = 0;
-        cells = null;
-        base = Double.doubleToRawLongBits(s.readDouble());
-    }
-
-}
--- a/src/share/classes/java/util/concurrent/Exchanger.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/Exchanger.java	Wed Feb 20 15:42:21 2013 -0800
@@ -35,7 +35,8 @@
  */
 
 package java.util.concurrent;
-import java.util.concurrent.atomic.*;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
 import java.util.concurrent.locks.LockSupport;
 
 /**
@@ -88,8 +89,7 @@
  *     new Thread(new FillingLoop()).start();
  *     new Thread(new EmptyingLoop()).start();
  *   }
- * }
- * }</pre>
+ * }}</pre>
  *
  * <p>Memory consistency effects: For each pair of threads that
  * successfully exchange objects via an {@code Exchanger}, actions
@@ -103,486 +103,427 @@
  * @param <V> The type of objects that may be exchanged
  */
 public class Exchanger<V> {
+
     /*
-     * Algorithm Description:
+     * Overview: The core algorithm is, for an exchange "slot",
+     * and a participant (caller) with an item:
      *
-     * The basic idea is to maintain a "slot", which is a reference to
-     * a Node containing both an Item to offer and a "hole" waiting to
-     * get filled in.  If an incoming "occupying" thread sees that the
-     * slot is null, it CAS'es (compareAndSets) a Node there and waits
-     * for another to invoke exchange.  That second "fulfilling" thread
-     * sees that the slot is non-null, and so CASes it back to null,
-     * also exchanging items by CASing the hole, plus waking up the
-     * occupying thread if it is blocked.  In each case CAS'es may
-     * fail because a slot at first appears non-null but is null upon
-     * CAS, or vice-versa.  So threads may need to retry these
-     * actions.
+     * for (;;) {
+     *   if (slot is empty) {                       // offer
+     *     place item in a Node;
+     *     if (can CAS slot from empty to node) {
+     *       wait for release;
+     *       return matching item in node;
+     *     }
+     *   }
+     *   else if (can CAS slot from node to empty) { // release
+     *     get the item in node;
+     *     set matching item in node;
+     *     release waiting thread;
+     *   }
+     *   // else retry on CAS failure
+     * }
      *
-     * This simple approach works great when there are only a few
-     * threads using an Exchanger, but performance rapidly
-     * deteriorates due to CAS contention on the single slot when
-     * there are lots of threads using an exchanger.  So instead we use
-     * an "arena"; basically a kind of hash table with a dynamically
-     * varying number of slots, any one of which can be used by
-     * threads performing an exchange.  Incoming threads pick slots
-     * based on a hash of their Thread ids.  If an incoming thread
-     * fails to CAS in its chosen slot, it picks an alternative slot
-     * instead.  And similarly from there.  If a thread successfully
-     * CASes into a slot but no other thread arrives, it tries
-     * another, heading toward the zero slot, which always exists even
-     * if the table shrinks.  The particular mechanics controlling this
-     * are as follows:
+     * This is among the simplest forms of a "dual data structure" --
+     * see Scott and Scherer's DISC 04 paper and
+     * http://www.cs.rochester.edu/research/synchronization/pseudocode/duals.html
      *
-     * Waiting: Slot zero is special in that it is the only slot that
-     * exists when there is no contention.  A thread occupying slot
-     * zero will block if no thread fulfills it after a short spin.
-     * In other cases, occupying threads eventually give up and try
-     * another slot.  Waiting threads spin for a while (a period that
-     * should be a little less than a typical context-switch time)
-     * before either blocking (if slot zero) or giving up (if other
-     * slots) and restarting.  There is no reason for threads to block
-     * unless there are unlikely to be any other threads present.
-     * Occupants are mainly avoiding memory contention so sit there
-     * quietly polling for a shorter period than it would take to
-     * block and then unblock them.  Non-slot-zero waits that elapse
-     * because of lack of other threads waste around one extra
-     * context-switch time per try, which is still on average much
-     * faster than alternative approaches.
+     * This works great in principle. But in practice, like many
+     * algorithms centered on atomic updates to a single location, it
+     * scales horribly when there are more than a few participants
+     * using the same Exchanger. So the implementation instead uses a
+     * form of elimination arena, that spreads out this contention by
+     * arranging that some threads typically use different slots,
+     * while still ensuring that eventually, any two parties will be
+     * able to exchange items. That is, we cannot completely partition
+     * across threads, but instead give threads arena indices that
+     * will on average grow under contention and shrink under lack of
+     * contention. We approach this by defining the Nodes that we need
+     * anyway as ThreadLocals, and include in them per-thread index
+     * and related bookkeeping state. (We can safely reuse per-thread
+     * nodes rather than creating them fresh each time because slots
+     * alternate between pointing to a node vs null, so cannot
+     * encounter ABA problems. However, we do need some care in
+     * resetting them between uses.)
      *
-     * Sizing: Usually, using only a few slots suffices to reduce
-     * contention.  Especially with small numbers of threads, using
-     * too many slots can lead to just as poor performance as using
-     * too few of them, and there's not much room for error.  The
-     * variable "max" maintains the number of slots actually in
-     * use.  It is increased when a thread sees too many CAS
-     * failures.  (This is analogous to resizing a regular hash table
-     * based on a target load factor, except here, growth steps are
-     * just one-by-one rather than proportional.)  Growth requires
-     * contention failures in each of three tried slots.  Requiring
-     * multiple failures for expansion copes with the fact that some
-     * failed CASes are not due to contention but instead to simple
-     * races between two threads or thread pre-emptions occurring
-     * between reading and CASing.  Also, very transient peak
-     * contention can be much higher than the average sustainable
-     * levels.  An attempt to decrease the max limit is usually made
-     * when a non-slot-zero wait elapses without being fulfilled.
-     * Threads experiencing elapsed waits move closer to zero, so
-     * eventually find existing (or future) threads even if the table
-     * has been shrunk due to inactivity.  The chosen mechanics and
-     * thresholds for growing and shrinking are intrinsically
-     * entangled with indexing and hashing inside the exchange code,
-     * and can't be nicely abstracted out.
+     * Implementing an effective arena requires allocating a bunch of
+     * space, so we only do so upon detecting contention (except on
+     * uniprocessors, where they wouldn't help, so aren't used).
+     * Otherwise, exchanges use the single-slot slotExchange method.
+     * On contention, not only must the slots be in different
+     * locations, but the locations must not encounter memory
+     * contention due to being on the same cache line (or more
+     * generally, the same coherence unit).  Because, as of this
+     * writing, there is no way to determine cacheline size, we define
+     * a value that is enough for common platforms.  Additionally,
+     * extra care elsewhere is taken to avoid other false/unintended
+     * sharing and to enhance locality, including adding padding to
+     * Nodes, embedding "bound" as an Exchanger field, and reworking
+     * some park/unpark mechanics compared to LockSupport versions.
      *
-     * Hashing: Each thread picks its initial slot to use in accord
-     * with a simple hashcode.  The sequence is the same on each
-     * encounter by any given thread, but effectively random across
-     * threads.  Using arenas encounters the classic cost vs quality
-     * tradeoffs of all hash tables.  Here, we use a one-step FNV-1a
-     * hash code based on the current thread's Thread.getId(), along
-     * with a cheap approximation to a mod operation to select an
-     * index.  The downside of optimizing index selection in this way
-     * is that the code is hardwired to use a maximum table size of
-     * 32.  But this value more than suffices for known platforms and
-     * applications.
+     * The arena starts out with only one used slot. We expand the
+     * effective arena size by tracking collisions; i.e., failed CASes
+     * while trying to exchange. By nature of the above algorithm, the
+     * only kinds of collision that reliably indicate contention are
+     * when two attempted releases collide -- one of two attempted
+     * offers can legitimately fail to CAS without indicating
+     * contention by more than one other thread. (Note: it is possible
+     * but not worthwhile to more precisely detect contention by
+     * reading slot values after CAS failures.)  When a thread has
+     * collided at each slot within the current arena bound, it tries
+     * to expand the arena size by one. We track collisions within
+     * bounds by using a version (sequence) number on the "bound"
+     * field, and conservatively reset collision counts when a
+     * participant notices that bound has been updated (in either
+     * direction).
      *
-     * Probing: On sensed contention of a selected slot, we probe
-     * sequentially through the table, analogously to linear probing
-     * after collision in a hash table.  (We move circularly, in
-     * reverse order, to mesh best with table growth and shrinkage
-     * rules.)  Except that to minimize the effects of false-alarms
-     * and cache thrashing, we try the first selected slot twice
-     * before moving.
+     * The effective arena size is reduced (when there is more than
+     * one slot) by giving up on waiting after a while and trying to
+     * decrement the arena size on expiration. The value of "a while"
+     * is an empirical matter.  We implement by piggybacking on the
+     * use of spin->yield->block that is essential for reasonable
+     * waiting performance anyway -- in a busy exchanger, offers are
+     * usually almost immediately released, in which case context
+     * switching on multiprocessors is extremely slow/wasteful.  Arena
+     * waits just omit the blocking part, and instead cancel. The spin
+     * count is empirically chosen to be a value that avoids blocking
+     * 99% of the time under maximum sustained exchange rates on a
+     * range of test machines. Spins and yields entail some limited
+     * randomness (using a cheap xorshift) to avoid regular patterns
+     * that can induce unproductive grow/shrink cycles. (Using a
+     * pseudorandom also helps regularize spin cycle duration by
+     * making branches unpredictable.)  Also, during an offer, a
+     * waiter can "know" that it will be released when its slot has
+     * changed, but cannot yet proceed until match is set.  In the
+     * mean time it cannot cancel the offer, so instead spins/yields.
+     * Note: It is possible to avoid this secondary check by changing
+     * the linearization point to be a CAS of the match field (as done
+     * in one case in the Scott & Scherer DISC paper), which also
+     * increases asynchrony a bit, at the expense of poorer collision
+     * detection and inability to always reuse per-thread nodes. So
+     * the current scheme is typically a better tradeoff.
      *
-     * Padding: Even with contention management, slots are heavily
-     * contended, so use cache-padding to avoid poor memory
-     * performance.  Because of this, slots are lazily constructed
-     * only when used, to avoid wasting this space unnecessarily.
-     * While isolation of locations is not much of an issue at first
-     * in an application, as time goes on and garbage-collectors
-     * perform compaction, slots are very likely to be moved adjacent
-     * to each other, which can cause much thrashing of cache lines on
-     * MPs unless padding is employed.
+     * On collisions, indices traverse the arena cyclically in reverse
+     * order, restarting at the maximum index (which will tend to be
+     * sparsest) when bounds change. (On expirations, indices instead
+     * are halved until reaching 0.) It is possible (and has been
+     * tried) to use randomized, prime-value-stepped, or double-hash
+     * style traversal instead of simple cyclic traversal to reduce
+     * bunching.  But empirically, whatever benefits these may have
+     * don't overcome their added overhead: We are managing operations
+     * that occur very quickly unless there is sustained contention,
+     * so simpler/faster control policies work better than more
+     * accurate but slower ones.
      *
-     * This is an improvement of the algorithm described in the paper
-     * "A Scalable Elimination-based Exchange Channel" by William
-     * Scherer, Doug Lea, and Michael Scott in Proceedings of SCOOL05
-     * workshop.  Available at: http://hdl.handle.net/1802/2104
+     * Because we use expiration for arena size control, we cannot
+     * throw TimeoutExceptions in the timed version of the public
+     * exchange method until the arena size has shrunken to zero (or
+     * the arena isn't enabled). This may delay response to timeout
+     * but is still within spec.
+     *
+     * Essentially all of the implementation is in methods
+     * slotExchange and arenaExchange. These have similar overall
+     * structure, but differ in too many details to combine. The
+     * slotExchange method uses the single Exchanger field "slot"
+     * rather than arena array elements. However, it still needs
+     * minimal collision detection to trigger arena construction.
+     * (The messiest part is making sure interrupt status and
+     * InterruptedExceptions come out right during transitions when
+     * both methods may be called. This is done by using null return
+     * as a sentinel to recheck interrupt status.)
+     *
+     * As is too common in this sort of code, methods are monolithic
+     * because most of the logic relies on reads of fields that are
+     * maintained as local variables so can't be nicely factored --
+     * mainly, here, bulky spin->yield->block/cancel code), and
+     * heavily dependent on intrinsics (Unsafe) to use inlined
+     * embedded CAS and related memory access operations (that tend
+     * not to be as readily inlined by dynamic compilers when they are
+     * hidden behind other methods that would more nicely name and
+     * encapsulate the intended effects). This includes the use of
+     * putOrderedX to clear fields of the per-thread Nodes between
+     * uses. Note that field Node.item is not declared as volatile
+     * even though it is read by releasing threads, because they only
+     * do so after CAS operations that must precede access, and all
+     * uses by the owning thread are otherwise acceptably ordered by
+     * other operations. (Because the actual points of atomicity are
+     * slot CASes, it would also be legal for the write to Node.match
+     * in a release to be weaker than a full volatile write. However,
+     * this is not done because it could allow further postponement of
+     * the write, delaying progress.)
      */
 
+    /**
+     * The byte distance (as a shift value) between any two used slots
+     * in the arena.  1 << ASHIFT should be at least cacheline size.
+     */
+    private static final int ASHIFT = 7;
+
+    /**
+     * The maximum supported arena index. The maximum allocatable
+     * arena size is MMASK + 1. Must be a power of two minus one, less
+     * than (1<<(31-ASHIFT)). The cap of 255 (0xff) more than suffices
+     * for the expected scaling limits of the main algorithms.
+     */
+    private static final int MMASK = 0xff;
+
+    /**
+     * Unit for sequence/version bits of bound field. Each successful
+     * change to the bound also adds SEQ.
+     */
+    private static final int SEQ = MMASK + 1;
+
     /** The number of CPUs, for sizing and spin control */
     private static final int NCPU = Runtime.getRuntime().availableProcessors();
 
     /**
-     * The capacity of the arena.  Set to a value that provides more
-     * than enough space to handle contention.  On small machines
-     * most slots won't be used, but it is still not wasted because
-     * the extra space provides some machine-level address padding
-     * to minimize interference with heavily CAS'ed Slot locations.
-     * And on very large machines, performance eventually becomes
-     * bounded by memory bandwidth, not numbers of threads/CPUs.
-     * This constant cannot be changed without also modifying
-     * indexing and hashing algorithms.
+     * The maximum slot index of the arena: The number of slots that
+     * can in principle hold all threads without contention, or at
+     * most the maximum indexable value.
      */
-    private static final int CAPACITY = 32;
+    static final int FULL = (NCPU >= (MMASK << 1)) ? MMASK : NCPU >>> 1;
 
     /**
-     * The value of "max" that will hold all threads without
-     * contention.  When this value is less than CAPACITY, some
-     * otherwise wasted expansion can be avoided.
+     * The bound for spins while waiting for a match. The actual
+     * number of iterations will on average be about twice this value
+     * due to randomization. Note: Spinning is disabled when NCPU==1.
      */
-    private static final int FULL =
-        Math.max(0, Math.min(CAPACITY, NCPU / 2) - 1);
-
-    /**
-     * The number of times to spin (doing nothing except polling a
-     * memory location) before blocking or giving up while waiting to
-     * be fulfilled.  Should be zero on uniprocessors.  On
-     * multiprocessors, this value should be large enough so that two
-     * threads exchanging items as fast as possible block only when
-     * one of them is stalled (due to GC or preemption), but not much
-     * longer, to avoid wasting CPU resources.  Seen differently, this
-     * value is a little over half the number of cycles of an average
-     * context switch time on most systems.  The value here is
-     * approximately the average of those across a range of tested
-     * systems.
-     */
-    private static final int SPINS = (NCPU == 1) ? 0 : 2000;
-
-    /**
-     * The number of times to spin before blocking in timed waits.
-     * Timed waits spin more slowly because checking the time takes
-     * time.  The best value relies mainly on the relative rate of
-     * System.nanoTime vs memory accesses.  The value is empirically
-     * derived to work well across a variety of systems.
-     */
-    private static final int TIMED_SPINS = SPINS / 20;
-
-    /**
-     * Sentinel item representing cancellation of a wait due to
-     * interruption, timeout, or elapsed spin-waits.  This value is
-     * placed in holes on cancellation, and used as a return value
-     * from waiting methods to indicate failure to set or get hole.
-     */
-    private static final Object CANCEL = new Object();
+    private static final int SPINS = 1 << 10;
 
     /**
      * Value representing null arguments/returns from public
-     * methods.  This disambiguates from internal requirement that
-     * holes start out as null to mean they are not yet set.
+     * methods. Needed because the API originally didn't disallow null
+     * arguments, which it should have.
      */
     private static final Object NULL_ITEM = new Object();
 
     /**
-     * Nodes hold partially exchanged data.  This class
-     * opportunistically subclasses AtomicReference to represent the
-     * hole.  So get() returns hole, and compareAndSet CAS'es value
-     * into hole.  This class cannot be parameterized as "V" because
-     * of the use of non-V CANCEL sentinels.
+     * Sentinel value returned by internal exchange methods upon
+     * timeout, to avoid need for separate timed versions of these
+     * methods.
      */
-    @SuppressWarnings("serial")
-    private static final class Node extends AtomicReference<Object> {
-        /** The element offered by the Thread creating this node. */
-        public final Object item;
-
-        /** The Thread waiting to be signalled; null until waiting. */
-        public volatile Thread waiter;
+    private static final Object TIMED_OUT = new Object();
 
         /**
-         * Creates node with given item and empty hole.
-         * @param item the item
+     * Nodes hold partially exchanged data, plus other per-thread
+     * bookkeeping.
          */
-        public Node(Object item) {
-            this.item = item;
+    static final class Node {
+        int index;              // Arena index
+        int bound;              // Last recorded value of Exchanger.bound
+        int collides;           // Number of CAS failures at current bound
+        int hash;               // Pseudo-random for spins
+        Object item;            // This thread's current item
+        volatile Object match;  // Item provided by releasing thread
+        volatile Thread parked; // Set to this thread when parked, else null
+
+        // Padding to ameliorate unfortunate memory placements
+        Object p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, pa, pb, pc, pd, pe, pf;
+        Object q0, q1, q2, q3, q4, q5, q6, q7, q8, q9, qa, qb, qc, qd, qe, qf;
+        }
+
+    /** The corresponding thread local class */
+    static final class Participant extends ThreadLocal<Node> {
+        public Node initialValue() { return new Node(); }
+    }
+
+    /**
+     * Per-thread state
+     */
+    private final Participant participant;
+
+    /**
+     * Elimination array; null until enabled (within slotExchange).
+     * Element accesses use emulation of volatile gets and CAS.
+     */
+    private volatile Node[] arena;
+
+    /**
+     * Slot used until contention detected.
+     */
+    private volatile Node slot;
+
+    /**
+     * The index of the largest valid arena position, OR'ed with SEQ
+     * number in high bits, incremented on each update.  The initial
+     * update from 0 to SEQ is used to ensure that the arena array is
+     * constructed only once.
+     */
+    private volatile int bound;
+
+    /**
+     * Exchange function when arenas enabled. See above for explanation.
+     *
+     * @param item the (non-null) item to exchange
+     * @param timed true if the wait is timed
+     * @param ns if timed, the maximum wait time, else 0L
+     * @return the other thread's item; or null if interrupted; or
+     * TIMED_OUT if timed and timed out
+     */
+    private final Object arenaExchange(Object item, boolean timed, long ns) {
+        Node[] a = arena;
+        Node p = participant.get();
+        for (int i = p.index;;) {                      // access slot at i
+            int b, m, c; long j;                       // j is raw array offset
+            Node q = (Node)U.getObjectVolatile(a, j = (i << ASHIFT) + ABASE);
+            if (q != null && U.compareAndSwapObject(a, j, q, null)) {
+                Object v = q.item;                     // release
+                q.match = item;
+                Thread w = q.parked;
+                if (w != null)
+                    U.unpark(w);
+                return v;
+            }
+            else if (i <= (m = (b = bound) & MMASK) && q == null) {
+                p.item = item;                         // offer
+                if (U.compareAndSwapObject(a, j, null, p)) {
+                    long end = (timed && m == 0) ? System.nanoTime() + ns : 0L;
+                    Thread t = Thread.currentThread(); // wait
+                    for (int h = p.hash, spins = SPINS;;) {
+                        Object v = p.match;
+                        if (v != null) {
+                            U.putOrderedObject(p, MATCH, null);
+                            p.item = null;             // clear for next use
+                            p.hash = h;
+                    return v;
+            }
+                        else if (spins > 0) {
+                            h ^= h << 1; h ^= h >>> 3; h ^= h << 10; // xorshift
+                            if (h == 0)                // initialize hash
+                                h = SPINS | (int)t.getId();
+                            else if (h < 0 &&          // approx 50% true
+                                     (--spins & ((SPINS >>> 1) - 1)) == 0)
+                                Thread.yield();        // two yields per wait
+            }
+                        else if (U.getObjectVolatile(a, j) != p)
+                            spins = SPINS;       // releaser hasn't set match yet
+                        else if (!t.isInterrupted() && m == 0 &&
+                                 (!timed ||
+                                  (ns = end - System.nanoTime()) > 0L)) {
+                            U.putObject(t, BLOCKER, this); // emulate LockSupport
+                            p.parked = t;              // minimize window
+                            if (U.getObjectVolatile(a, j) == p)
+                                U.park(false, ns);
+                            p.parked = null;
+                            U.putObject(t, BLOCKER, null);
+        }
+                        else if (U.getObjectVolatile(a, j) == p &&
+                                 U.compareAndSwapObject(a, j, p, null)) {
+                            if (m != 0)                // try to shrink
+                                U.compareAndSwapInt(this, BOUND, b, b + SEQ - 1);
+                            p.item = null;
+                            p.hash = h;
+                            i = p.index >>>= 1;        // descend
+                            if (Thread.interrupted())
+                                return null;
+                            if (timed && m == 0 && ns <= 0L)
+                                return TIMED_OUT;
+                            break;                     // expired; restart
+    }
+    }
+        }
+                else
+                    p.item = null;                     // clear offer
+    }
+            else {
+                if (p.bound != b) {                    // stale; reset
+                    p.bound = b;
+                    p.collides = 0;
+                    i = (i != m || m == 0) ? m : m - 1;
+    }
+                else if ((c = p.collides) < m || m == FULL ||
+                         !U.compareAndSwapInt(this, BOUND, b, b + SEQ + 1)) {
+                    p.collides = c + 1;
+                    i = (i == 0) ? m : i - 1;          // cyclically traverse
+        }
+                else
+                    i = m + 1;                         // grow
+                p.index = i;
+    }
         }
     }
 
     /**
-     * A Slot is an AtomicReference with heuristic padding to lessen
-     * cache effects of this heavily CAS'ed location.  While the
-     * padding adds noticeable space, all slots are created only on
-     * demand, and there will be more than one of them only when it
-     * would improve throughput more than enough to outweigh using
-     * extra space.
+     * Exchange function used until arenas enabled. See above for explanation.
+     *
+     * @param item the item to exchange
+     * @param timed true if the wait is timed
+     * @param ns if timed, the maximum wait time, else 0L
+     * @return the other thread's item; or null if either the arena
+     * was enabled or the thread was interrupted before completion; or
+     * TIMED_OUT if timed and timed out
      */
-    @SuppressWarnings("serial")
-    private static final class Slot extends AtomicReference<Object> {
-        // Improve likelihood of isolation on <= 64 byte cache lines
-        long q0, q1, q2, q3, q4, q5, q6, q7, q8, q9, qa, qb, qc, qd, qe;
+    private final Object slotExchange(Object item, boolean timed, long ns) {
+        Node p = participant.get();
+        Thread t = Thread.currentThread();
+        if (t.isInterrupted()) // preserve interrupt status so caller can recheck
+            return null;
+
+        for (Node q;;) {
+            if ((q = slot) != null) {
+                if (U.compareAndSwapObject(this, SLOT, q, null)) {
+                    Object v = q.item;
+                    q.match = item;
+                    Thread w = q.parked;
+                    if (w != null)
+                        U.unpark(w);
+                return v;
+            }
+                // create arena on contention, but continue until slot null
+                if (NCPU > 1 && bound == 0 &&
+                    U.compareAndSwapInt(this, BOUND, 0, SEQ))
+                    arena = new Node[(FULL + 2) << ASHIFT];
+        }
+            else if (arena != null)
+                return null; // caller must reroute to arenaExchange
+            else {
+                p.item = item;
+                if (U.compareAndSwapObject(this, SLOT, null, p))
+                    break;
+                p.item = null;
     }
+                        }
 
-    /**
-     * Slot array.  Elements are lazily initialized when needed.
-     * Declared volatile to enable double-checked lazy construction.
-     */
-    private volatile Slot[] arena = new Slot[CAPACITY];
-
-    /**
-     * The maximum slot index being used.  The value sometimes
-     * increases when a thread experiences too many CAS contentions,
-     * and sometimes decreases when a spin-wait elapses.  Changes
-     * are performed only via compareAndSet, to avoid stale values
-     * when a thread happens to stall right before setting.
-     */
-    private final AtomicInteger max = new AtomicInteger();
-
-    /**
-     * Main exchange function, handling the different policy variants.
-     * Uses Object, not "V" as argument and return value to simplify
-     * handling of sentinel values.  Callers from public methods decode
-     * and cast accordingly.
-     *
-     * @param item the (non-null) item to exchange
-     * @param timed true if the wait is timed
-     * @param nanos if timed, the maximum wait time
-     * @return the other thread's item, or CANCEL if interrupted or timed out
-     */
-    private Object doExchange(Object item, boolean timed, long nanos) {
-        Node me = new Node(item);                 // Create in case occupying
-        int index = hashIndex();                  // Index of current slot
-        int fails = 0;                            // Number of CAS failures
-
-        for (;;) {
-            Object y;                             // Contents of current slot
-            Slot slot = arena[index];
-            if (slot == null)                     // Lazily initialize slots
-                createSlot(index);                // Continue loop to reread
-            else if ((y = slot.get()) != null &&  // Try to fulfill
-                     slot.compareAndSet(y, null)) {
-                Node you = (Node)y;               // Transfer item
-                if (you.compareAndSet(null, item)) {
-                    LockSupport.unpark(you.waiter);
-                    return you.item;
-                }                                 // Else cancelled; continue
-            }
-            else if (y == null &&                 // Try to occupy
-                     slot.compareAndSet(null, me)) {
-                if (index == 0)                   // Blocking wait for slot 0
-                    return timed ?
-                        awaitNanos(me, slot, nanos) :
-                        await(me, slot);
-                Object v = spinWait(me, slot);    // Spin wait for non-0
-                if (v != CANCEL)
-                    return v;
-                me = new Node(item);              // Throw away cancelled node
-                int m = max.get();
-                if (m > (index >>>= 1))           // Decrease index
-                    max.compareAndSet(m, m - 1);  // Maybe shrink table
-            }
-            else if (++fails > 1) {               // Allow 2 fails on 1st slot
-                int m = max.get();
-                if (fails > 3 && m < FULL && max.compareAndSet(m, m + 1))
-                    index = m + 1;                // Grow on 3rd failed slot
-                else if (--index < 0)
-                    index = m;                    // Circularly traverse
+        // await release
+        int h = p.hash;
+        long end = timed ? System.nanoTime() + ns : 0L;
+        int spins = (NCPU > 1) ? SPINS : 1;
+        Object v;
+        while ((v = p.match) == null) {
+            if (spins > 0) {
+                h ^= h << 1; h ^= h >>> 3; h ^= h << 10;
+                if (h == 0)
+                    h = SPINS | (int)t.getId();
+                else if (h < 0 && (--spins & ((SPINS >>> 1) - 1)) == 0)
+                    Thread.yield();
+                    }
+            else if (slot != p)
+                spins = SPINS;
+            else if (!t.isInterrupted() && arena == null &&
+                     (!timed || (ns = end - System.nanoTime()) > 0L)) {
+                U.putObject(t, BLOCKER, this);
+                p.parked = t;
+                if (slot == p)
+                    U.park(false, ns);
+                p.parked = null;
+                U.putObject(t, BLOCKER, null);
+                }
+            else if (U.compareAndSwapObject(this, SLOT, p, null)) {
+                v = timed && ns <= 0L && !t.isInterrupted() ? TIMED_OUT : null;
+                break;
             }
         }
-    }
-
-    /**
-     * Returns a hash index for the current thread.  Uses a one-step
-     * FNV-1a hash code (http://www.isthe.com/chongo/tech/comp/fnv/)
-     * based on the current thread's Thread.getId().  These hash codes
-     * have more uniform distribution properties with respect to small
-     * moduli (here 1-31) than do other simple hashing functions.
-     *
-     * <p>To return an index between 0 and max, we use a cheap
-     * approximation to a mod operation, that also corrects for bias
-     * due to non-power-of-2 remaindering (see {@link
-     * java.util.Random#nextInt}).  Bits of the hashcode are masked
-     * with "nbits", the ceiling power of two of table size (looked up
-     * in a table packed into three ints).  If too large, this is
-     * retried after rotating the hash by nbits bits, while forcing new
-     * top bit to 0, which guarantees eventual termination (although
-     * with a non-random-bias).  This requires an average of less than
-     * 2 tries for all table sizes, and has a maximum 2% difference
-     * from perfectly uniform slot probabilities when applied to all
-     * possible hash codes for sizes less than 32.
-     *
-     * @return a per-thread-random index, 0 <= index < max
-     */
-    private final int hashIndex() {
-        long id = Thread.currentThread().getId();
-        int hash = (((int)(id ^ (id >>> 32))) ^ 0x811c9dc5) * 0x01000193;
-
-        int m = max.get();
-        int nbits = (((0xfffffc00  >> m) & 4) | // Compute ceil(log2(m+1))
-                     ((0x000001f8 >>> m) & 2) | // The constants hold
-                     ((0xffff00f2 >>> m) & 1)); // a lookup table
-        int index;
-        while ((index = hash & ((1 << nbits) - 1)) > m)       // May retry on
-            hash = (hash >>> nbits) | (hash << (33 - nbits)); // non-power-2 m
-        return index;
-    }
-
-    /**
-     * Creates a new slot at given index.  Called only when the slot
-     * appears to be null.  Relies on double-check using builtin
-     * locks, since they rarely contend.  This in turn relies on the
-     * arena array being declared volatile.
-     *
-     * @param index the index to add slot at
-     */
-    private void createSlot(int index) {
-        // Create slot outside of lock to narrow sync region
-        Slot newSlot = new Slot();
-        Slot[] a = arena;
-        synchronized (a) {
-            if (a[index] == null)
-                a[index] = newSlot;
-        }
-    }
-
-    /**
-     * Tries to cancel a wait for the given node waiting in the given
-     * slot, if so, helping clear the node from its slot to avoid
-     * garbage retention.
-     *
-     * @param node the waiting node
-     * @param the slot it is waiting in
-     * @return true if successfully cancelled
-     */
-    private static boolean tryCancel(Node node, Slot slot) {
-        if (!node.compareAndSet(null, CANCEL))
-            return false;
-        if (slot.get() == node) // pre-check to minimize contention
-            slot.compareAndSet(node, null);
-        return true;
-    }
-
-    // Three forms of waiting. Each just different enough not to merge
-    // code with others.
-
-    /**
-     * Spin-waits for hole for a non-0 slot.  Fails if spin elapses
-     * before hole filled.  Does not check interrupt, relying on check
-     * in public exchange method to abort if interrupted on entry.
-     *
-     * @param node the waiting node
-     * @return on success, the hole; on failure, CANCEL
-     */
-    private static Object spinWait(Node node, Slot slot) {
-        int spins = SPINS;
-        for (;;) {
-            Object v = node.get();
-            if (v != null)
-                return v;
-            else if (spins > 0)
-                --spins;
-            else
-                tryCancel(node, slot);
-        }
-    }
-
-    /**
-     * Waits for (by spinning and/or blocking) and gets the hole
-     * filled in by another thread.  Fails if interrupted before
-     * hole filled.
-     *
-     * When a node/thread is about to block, it sets its waiter field
-     * and then rechecks state at least one more time before actually
-     * parking, thus covering race vs fulfiller noticing that waiter
-     * is non-null so should be woken.
-     *
-     * Thread interruption status is checked only surrounding calls to
-     * park.  The caller is assumed to have checked interrupt status
-     * on entry.
-     *
-     * @param node the waiting node
-     * @return on success, the hole; on failure, CANCEL
-     */
-    private static Object await(Node node, Slot slot) {
-        Thread w = Thread.currentThread();
-        int spins = SPINS;
-        for (;;) {
-            Object v = node.get();
-            if (v != null)
-                return v;
-            else if (spins > 0)                 // Spin-wait phase
-                --spins;
-            else if (node.waiter == null)       // Set up to block next
-                node.waiter = w;
-            else if (w.isInterrupted())         // Abort on interrupt
-                tryCancel(node, slot);
-            else                                // Block
-                LockSupport.park(node);
-        }
-    }
-
-    /**
-     * Waits for (at index 0) and gets the hole filled in by another
-     * thread.  Fails if timed out or interrupted before hole filled.
-     * Same basic logic as untimed version, but a bit messier.
-     *
-     * @param node the waiting node
-     * @param nanos the wait time
-     * @return on success, the hole; on failure, CANCEL
-     */
-    private Object awaitNanos(Node node, Slot slot, long nanos) {
-        int spins = TIMED_SPINS;
-        long lastTime = 0;
-        Thread w = null;
-        for (;;) {
-            Object v = node.get();
-            if (v != null)
-                return v;
-            long now = System.nanoTime();
-            if (w == null)
-                w = Thread.currentThread();
-            else
-                nanos -= now - lastTime;
-            lastTime = now;
-            if (nanos > 0) {
-                if (spins > 0)
-                    --spins;
-                else if (node.waiter == null)
-                    node.waiter = w;
-                else if (w.isInterrupted())
-                    tryCancel(node, slot);
-                else
-                    LockSupport.parkNanos(node, nanos);
-            }
-            else if (tryCancel(node, slot) && !w.isInterrupted())
-                return scanOnTimeout(node);
-        }
-    }
-
-    /**
-     * Sweeps through arena checking for any waiting threads.  Called
-     * only upon return from timeout while waiting in slot 0.  When a
-     * thread gives up on a timed wait, it is possible that a
-     * previously-entered thread is still waiting in some other
-     * slot.  So we scan to check for any.  This is almost always
-     * overkill, but decreases the likelihood of timeouts when there
-     * are other threads present to far less than that in lock-based
-     * exchangers in which earlier-arriving threads may still be
-     * waiting on entry locks.
-     *
-     * @param node the waiting node
-     * @return another thread's item, or CANCEL
-     */
-    private Object scanOnTimeout(Node node) {
-        Object y;
-        for (int j = arena.length - 1; j >= 0; --j) {
-            Slot slot = arena[j];
-            if (slot != null) {
-                while ((y = slot.get()) != null) {
-                    if (slot.compareAndSet(y, null)) {
-                        Node you = (Node)y;
-                        if (you.compareAndSet(null, node.item)) {
-                            LockSupport.unpark(you.waiter);
-                            return you.item;
-                        }
-                    }
-                }
-            }
-        }
-        return CANCEL;
+        U.putOrderedObject(p, MATCH, null);
+        p.item = null;
+        p.hash = h;
+        return v;
     }
 
     /**
      * Creates a new Exchanger.
      */
     public Exchanger() {
+        participant = new Participant();
     }
 
     /**
@@ -620,15 +561,14 @@
      */
     @SuppressWarnings("unchecked")
     public V exchange(V x) throws InterruptedException {
-        if (!Thread.interrupted()) {
-            Object o = doExchange((x == null) ? NULL_ITEM : x, false, 0);
-            if (o == NULL_ITEM)
-                return null;
-            if (o != CANCEL)
-                return (V)o;
-            Thread.interrupted(); // Clear interrupt status on IE throw
-        }
+        Object v;
+        Object item = (x == null) ? NULL_ITEM : x; // translate null args
+        if ((arena != null ||
+             (v = slotExchange(item, false, 0L)) == null) &&
+            ((Thread.interrupted() || // disambiguates null return
+              (v = arenaExchange(item, false, 0L)) == null)))
         throw new InterruptedException();
+        return (v == NULL_ITEM) ? null : (V)v;
     }
 
     /**
@@ -666,7 +606,7 @@
      *
      * @param x the object to exchange
      * @param timeout the maximum time to wait
-     * @param unit the time unit of the <tt>timeout</tt> argument
+     * @param unit the time unit of the {@code timeout} argument
      * @return the object provided by the other thread
      * @throws InterruptedException if the current thread was
      *         interrupted while waiting
@@ -676,16 +616,51 @@
     @SuppressWarnings("unchecked")
     public V exchange(V x, long timeout, TimeUnit unit)
         throws InterruptedException, TimeoutException {
-        if (!Thread.interrupted()) {
-            Object o = doExchange((x == null) ? NULL_ITEM : x,
-                                  true, unit.toNanos(timeout));
-            if (o == NULL_ITEM)
-                return null;
-            if (o != CANCEL)
-                return (V)o;
-            if (!Thread.interrupted())
+        Object v;
+        Object item = (x == null) ? NULL_ITEM : x;
+        long ns = unit.toNanos(timeout);
+        if ((arena != null ||
+             (v = slotExchange(item, true, ns)) == null) &&
+            ((Thread.interrupted() ||
+              (v = arenaExchange(item, true, ns)) == null)))
+            throw new InterruptedException();
+        if (v == TIMED_OUT)
                 throw new TimeoutException();
+        return (v == NULL_ITEM) ? null : (V)v;
         }
-        throw new InterruptedException();
+
+    // Unsafe mechanics
+    private static final sun.misc.Unsafe U;
+    private static final long BOUND;
+    private static final long SLOT;
+    private static final long MATCH;
+    private static final long BLOCKER;
+    private static final int ABASE;
+    static {
+        int s;
+        try {
+            U = sun.misc.Unsafe.getUnsafe();
+            Class<?> ek = Exchanger.class;
+            Class<?> nk = Node.class;
+            Class<?> ak = Node[].class;
+            Class<?> tk = Thread.class;
+            BOUND = U.objectFieldOffset
+                (ek.getDeclaredField("bound"));
+            SLOT = U.objectFieldOffset
+                (ek.getDeclaredField("slot"));
+            MATCH = U.objectFieldOffset
+                (nk.getDeclaredField("match"));
+            BLOCKER = U.objectFieldOffset
+                (tk.getDeclaredField("parkBlocker"));
+            s = U.arrayIndexScale(ak);
+            // ABASE absorbs padding in front of element 0
+            ABASE = U.arrayBaseOffset(ak) + (1 << ASHIFT);
+
+        } catch (Exception e) {
+            throw new Error(e);
+        }
+        if ((s & (s-1)) != 0 || s > (1 << ASHIFT))
+            throw new Error("Unsupported array scale");
     }
+
 }
--- a/src/share/classes/java/util/concurrent/ExecutionException.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/ExecutionException.java	Wed Feb 20 15:42:21 2013 -0800
@@ -48,14 +48,14 @@
     private static final long serialVersionUID = 7830266012832686185L;
 
     /**
-     * Constructs an <tt>ExecutionException</tt> with no detail message.
+     * Constructs an {@code ExecutionException} with no detail message.
      * The cause is not initialized, and may subsequently be
      * initialized by a call to {@link #initCause(Throwable) initCause}.
      */
     protected ExecutionException() { }
 
     /**
-     * Constructs an <tt>ExecutionException</tt> with the specified detail
+     * Constructs an {@code ExecutionException} with the specified detail
      * message. The cause is not initialized, and may subsequently be
      * initialized by a call to {@link #initCause(Throwable) initCause}.
      *
@@ -66,7 +66,7 @@
     }
 
     /**
-     * Constructs an <tt>ExecutionException</tt> with the specified detail
+     * Constructs an {@code ExecutionException} with the specified detail
      * message and cause.
      *
      * @param  message the detail message
@@ -78,7 +78,7 @@
     }
 
     /**
-     * Constructs an <tt>ExecutionException</tt> with the specified cause.
+     * Constructs an {@code ExecutionException} with the specified cause.
      * The detail message is set to {@code (cause == null ? null :
      * cause.toString())} (which typically contains the class and
      * detail message of {@code cause}).
--- a/src/share/classes/java/util/concurrent/Executor.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/Executor.java	Wed Feb 20 15:42:21 2013 -0800
@@ -39,9 +39,9 @@
  * An object that executes submitted {@link Runnable} tasks. This
  * interface provides a way of decoupling task submission from the
  * mechanics of how each task will be run, including details of thread
- * use, scheduling, etc.  An <tt>Executor</tt> is normally used
+ * use, scheduling, etc.  An {@code Executor} is normally used
  * instead of explicitly creating threads. For example, rather than
- * invoking <tt>new Thread(new(RunnableTask())).start()</tt> for each
+ * invoking {@code new Thread(new(RunnableTask())).start()} for each
  * of a set of tasks, you might use:
  *
  * <pre>
@@ -51,7 +51,7 @@
  * ...
  * </pre>
  *
- * However, the <tt>Executor</tt> interface does not strictly
+ * However, the {@code Executor} interface does not strictly
  * require that execution be asynchronous. In the simplest case, an
  * executor can run the submitted task immediately in the caller's
  * thread:
@@ -74,7 +74,7 @@
  *   }
  * }}</pre>
  *
- * Many <tt>Executor</tt> implementations impose some sort of
+ * Many {@code Executor} implementations impose some sort of
  * limitation on how and when tasks are scheduled.  The executor below
  * serializes the submission of tasks to a second executor,
  * illustrating a composite executor.
@@ -111,7 +111,7 @@
  *   }
  * }}</pre>
  *
- * The <tt>Executor</tt> implementations provided in this package
+ * The {@code Executor} implementations provided in this package
  * implement {@link ExecutorService}, which is a more extensive
  * interface.  The {@link ThreadPoolExecutor} class provides an
  * extensible thread pool implementation. The {@link Executors} class
@@ -130,11 +130,11 @@
     /**
      * Executes the given command at some time in the future.  The command
      * may execute in a new thread, in a pooled thread, or in the calling
-     * thread, at the discretion of the <tt>Executor</tt> implementation.
+     * thread, at the discretion of the {@code Executor} implementation.
      *
      * @param command the runnable task
      * @throws RejectedExecutionException if this task cannot be
-     * accepted for execution.
+     * accepted for execution
      * @throws NullPointerException if command is null
      */
     void execute(Runnable command);
--- a/src/share/classes/java/util/concurrent/ExecutorService.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/ExecutorService.java	Wed Feb 20 15:42:21 2013 -0800
@@ -42,21 +42,21 @@
  * methods that can produce a {@link Future} for tracking progress of
  * one or more asynchronous tasks.
  *
- * <p> An <tt>ExecutorService</tt> can be shut down, which will cause
+ * <p> An {@code ExecutorService} can be shut down, which will cause
  * it to reject new tasks.  Two different methods are provided for
- * shutting down an <tt>ExecutorService</tt>. The {@link #shutdown}
+ * shutting down an {@code ExecutorService}. The {@link #shutdown}
  * method will allow previously submitted tasks to execute before
  * terminating, while the {@link #shutdownNow} method prevents waiting
  * tasks from starting and attempts to stop currently executing tasks.
  * Upon termination, an executor has no tasks actively executing, no
  * tasks awaiting execution, and no new tasks can be submitted.  An
- * unused <tt>ExecutorService</tt> should be shut down to allow
+ * unused {@code ExecutorService} should be shut down to allow
  * reclamation of its resources.
  *
- * <p> Method <tt>submit</tt> extends base method {@link
- * Executor#execute} by creating and returning a {@link Future} that
- * can be used to cancel execution and/or wait for completion.
- * Methods <tt>invokeAny</tt> and <tt>invokeAll</tt> perform the most
+ * <p> Method {@code submit} extends base method {@link
+ * Executor#execute(Runnable)} by creating and returning a {@link Future}
+ * that can be used to cancel execution and/or wait for completion.
+ * Methods {@code invokeAny} and {@code invokeAll} perform the most
  * commonly useful forms of bulk execution, executing a collection of
  * tasks and then waiting for at least one, or all, to
  * complete. (Class {@link ExecutorCompletionService} can be used to
@@ -101,9 +101,9 @@
  *   }
  * }}</pre>
  *
- * The following method shuts down an <tt>ExecutorService</tt> in two phases,
- * first by calling <tt>shutdown</tt> to reject incoming tasks, and then
- * calling <tt>shutdownNow</tt>, if necessary, to cancel any lingering tasks:
+ * The following method shuts down an {@code ExecutorService} in two phases,
+ * first by calling {@code shutdown} to reject incoming tasks, and then
+ * calling {@code shutdownNow}, if necessary, to cancel any lingering tasks:
  *
  *  <pre> {@code
  * void shutdownAndAwaitTermination(ExecutorService pool) {
@@ -149,8 +149,8 @@
      *         shutting down this ExecutorService may manipulate
      *         threads that the caller is not permitted to modify
      *         because it does not hold {@link
-     *         java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
-     *         or the security manager's <tt>checkAccess</tt> method
+     *         java.lang.RuntimePermission}{@code ("modifyThread")},
+     *         or the security manager's {@code checkAccess} method
      *         denies access.
      */
     void shutdown();
@@ -174,25 +174,25 @@
      *         shutting down this ExecutorService may manipulate
      *         threads that the caller is not permitted to modify
      *         because it does not hold {@link
-     *         java.lang.RuntimePermission}<tt>("modifyThread")</tt>,
-     *         or the security manager's <tt>checkAccess</tt> method
+     *         java.lang.RuntimePermission}{@code ("modifyThread")},
+     *         or the security manager's {@code checkAccess} method
      *         denies access.
      */
     List<Runnable> shutdownNow();
 
     /**
-     * Returns <tt>true</tt> if this executor has been shut down.
+     * Returns {@code true} if this executor has been shut down.
      *
-     * @return <tt>true</tt> if this executor has been shut down
+     * @return {@code true} if this executor has been shut down
      */
     boolean isShutdown();
 
     /**
-     * Returns <tt>true</tt> if all tasks have completed following shut down.
-     * Note that <tt>isTerminated</tt> is never <tt>true</tt> unless
-     * either <tt>shutdown</tt> or <tt>shutdownNow</tt> was called first.
+     * Returns {@code true} if all tasks have completed following shut down.
+     * Note that {@code isTerminated} is never {@code true} unless
+     * either {@code shutdown} or {@code shutdownNow} was called first.
      *
-     * @return <tt>true</tt> if all tasks have completed following shut down
+     * @return {@code true} if all tasks have completed following shut down
      */
     boolean isTerminated();
 
@@ -203,8 +203,8 @@
      *
      * @param timeout the maximum time to wait
      * @param unit the time unit of the timeout argument
-     * @return <tt>true</tt> if this executor terminated and
-     *         <tt>false</tt> if the timeout elapsed before termination
+     * @return {@code true} if this executor terminated and
+     *         {@code false} if the timeout elapsed before termination
      * @throws InterruptedException if interrupted while waiting
      */
     boolean awaitTermination(long timeout, TimeUnit unit)
@@ -213,13 +213,13 @@
     /**
      * Submits a value-returning task for execution and returns a
      * Future representing the pending results of the task. The
-     * Future's <tt>get</tt> method will return the task's result upon
+     * Future's {@code get} method will return the task's result upon
      * successful completion.
      *
      * <p>
      * If you would like to immediately block waiting
      * for a task, you can use constructions of the form
-     * <tt>result = exec.submit(aCallable).get();</tt>
+     * {@code result = exec.submit(aCallable).get();}
      *
      * <p> Note: The {@link Executors} class includes a set of methods
      * that can convert some other common closure-like objects,
@@ -236,7 +236,7 @@
 
     /**
      * Submits a Runnable task for execution and returns a Future
-     * representing that task. The Future's <tt>get</tt> method will
+     * representing that task. The Future's {@code get} method will
      * return the given result upon successful completion.
      *
      * @param task the task to submit
@@ -250,8 +250,8 @@
 
     /**
      * Submits a Runnable task for execution and returns a Future
-     * representing that task. The Future's <tt>get</tt> method will
-     * return <tt>null</tt> upon <em>successful</em> completion.
+     * representing that task. The Future's {@code get} method will
+     * return {@code null} upon <em>successful</em> completion.
      *
      * @param task the task to submit
      * @return a Future representing pending completion of the task
@@ -264,7 +264,7 @@
     /**
      * Executes the given tasks, returning a list of Futures holding
      * their status and results when all complete.
-     * {@link Future#isDone} is <tt>true</tt> for each
+     * {@link Future#isDone} is {@code true} for each
      * element of the returned list.
      * Note that a <em>completed</em> task could have
      * terminated either normally or by throwing an exception.
@@ -272,12 +272,12 @@
      * collection is modified while this operation is in progress.
      *
      * @param tasks the collection of tasks
-     * @return A list of Futures representing the tasks, in the same
+     * @return a list of Futures representing the tasks, in the same
      *         sequential order as produced by the iterator for the
-     *         given task list, each of which has completed.
+     *         given task list, each of which has completed
      * @throws InterruptedException if interrupted while waiting, in
-     *         which case unfinished tasks are cancelled.
-     * @throws NullPointerException if tasks or any of its elements are <tt>null</tt>
+     *         which case unfinished tasks are cancelled
+     * @throws NullPointerException if tasks or any of its elements are {@code null}
      * @throws RejectedExecutionException if any task cannot be
      *         scheduled for execution
      */
@@ -288,7 +288,7 @@
      * Executes the given tasks, returning a list of Futures holding
      * their status and results
      * when all complete or the timeout expires, whichever happens first.
-     * {@link Future#isDone} is <tt>true</tt> for each
+     * {@link Future#isDone} is {@code true} for each
      * element of the returned list.
      * Upon return, tasks that have not completed are cancelled.
      * Note that a <em>completed</em> task could have
@@ -307,7 +307,7 @@
      * @throws InterruptedException if interrupted while waiting, in
      *         which case unfinished tasks are cancelled
      * @throws NullPointerException if tasks, any of its elements, or
-     *         unit are <tt>null</tt>
+     *         unit are {@code null}
      * @throws RejectedExecutionException if any task cannot be scheduled
      *         for execution
      */
@@ -327,7 +327,7 @@
      * @return the result returned by one of the tasks
      * @throws InterruptedException if interrupted while waiting
      * @throws NullPointerException if tasks or any element task
-     *         subject to execution is <tt>null</tt>
+     *         subject to execution is {@code null}
      * @throws IllegalArgumentException if tasks is empty
      * @throws ExecutionException if no task successfully completes
      * @throws RejectedExecutionException if tasks cannot be scheduled
@@ -348,10 +348,10 @@
      * @param tasks the collection of tasks
      * @param timeout the maximum time to wait
      * @param unit the time unit of the timeout argument
-     * @return the result returned by one of the tasks.
+     * @return the result returned by one of the tasks
      * @throws InterruptedException if interrupted while waiting
      * @throws NullPointerException if tasks, or unit, or any element
-     *         task subject to execution is <tt>null</tt>
+     *         task subject to execution is {@code null}
      * @throws TimeoutException if the given timeout elapses before
      *         any task successfully completes
      * @throws ExecutionException if no task successfully completes
--- a/src/share/classes/java/util/concurrent/Executors.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/Executors.java	Wed Feb 20 15:42:21 2013 -0800
@@ -62,7 +62,7 @@
  *        that sets newly created threads to a known state.
  *   <li> Methods that create and return a {@link Callable}
  *        out of other closure-like forms, so they can be used
- *        in execution methods requiring <tt>Callable</tt>.
+ *        in execution methods requiring {@code Callable}.
  * </ul>
  *
  * @since 1.5
@@ -73,7 +73,7 @@
     /**
      * Creates a thread pool that reuses a fixed number of threads
      * operating off a shared unbounded queue.  At any point, at most
-     * <tt>nThreads</tt> threads will be active processing tasks.
+     * {@code nThreads} threads will be active processing tasks.
      * If additional tasks are submitted when all threads are active,
      * they will wait in the queue until a thread is available.
      * If any thread terminates due to a failure during execution
@@ -92,10 +92,46 @@
     }
 
     /**
+     * Creates a thread pool that maintains enough threads to support
+     * the given parallelism level, and may use multiple queues to
+     * reduce contention. The parallelism level corresponds to the
+     * maximum number of threads actively engaged in, or available to
+     * engage in, task processing. The actual number of threads may
+     * grow and shrink dynamically. A work-stealing pool makes no
+     * guarantees about the order in which submitted tasks are
+     * executed.
+     *
+     * @param parallelism the targeted parallelism level
+     * @return the newly created thread pool
+     * @throws IllegalArgumentException if {@code parallelism <= 0}
+     * @since 1.8
+     */
+    public static ExecutorService newWorkStealingPool(int parallelism) {
+        return new ForkJoinPool
+            (parallelism,
+             ForkJoinPool.defaultForkJoinWorkerThreadFactory,
+             null, true);
+    }
+
+    /**
+     * Creates a work-stealing thread pool using all
+     * {@link Runtime#availableProcessors available processors}
+     * as its target parallelism level.
+     * @return the newly created thread pool
+     * @since 1.8
+     */
+    public static ExecutorService newWorkStealingPool() {
+        return new ForkJoinPool
+            (Runtime.getRuntime().availableProcessors(),
+             ForkJoinPool.defaultForkJoinWorkerThreadFactory,
+             null, true);
+    }
+
+    /**
      * Creates a thread pool that reuses a fixed number of threads
      * operating off a shared unbounded queue, using the provided
      * ThreadFactory to create new threads when needed.  At any point,
-     * at most <tt>nThreads</tt> threads will be active processing
+     * at most {@code nThreads} threads will be active processing
      * tasks.  If additional tasks are submitted when all threads are
      * active, they will wait in the queue until a thread is
      * available.  If any thread terminates due to a failure during
@@ -125,7 +161,7 @@
      * subsequent tasks.)  Tasks are guaranteed to execute
      * sequentially, and no more than one task will be active at any
      * given time. Unlike the otherwise equivalent
-     * <tt>newFixedThreadPool(1)</tt> the returned executor is
+     * {@code newFixedThreadPool(1)} the returned executor is
      * guaranteed not to be reconfigurable to use additional threads.
      *
      * @return the newly created single-threaded Executor
@@ -141,7 +177,7 @@
      * Creates an Executor that uses a single worker thread operating
      * off an unbounded queue, and uses the provided ThreadFactory to
      * create a new thread when needed. Unlike the otherwise
-     * equivalent <tt>newFixedThreadPool(1, threadFactory)</tt> the
+     * equivalent {@code newFixedThreadPool(1, threadFactory)} the
      * returned executor is guaranteed not to be reconfigurable to use
      * additional threads.
      *
@@ -164,7 +200,7 @@
      * will reuse previously constructed threads when they are
      * available.  These pools will typically improve the performance
      * of programs that execute many short-lived asynchronous tasks.
-     * Calls to <tt>execute</tt> will reuse previously constructed
+     * Calls to {@code execute} will reuse previously constructed
      * threads if available. If no existing thread is available, a new
      * thread will be created and added to the pool. Threads that have
      * not been used for sixty seconds are terminated and removed from
@@ -206,7 +242,7 @@
      * subsequent tasks.)  Tasks are guaranteed to execute
      * sequentially, and no more than one task will be active at any
      * given time. Unlike the otherwise equivalent
-     * <tt>newScheduledThreadPool(1)</tt> the returned executor is
+     * {@code newScheduledThreadPool(1)} the returned executor is
      * guaranteed not to be reconfigurable to use additional threads.
      * @return the newly created scheduled executor
      */
@@ -223,7 +259,7 @@
      * place if needed to execute subsequent tasks.)  Tasks are
      * guaranteed to execute sequentially, and no more than one task
      * will be active at any given time. Unlike the otherwise
-     * equivalent <tt>newScheduledThreadPool(1, threadFactory)</tt>
+     * equivalent {@code newScheduledThreadPool(1, threadFactory)}
      * the returned executor is guaranteed not to be reconfigurable to
      * use additional threads.
      * @param threadFactory the factory to use when creating new
@@ -240,7 +276,7 @@
      * Creates a thread pool that can schedule commands to run after a
      * given delay, or to execute periodically.
      * @param corePoolSize the number of threads to keep in the pool,
-     * even if they are idle.
+     * even if they are idle
      * @return a newly created scheduled thread pool
      * @throws IllegalArgumentException if {@code corePoolSize < 0}
      */
@@ -252,9 +288,9 @@
      * Creates a thread pool that can schedule commands to run after a
      * given delay, or to execute periodically.
      * @param corePoolSize the number of threads to keep in the pool,
-     * even if they are idle.
+     * even if they are idle
      * @param threadFactory the factory to use when the executor
-     * creates a new thread.
+     * creates a new thread
      * @return a newly created scheduled thread pool
      * @throws IllegalArgumentException if {@code corePoolSize < 0}
      * @throws NullPointerException if threadFactory is null
@@ -264,7 +300,6 @@
         return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
     }
 
-
     /**
      * Returns an object that delegates all defined {@link
      * ExecutorService} methods to the given executor, but not any
@@ -272,7 +307,7 @@
      * casts. This provides a way to safely "freeze" configuration and
      * disallow tuning of a given concrete implementation.
      * @param executor the underlying implementation
-     * @return an <tt>ExecutorService</tt> instance
+     * @return an {@code ExecutorService} instance
      * @throws NullPointerException if executor null
      */
     public static ExecutorService unconfigurableExecutorService(ExecutorService executor) {
@@ -288,7 +323,7 @@
      * casts. This provides a way to safely "freeze" configuration and
      * disallow tuning of a given concrete implementation.
      * @param executor the underlying implementation
-     * @return a <tt>ScheduledExecutorService</tt> instance
+     * @return a {@code ScheduledExecutorService} instance
      * @throws NullPointerException if executor null
      */
     public static ScheduledExecutorService unconfigurableScheduledExecutorService(ScheduledExecutorService executor) {
@@ -303,9 +338,9 @@
      * same {@link ThreadGroup}. If there is a {@link
      * java.lang.SecurityManager}, it uses the group of {@link
      * System#getSecurityManager}, else the group of the thread
-     * invoking this <tt>defaultThreadFactory</tt> method. Each new
+     * invoking this {@code defaultThreadFactory} method. Each new
      * thread is created as a non-daemon thread with priority set to
-     * the smaller of <tt>Thread.NORM_PRIORITY</tt> and the maximum
+     * the smaller of {@code Thread.NORM_PRIORITY} and the maximum
      * priority permitted in the thread group.  New threads have names
      * accessible via {@link Thread#getName} of
      * <em>pool-N-thread-M</em>, where <em>N</em> is the sequence
@@ -324,11 +359,12 @@
      * Executors#defaultThreadFactory}, additionally setting the
      * AccessControlContext and contextClassLoader of new threads to
      * be the same as the thread invoking this
-     * <tt>privilegedThreadFactory</tt> method.  A new
-     * <tt>privilegedThreadFactory</tt> can be created within an
-     * {@link AccessController#doPrivileged} action setting the
-     * current thread's access control context to create threads with
-     * the selected permission settings holding within that action.
+     * {@code privilegedThreadFactory} method.  A new
+     * {@code privilegedThreadFactory} can be created within an
+     * {@link AccessController#doPrivileged AccessController.doPrivileged}
+     * action setting the current thread's access control context to
+     * create threads with the selected permission settings holding
+     * within that action.
      *
      * <p> Note that while tasks running within such threads will have
      * the same access control and class loader settings as the
@@ -337,17 +373,17 @@
      * java.lang.InheritableThreadLocal} values. If necessary,
      * particular values of thread locals can be set or reset before
      * any task runs in {@link ThreadPoolExecutor} subclasses using
-     * {@link ThreadPoolExecutor#beforeExecute}. Also, if it is
-     * necessary to initialize worker threads to have the same
-     * InheritableThreadLocal settings as some other designated
-     * thread, you can create a custom ThreadFactory in which that
-     * thread waits for and services requests to create others that
-     * will inherit its values.
+     * {@link ThreadPoolExecutor#beforeExecute(Thread, Runnable)}.
+     * Also, if it is necessary to initialize worker threads to have
+     * the same InheritableThreadLocal settings as some other
+     * designated thread, you can create a custom ThreadFactory in
+     * which that thread waits for and services requests to create
+     * others that will inherit its values.
      *
      * @return a thread factory
      * @throws AccessControlException if the current access control
      * context does not have permission to both get and set context
-     * class loader.
+     * class loader
      */
     public static ThreadFactory privilegedThreadFactory() {
         return new PrivilegedThreadFactory();
@@ -357,7 +393,7 @@
      * Returns a {@link Callable} object that, when
      * called, runs the given task and returns the given result.  This
      * can be useful when applying methods requiring a
-     * <tt>Callable</tt> to an otherwise resultless action.
+     * {@code Callable} to an otherwise resultless action.
      * @param task the task to run
      * @param result the result to return
      * @return a callable object
@@ -371,7 +407,7 @@
 
     /**
      * Returns a {@link Callable} object that, when
-     * called, runs the given task and returns <tt>null</tt>.
+     * called, runs the given task and returns {@code null}.
      * @param task the task to run
      * @return a callable object
      * @throws NullPointerException if task null
@@ -412,18 +448,17 @@
     }
 
     /**
-     * Returns a {@link Callable} object that will, when
-     * called, execute the given <tt>callable</tt> under the current
-     * access control context. This method should normally be
-     * invoked within an {@link AccessController#doPrivileged} action
-     * to create callables that will, if possible, execute under the
-     * selected permission settings holding within that action; or if
-     * not possible, throw an associated {@link
+     * Returns a {@link Callable} object that will, when called,
+     * execute the given {@code callable} under the current access
+     * control context. This method should normally be invoked within
+     * an {@link AccessController#doPrivileged AccessController.doPrivileged}
+     * action to create callables that will, if possible, execute
+     * under the selected permission settings holding within that
+     * action; or if not possible, throw an associated {@link
      * AccessControlException}.
      * @param callable the underlying task
      * @return a callable object
      * @throws NullPointerException if callable null
-     *
      */
     public static <T> Callable<T> privilegedCallable(Callable<T> callable) {
         if (callable == null)
@@ -432,22 +467,23 @@
     }
 
     /**
-     * Returns a {@link Callable} object that will, when
-     * called, execute the given <tt>callable</tt> under the current
-     * access control context, with the current context class loader
-     * as the context class loader. This method should normally be
-     * invoked within an {@link AccessController#doPrivileged} action
-     * to create callables that will, if possible, execute under the
-     * selected permission settings holding within that action; or if
-     * not possible, throw an associated {@link
+     * Returns a {@link Callable} object that will, when called,
+     * execute the given {@code callable} under the current access
+     * control context, with the current context class loader as the
+     * context class loader. This method should normally be invoked
+     * within an
+     * {@link AccessController#doPrivileged AccessController.doPrivileged}
+     * action to create callables that will, if possible, execute
+     * under the selected permission settings holding within that
+     * action; or if not possible, throw an associated {@link
      * AccessControlException}.
+     *
      * @param callable the underlying task
-     *
      * @return a callable object
      * @throws NullPointerException if callable null
      * @throws AccessControlException if the current access control
      * context does not have permission to both set and get context
-     * class loader.
+     * class loader
      */
     public static <T> Callable<T> privilegedCallableUsingCurrentClassLoader(Callable<T> callable) {
         if (callable == null)
@@ -699,7 +735,6 @@
         }
     }
 
-
     /** Cannot instantiate. */
     private Executors() {}
 }
--- a/src/share/classes/java/util/concurrent/ForkJoinPool.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/ForkJoinPool.java	Wed Feb 20 15:42:21 2013 -0800
@@ -35,6 +35,7 @@
 
 package java.util.concurrent;
 
+import java.lang.Thread.UncaughtExceptionHandler;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
@@ -104,38 +105,44 @@
  * there is little difference among choice of methods.
  *
  * <table BORDER CELLPADDING=3 CELLSPACING=1>
+ * <caption>Summary of task execution methods</caption>
  *  <tr>
  *    <td></td>
  *    <td ALIGN=CENTER> <b>Call from non-fork/join clients</b></td>
  *    <td ALIGN=CENTER> <b>Call from within fork/join computations</b></td>
  *  </tr>
  *  <tr>
- *    <td> <b>Arrange async execution</td>
+ *    <td> <b>Arrange async execution</b></td>
  *    <td> {@link #execute(ForkJoinTask)}</td>
  *    <td> {@link ForkJoinTask#fork}</td>
  *  </tr>
  *  <tr>
- *    <td> <b>Await and obtain result</td>
+ *    <td> <b>Await and obtain result</b></td>
  *    <td> {@link #invoke(ForkJoinTask)}</td>
  *    <td> {@link ForkJoinTask#invoke}</td>
  *  </tr>
  *  <tr>
- *    <td> <b>Arrange exec and obtain Future</td>
+ *    <td> <b>Arrange exec and obtain Future</b></td>
  *    <td> {@link #submit(ForkJoinTask)}</td>
  *    <td> {@link ForkJoinTask#fork} (ForkJoinTasks <em>are</em> Futures)</td>
  *  </tr>
  * </table>
  *
  * <p>The common pool is by default constructed with default
- * parameters, but these may be controlled by setting three {@link
- * System#getProperty system properties} with prefix {@code
- * java.util.concurrent.ForkJoinPool.common}: {@code parallelism} --
- * an integer greater than zero, {@code threadFactory} -- the class
- * name of a {@link ForkJoinWorkerThreadFactory}, and {@code
- * exceptionHandler} -- the class name of a {@link
- * java.lang.Thread.UncaughtExceptionHandler
- * Thread.UncaughtExceptionHandler}. Upon any error in establishing
- * these settings, default parameters are used.
+ * parameters, but these may be controlled by setting three
+ * {@linkplain System#getProperty system properties}:
+ * <ul>
+ * <li>{@code java.util.concurrent.ForkJoinPool.common.parallelism}
+ * - the parallelism level, a non-negative integer
+ * <li>{@code java.util.concurrent.ForkJoinPool.common.threadFactory}
+ * - the class name of a {@link ForkJoinWorkerThreadFactory}
+ * <li>{@code java.util.concurrent.ForkJoinPool.common.exceptionHandler}
+ * - the class name of a {@link UncaughtExceptionHandler}
+ * </ul>
+ * Upon any error in establishing these settings, default parameters
+ * are used. It is possible to disable or limit the use of threads in
+ * the common pool by setting the parallelism property to zero, and/or
+ * using a factory that may return {@code null}.
  *
  * <p><b>Implementation notes</b>: This implementation restricts the
  * maximum number of running threads to 32767. Attempts to create
@@ -225,18 +232,18 @@
      * for work-stealing (this would contaminate lifo/fifo
      * processing). Instead, we randomly associate submission queues
      * with submitting threads, using a form of hashing.  The
-     * ThreadLocal Submitter class contains a value initially used as
-     * a hash code for choosing existing queues, but may be randomly
-     * repositioned upon contention with other submitters.  In
-     * essence, submitters act like workers except that they are
-     * restricted to executing local tasks that they submitted (or in
-     * the case of CountedCompleters, others with the same root task).
-     * However, because most shared/external queue operations are more
-     * expensive than internal, and because, at steady state, external
-     * submitters will compete for CPU with workers, ForkJoinTask.join
-     * and related methods disable them from repeatedly helping to
-     * process tasks if all workers are active.  Insertion of tasks in
-     * shared mode requires a lock (mainly to protect in the case of
+     * ThreadLocalRandom probe value serves as a hash code for
+     * choosing existing queues, and may be randomly repositioned upon
+     * contention with other submitters.  In essence, submitters act
+     * like workers except that they are restricted to executing local
+     * tasks that they submitted (or in the case of CountedCompleters,
+     * others with the same root task).  However, because most
+     * shared/external queue operations are more expensive than
+     * internal, and because, at steady state, external submitters
+     * will compete for CPU with workers, ForkJoinTask.join and
+     * related methods disable them from repeatedly helping to process
+     * tasks if all workers are active.  Insertion of tasks in shared
+     * mode requires a lock (mainly to protect in the case of
      * resizing) but we use only a simple spinlock (using bits in
      * field qlock), because submitters encountering a busy queue move
      * on to try or create other queues -- they block only when
@@ -548,6 +555,7 @@
          *
          * @param pool the pool this thread works in
          * @throws NullPointerException if the pool is null
+         * @return the new worker thread
          */
         public ForkJoinWorkerThread newThread(ForkJoinPool pool);
     }
@@ -564,26 +572,6 @@
     }
 
     /**
-     * Per-thread records for threads that submit to pools. Currently
-     * holds only pseudo-random seed / index that is used to choose
-     * submission queues in method externalPush. In the future, this may
-     * also incorporate a means to implement different task rejection
-     * and resubmission policies.
-     *
-     * Seeds for submitters and workers/workQueues work in basically
-     * the same way but are initialized and updated using slightly
-     * different mechanics. Both are initialized using the same
-     * approach as in class ThreadLocal, where successive values are
-     * unlikely to collide with previous values. Seeds are then
-     * randomly modified upon collisions using xorshifts, which
-     * requires a non-zero seed.
-     */
-    static final class Submitter {
-        int seed;
-        Submitter(int s) { seed = s; }
-    }
-
-    /**
      * Class for artificial tasks that are used to replace the target
      * of local joins if they are removed from an interior queue slot
      * in WorkQueue.tryRemoveAndExec. We don't need the proxy to
@@ -737,7 +725,7 @@
          * shared-queue version is embedded in method externalPush.)
          *
          * @param task the task. Caller must ensure non-null.
-         * @throw RejectedExecutionException if array cannot be resized
+         * @throws RejectedExecutionException if array cannot be resized
          */
         final void push(ForkJoinTask<?> task) {
             ForkJoinTask<?>[] a; ForkJoinPool p;
@@ -936,7 +924,7 @@
          * or any other cancelled task. Returns (true) on any CAS
          * or consistency check failure so caller can retry.
          *
-         * @return false if no progress can be made, else true;
+         * @return false if no progress can be made, else true
          */
         final boolean tryRemoveAndExec(ForkJoinTask<?> task) {
             boolean stat = true, removed = false, empty = true;
@@ -981,7 +969,7 @@
 
         /**
          * Polls for and executes the given task or any other task in
-         * its CountedCompleter computation
+         * its CountedCompleter computation.
          */
         final boolean pollAndExecCC(ForkJoinTask<?> root) {
             ForkJoinTask<?>[] a; int b; Object o;
@@ -1055,7 +1043,6 @@
         private static final int ABASE;
         private static final int ASHIFT;
         static {
-            int s;
             try {
                 U = sun.misc.Unsafe.getUnsafe();
                 Class<?> k = WorkQueue.class;
@@ -1063,13 +1050,13 @@
                 QLOCK = U.objectFieldOffset
                     (k.getDeclaredField("qlock"));
                 ABASE = U.arrayBaseOffset(ak);
-                s = U.arrayIndexScale(ak);
+                int scale = U.arrayIndexScale(ak);
+                if ((scale & (scale - 1)) != 0)
+                    throw new Error("data type scale not a power of two");
+                ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
             } catch (Exception e) {
                 throw new Error(e);
             }
-            if ((s & (s-1)) != 0)
-                throw new Error("data type scale not a power of two");
-            ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
         }
     }
 
@@ -1083,15 +1070,6 @@
         defaultForkJoinWorkerThreadFactory;
 
     /**
-     * Per-thread submission bookkeeping. Shared across all pools
-     * to reduce ThreadLocal pollution and because random motion
-     * to avoid contention in one pool is likely to hold for others.
-     * Lazily initialized on first submission (but null-checked
-     * in other contexts to avoid unnecessary initialization).
-     */
-    static final ThreadLocal<Submitter> submitters;
-
-    /**
      * Permission required for callers of methods that may start or
      * kill threads.
      */
@@ -1103,12 +1081,15 @@
      * to paranoically avoid potential initialization circularities
      * as well as to simplify generated code.
      */
-    static final ForkJoinPool commonPool;
+    static final ForkJoinPool common;
 
     /**
-     * Common pool parallelism. Must equal commonPool.parallelism.
+     * Common pool parallelism. To allow simpler use and management
+     * when common pool threads are disabled, we allow the underlying
+     * common.config field to be zero, but in that case still report
+     * parallelism as 1 to reflect resulting caller-runs mechanics.
      */
-    static final int commonPoolParallelism;
+    static final int commonParallelism;
 
     /**
      * Sequence number for creating workerNamePrefix.
@@ -1116,8 +1097,8 @@
     private static int poolNumberSequence;
 
     /**
-     * Return the next sequence number. We don't expect this to
-     * ever contend so use simple builtin sync.
+     * Returns the next sequence number. We don't expect this to
+     * ever contend, so use simple builtin sync.
      */
     private static final synchronized int nextPoolId() {
         return ++poolNumberSequence;
@@ -1161,7 +1142,7 @@
      */
     private static final int SEED_INCREMENT = 0x61c88647;
 
-    /**
+    /*
      * Bits and masks for control variables
      *
      * Field ctl is a long packed with:
@@ -1268,39 +1249,28 @@
     final int config;                          // mode and parallelism level
     WorkQueue[] workQueues;                    // main registry
     final ForkJoinWorkerThreadFactory factory;
-    final Thread.UncaughtExceptionHandler ueh; // per-worker UEH
+    final UncaughtExceptionHandler ueh;        // per-worker UEH
     final String workerNamePrefix;             // to create worker name string
 
     volatile Object pad10, pad11, pad12, pad13, pad14, pad15, pad16, pad17;
     volatile Object pad18, pad19, pad1a, pad1b;
 
-    /*
+    /**
      * Acquires the plock lock to protect worker array and related
      * updates. This method is called only if an initial CAS on plock
-     * fails. This acts as a spinLock for normal cases, but falls back
+     * fails. This acts as a spinlock for normal cases, but falls back
      * to builtin monitor to block when (rarely) needed. This would be
      * a terrible idea for a highly contended lock, but works fine as
      * a more conservative alternative to a pure spinlock.
      */
     private int acquirePlock() {
-        int spins = PL_SPINS, r = 0, ps, nps;
+        int spins = PL_SPINS, ps, nps;
         for (;;) {
             if (((ps = plock) & PL_LOCK) == 0 &&
                 U.compareAndSwapInt(this, PLOCK, ps, nps = ps + PL_LOCK))
                 return nps;
-            else if (r == 0) { // randomize spins if possible
-                Thread t = Thread.currentThread(); WorkQueue w; Submitter z;
-                if ((t instanceof ForkJoinWorkerThread) &&
-                    (w = ((ForkJoinWorkerThread)t).workQueue) != null)
-                    r = w.seed;
-                else if ((z = submitters.get()) != null)
-                    r = z.seed;
-                else
-                    r = 1;
-            }
             else if (spins >= 0) {
-                r ^= r << 1; r ^= r >>> 3; r ^= r << 10; // xorshift
-                if (r >= 0)
+                if (ThreadLocalRandom.nextSecondarySeed() >= 0)
                     --spins;
             }
             else if (U.compareAndSwapInt(this, PLOCK, ps, ps | PL_SIGNAL)) {
@@ -1332,39 +1302,6 @@
     }
 
     /**
-     * Performs secondary initialization, called when plock is zero.
-     * Creates workQueue array and sets plock to a valid value.  The
-     * lock body must be exception-free (so no try/finally) so we
-     * optimistically allocate new array outside the lock and throw
-     * away if (very rarely) not needed. (A similar tactic is used in
-     * fullExternalPush.)  Because the plock seq value can eventually
-     * wrap around zero, this method harmlessly fails to reinitialize
-     * if workQueues exists, while still advancing plock.
-     *
-     * Additionally tries to create the first worker.
-     */
-    private void initWorkers() {
-        WorkQueue[] ws, nws; int ps;
-        int p = config & SMASK;        // find power of two table size
-        int n = (p > 1) ? p - 1 : 1;   // ensure at least 2 slots
-        n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16;
-        n = (n + 1) << 1;
-        if ((ws = workQueues) == null || ws.length == 0)
-            nws = new WorkQueue[n];
-        else
-            nws = null;
-        if (((ps = plock) & PL_LOCK) != 0 ||
-            !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
-            ps = acquirePlock();
-        if (((ws = workQueues) == null || ws.length == 0) && nws != null)
-            workQueues = nws;
-        int nps = (ps & SHUTDOWN) | ((ps + PL_LOCK) & ~SHUTDOWN);
-        if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
-            releasePlock(nps);
-        tryAddWorker();
-    }
-
-    /**
      * Tries to create and start one worker if fewer than target
      * parallelism level exist. Adjusts counts etc on failure.
      */
@@ -1406,7 +1343,7 @@
      * @return the worker's queue
      */
     final WorkQueue registerWorker(ForkJoinWorkerThread wt) {
-        Thread.UncaughtExceptionHandler handler; WorkQueue[] ws; int s, ps;
+        UncaughtExceptionHandler handler; WorkQueue[] ws; int s, ps;
         wt.setDaemon(true);
         if ((handler = ueh) != null)
             wt.setUncaughtExceptionHandler(handler);
@@ -1450,7 +1387,7 @@
      * array, and adjusts counts. If pool is shutting down, tries to
      * complete termination.
      *
-     * @param wt the worker thread or null if construction failed
+     * @param wt the worker thread, or null if construction failed
      * @param ex the exception causing failure, or null if none
      */
     final void deregisterWorker(ForkJoinWorkerThread wt, Throwable ex) {
@@ -1489,7 +1426,7 @@
                 if (e > 0) {             // activate or create replacement
                     if ((ws = workQueues) == null ||
                         (i = e & SMASK) >= ws.length ||
-                        (v = ws[i]) != null)
+                        (v = ws[i]) == null)
                         break;
                     long nc = (((long)(v.nextWait & E_MASK)) |
                                ((long)(u + UAC_UNIT) << 32));
@@ -1526,10 +1463,10 @@
      * @param task the task. Caller must ensure non-null.
      */
     final void externalPush(ForkJoinTask<?> task) {
-        WorkQueue[] ws; WorkQueue q; Submitter z; int m; ForkJoinTask<?>[] a;
-        if ((z = submitters.get()) != null && plock > 0 &&
+        WorkQueue[] ws; WorkQueue q; int z, m; ForkJoinTask<?>[] a;
+        if ((z = ThreadLocalRandom.getProbe()) != 0 && plock > 0 &&
             (ws = workQueues) != null && (m = (ws.length - 1)) >= 0 &&
-            (q = ws[m & z.seed & SQMASK]) != null &&
+            (q = ws[m & z & SQMASK]) != null &&
             U.compareAndSwapInt(q, QLOCK, 0, 1)) { // lock
             int b = q.base, s = q.top, n, an;
             if ((a = q.array) != null && (an = a.length) > (n = s + 1 - b)) {
@@ -1549,34 +1486,48 @@
     /**
      * Full version of externalPush. This method is called, among
      * other times, upon the first submission of the first task to the
-     * pool, so must perform secondary initialization (via
-     * initWorkers). It also detects first submission by an external
-     * thread by looking up its ThreadLocal, and creates a new shared
-     * queue if the one at index if empty or contended. The plock lock
-     * body must be exception-free (so no try/finally) so we
-     * optimistically allocate new queues outside the lock and throw
-     * them away if (very rarely) not needed.
+     * pool, so must perform secondary initialization.  It also
+     * detects first submission by an external thread by looking up
+     * its ThreadLocal, and creates a new shared queue if the one at
+     * index if empty or contended. The plock lock body must be
+     * exception-free (so no try/finally) so we optimistically
+     * allocate new queues outside the lock and throw them away if
+     * (very rarely) not needed.
+     *
+     * Secondary initialization occurs when plock is zero, to create
+     * workQueue array and set plock to a valid value.  This lock body
+     * must also be exception-free. Because the plock seq value can
+     * eventually wrap around zero, this method harmlessly fails to
+     * reinitialize if workQueues exists, while still advancing plock.
      */
     private void fullExternalPush(ForkJoinTask<?> task) {
-        int r = 0; // random index seed
-        for (Submitter z = submitters.get();;) {
+        int r;
+        if ((r = ThreadLocalRandom.getProbe()) == 0) {
+            ThreadLocalRandom.localInit();
+            r = ThreadLocalRandom.getProbe();
+            }
+        for (;;) {
             WorkQueue[] ws; WorkQueue q; int ps, m, k;
-            if (z == null) {
-                if (U.compareAndSwapInt(this, INDEXSEED, r = indexSeed,
-                                        r += SEED_INCREMENT) && r != 0)
-                    submitters.set(z = new Submitter(r));
-            }
-            else if (r == 0) {               // move to a different index
-                r = z.seed;
-                r ^= r << 13;                // same xorshift as WorkQueues
-                r ^= r >>> 17;
-                z.seed = r ^ (r << 5);
-            }
-            else if ((ps = plock) < 0)
+            boolean move = false;
+            if ((ps = plock) < 0)
                 throw new RejectedExecutionException();
             else if (ps == 0 || (ws = workQueues) == null ||
-                     (m = ws.length - 1) < 0)
-                initWorkers();
+                     (m = ws.length - 1) < 0) { // initialize workQueues
+                int p = config & SMASK;         // find power of two table size
+                int n = (p > 1) ? p - 1 : 1;    // ensure at least 2 slots
+                n |= n >>> 1; n |= n >>> 2;  n |= n >>> 4;
+                n |= n >>> 8; n |= n >>> 16; n = (n + 1) << 1;
+                WorkQueue[] nws = ((ws = workQueues) == null || ws.length == 0 ?
+                                   new WorkQueue[n] : null);
+                if (((ps = plock) & PL_LOCK) != 0 ||
+                    !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
+                    ps = acquirePlock();
+                if (((ws = workQueues) == null || ws.length == 0) && nws != null)
+                    workQueues = nws;
+                int nps = (ps & SHUTDOWN) | ((ps + PL_LOCK) & ~SHUTDOWN);
+                if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
+                    releasePlock(nps);
+            }
             else if ((q = ws[k = r & m & SQMASK]) != null) {
                 if (q.qlock == 0 && U.compareAndSwapInt(q, QLOCK, 0, 1)) {
                     ForkJoinTask<?>[] a = q.array;
@@ -1598,7 +1549,7 @@
                         return;
                     }
                 }
-                r = 0; // move on failure
+                move = true; // move on failure
             }
             else if (((ps = plock) & PL_LOCK) == 0) { // create new queue
                 q = new WorkQueue(this, null, SHARED_QUEUE, r);
@@ -1612,7 +1563,9 @@
                     releasePlock(nps);
             }
             else
-                r = 0; // try elsewhere while lock held
+                move = true; // move if busy
+            if (move)
+                r = ThreadLocalRandom.advanceProbe(r);
         }
     }
 
@@ -1703,7 +1656,7 @@
      * park awaiting signal, else lingering to help scan and signal.
      *
      * * If a non-empty queue discovered or left as a hint,
-     * help wake up other workers before return
+     * help wake up other workers before return.
      *
      * @param w the worker (via its WorkQueue)
      * @return a task or null if none found
@@ -1758,14 +1711,13 @@
                         else if ((int)(c >> AC_SHIFT) == 1 - (config & SMASK))
                             idleAwaitWork(w, nc, c);
                     }
-                    else if (w.eventCount < 0 && !tryTerminate(false, false) &&
-                             ctl == c) {         // block
+                    else if (w.eventCount < 0 && ctl == c) {
                         Thread wt = Thread.currentThread();
                         Thread.interrupted();    // clear status
                         U.putObject(wt, PARKBLOCKER, this);
                         w.parker = wt;           // emulate LockSupport.park
                         if (w.eventCount < 0)    // recheck
-                            U.park(false, 0L);
+                            U.park(false, 0L);   // block
                         w.parker = null;
                         U.putObject(wt, PARKBLOCKER, null);
                     }
@@ -1774,7 +1726,7 @@
                     (ws = workQueues) != null && h < ws.length &&
                     (q = ws[h]) != null) {      // signal others before retry
                     WorkQueue v; Thread p; int u, i, s;
-                    for (int n = (config & SMASK) >>> 1;;) {
+                    for (int n = (config & SMASK) - 1;;) {
                         int idleCount = (w.eventCount < 0) ? 0 : -1;
                         if (((s = idleCount - q.base + q.top) <= n &&
                              (n = s) <= 0) ||
@@ -1814,7 +1766,8 @@
      */
     private void idleAwaitWork(WorkQueue w, long currentCtl, long prevCtl) {
         if (w != null && w.eventCount < 0 &&
-            !tryTerminate(false, false) && (int)prevCtl != 0) {
+            !tryTerminate(false, false) && (int)prevCtl != 0 &&
+            ctl == currentCtl) {
             int dc = -(short)(currentCtl >>> TC_SHIFT);
             long parkTime = dc < 0 ? FAST_IDLE_TIMEOUT: (dc + 1) * IDLE_TIMEOUT;
             long deadline = System.nanoTime() + parkTime - TIMEOUT_SLOP;
@@ -1832,6 +1785,7 @@
                 if (deadline - System.nanoTime() <= 0L &&
                     U.compareAndSwapLong(this, CTL, currentCtl, prevCtl)) {
                     w.eventCount = (w.eventCount + E_SEQ) | E_MASK;
+                    w.hint = -1;
                     w.qlock = -1;   // shrink
                     break;
                 }
@@ -1973,7 +1927,6 @@
      * @param task the task to join
      * @param mode if shared, exit upon completing any task
      * if all workers are active
-     *
      */
     private int helpComplete(ForkJoinTask<?> task, int mode) {
         WorkQueue[] ws; WorkQueue q; int m, n, s, u;
@@ -2125,29 +2078,22 @@
 
     /**
      * Returns a (probably) non-empty steal queue, if one is found
-     * during a random, then cyclic scan, else null.  This method must
-     * be retried by caller if, by the time it tries to use the queue,
-     * it is empty.
+     * during a scan, else null.  This method must be retried by
+     * caller if, by the time it tries to use the queue, it is empty.
      * @param r a (random) seed for scanning
      */
     private WorkQueue findNonEmptyStealQueue(int r) {
-        for (WorkQueue[] ws;;) {
-            int ps = plock, m, n;
-            if ((ws = workQueues) == null || (m = ws.length - 1) < 1)
-                return null;
-            for (int j = (m + 1) << 2; ;) {
-                WorkQueue q = ws[(((r + j) << 1) | 1) & m];
-                if (q != null && (n = q.base - q.top) < 0) {
-                    if (n < -1)
-                        signalWork(q);
+        for (;;) {
+            int ps = plock, m; WorkQueue[] ws; WorkQueue q;
+            if ((ws = workQueues) != null && (m = ws.length - 1) >= 0) {
+                for (int j = (m + 1) << 2; j >= 0; --j) {
+                    if ((q = ws[(((r + j) << 1) | 1) & m]) != null &&
+                        q.base - q.top < 0)
                     return q;
                 }
-                else if (--j < 0) {
+            }
                     if (plock == ps)
                         return null;
-                    break;
-                }
-            }
         }
     }
 
@@ -2159,37 +2105,34 @@
      */
     final void helpQuiescePool(WorkQueue w) {
         for (boolean active = true;;) {
-            ForkJoinTask<?> localTask; // exhaust local queue
-            while ((localTask = w.nextLocalTask()) != null)
-                localTask.doExec();
-            // Similar to loop in scan(), but ignoring submissions
-            WorkQueue q = findNonEmptyStealQueue(w.nextSeed());
-            if (q != null) {
-                ForkJoinTask<?> t; int b;
+            long c; WorkQueue q; ForkJoinTask<?> t; int b;
+            while ((t = w.nextLocalTask()) != null) {
+                if (w.base - w.top < 0)
+                    signalWork(w);
+                t.doExec();
+            }
+            if ((q = findNonEmptyStealQueue(w.nextSeed())) != null) {
                 if (!active) {      // re-establish active count
-                    long c;
                     active = true;
                     do {} while (!U.compareAndSwapLong
                                  (this, CTL, c = ctl, c + AC_UNIT));
                 }
-                if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
+                if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null) {
+                    if (q.base - q.top < 0)
+                        signalWork(q);
                     w.runSubtask(t);
             }
-            else {
-                long c;
-                if (active) {       // decrement active count without queuing
+                }
+            else if (active) {       // decrement active count without queuing
+                long nc = (c = ctl) - AC_UNIT;
+                if ((int)(nc >> AC_SHIFT) + (config & SMASK) == 0)
+                    return;          // bypass decrement-then-increment
+                if (U.compareAndSwapLong(this, CTL, c, nc))
                     active = false;
-                    do {} while (!U.compareAndSwapLong
-                                 (this, CTL, c = ctl, c -= AC_UNIT));
-                }
-                else
-                    c = ctl;        // re-increment on exit
-                if ((int)(c >> AC_SHIFT) + (config & SMASK) == 0) {
-                    do {} while (!U.compareAndSwapLong
-                                 (this, CTL, c = ctl, c + AC_UNIT));
-                    break;
-                }
             }
+            else if ((int)((c = ctl) >> AC_SHIFT) + (config & SMASK) == 0 &&
+                     U.compareAndSwapLong(this, CTL, c, c + AC_UNIT))
+                return;
         }
     }
 
@@ -2205,10 +2148,13 @@
                 return t;
             if ((q = findNonEmptyStealQueue(w.nextSeed())) == null)
                 return null;
-            if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null)
+            if ((b = q.base) - q.top < 0 && (t = q.pollAt(b)) != null) {
+                if (q.base - q.top < 0)
+                    signalWork(q);
                 return t;
         }
     }
+    }
 
     /**
      * Returns a cheap heuristic guide for task partitioning when
@@ -2235,7 +2181,7 @@
      * producing extra tasks amortizes the uncertainty of progress and
      * diffusion assumptions.
      *
-     * So, users will want to use values larger, but not much larger
+     * So, users will want to use values larger (but not much larger)
      * than 1 to both smooth over transient shortages and hedge
      * against uneven progress; as traded off against the cost of
      * extra task overhead. We leave the user to pick a threshold
@@ -2288,8 +2234,19 @@
      * @return true if now terminating or terminated
      */
     private boolean tryTerminate(boolean now, boolean enable) {
-        if (this == commonPool)                     // cannot shut down
+        int ps;
+        if (this == common)                    // cannot shut down
             return false;
+        if ((ps = plock) >= 0) {                   // enable by setting plock
+            if (!enable)
+                return false;
+            if ((ps & PL_LOCK) != 0 ||
+                !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
+                ps = acquirePlock();
+            int nps = ((ps + PL_LOCK) & ~SHUTDOWN) | SHUTDOWN;
+            if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
+                releasePlock(nps);
+        }
         for (long c;;) {
             if (((c = ctl) & STOP_BIT) != 0) {      // already terminating
                 if ((short)(c >>> TC_SHIFT) == -(config & SMASK)) {
@@ -2299,34 +2256,27 @@
                 }
                 return true;
             }
-            if (plock >= 0) {                       // not yet enabled
-                int ps;
-                if (!enable)
+            if (!now) {                             // check if idle & no tasks
+                WorkQueue[] ws; WorkQueue w;
+                if ((int)(c >> AC_SHIFT) != -(config & SMASK))
                     return false;
-                if (((ps = plock) & PL_LOCK) != 0 ||
-                    !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
-                    ps = acquirePlock();
-                if (!U.compareAndSwapInt(this, PLOCK, ps, SHUTDOWN))
-                    releasePlock(SHUTDOWN);
-            }
-            if (!now) {                             // check if idle & no tasks
-                if ((int)(c >> AC_SHIFT) != -(config & SMASK) ||
-                    hasQueuedSubmissions())
-                    return false;
-                // Check for unqueued inactive workers. One pass suffices.
-                WorkQueue[] ws = workQueues; WorkQueue w;
-                if (ws != null) {
-                    for (int i = 1; i < ws.length; i += 2) {
-                        if ((w = ws[i]) != null && w.eventCount >= 0)
+                if ((ws = workQueues) != null) {
+                    for (int i = 0; i < ws.length; ++i) {
+                        if ((w = ws[i]) != null) {
+                            if (!w.isEmpty()) {    // signal unprocessed tasks
+                                signalWork(w);
                             return false;
                     }
+                            if ((i & 1) != 0 && w.eventCount >= 0)
+                                return false;      // unqueued inactive worker
+                        }
+                    }
                 }
             }
             if (U.compareAndSwapLong(this, CTL, c, c | STOP_BIT)) {
                 for (int pass = 0; pass < 3; ++pass) {
-                    WorkQueue[] ws = workQueues;
-                    if (ws != null) {
-                        WorkQueue w; Thread wt;
+                    WorkQueue[] ws; WorkQueue w; Thread wt;
+                    if ((ws = workQueues) != null) {
                         int n = ws.length;
                         for (int i = 0; i < n; ++i) {
                             if ((w = ws[i]) != null) {
@@ -2337,7 +2287,7 @@
                                         if (!wt.isInterrupted()) {
                                             try {
                                                 wt.interrupt();
-                                            } catch (SecurityException ignore) {
+                                            } catch (Throwable ignore) {
                                             }
                                         }
                                         U.unpark(wt);
@@ -2348,7 +2298,7 @@
                         // Wake up workers parked on event queue
                         int i, e; long cc; Thread p;
                         while ((e = (int)(cc = ctl) & E_MASK) != 0 &&
-                               (i = e & SMASK) < n &&
+                               (i = e & SMASK) < n && i >= 0 &&
                                (w = ws[i]) != null) {
                             long nc = ((long)(w.nextWait & E_MASK) |
                                        ((cc + AC_UNIT) & AC_MASK) |
@@ -2374,26 +2324,26 @@
      * least one task.
      */
     static WorkQueue commonSubmitterQueue() {
-        ForkJoinPool p; WorkQueue[] ws; int m; Submitter z;
-        return ((z = submitters.get()) != null &&
-                (p = commonPool) != null &&
+        ForkJoinPool p; WorkQueue[] ws; int m, z;
+        return ((z = ThreadLocalRandom.getProbe()) != 0 &&
+                (p = common) != null &&
                 (ws = p.workQueues) != null &&
                 (m = ws.length - 1) >= 0) ?
-            ws[m & z.seed & SQMASK] : null;
+            ws[m & z & SQMASK] : null;
     }
 
     /**
      * Tries to pop the given task from submitter's queue in common pool.
      */
     static boolean tryExternalUnpush(ForkJoinTask<?> t) {
-        ForkJoinPool p; WorkQueue[] ws; WorkQueue q; Submitter z;
-        ForkJoinTask<?>[] a;  int m, s;
+        ForkJoinPool p; WorkQueue[] ws; WorkQueue q;
+        ForkJoinTask<?>[] a;  int m, s, z;
         if (t != null &&
-            (z = submitters.get()) != null &&
-            (p = commonPool) != null &&
+            (z = ThreadLocalRandom.getProbe()) != 0 &&
+            (p = common) != null &&
             (ws = p.workQueues) != null &&
             (m = ws.length - 1) >= 0 &&
-            (q = ws[m & z.seed & SQMASK]) != null &&
+            (q = ws[m & z & SQMASK]) != null &&
             (s = q.top) != q.base &&
             (a = q.array) != null) {
             long j = (((a.length - 1) & (s - 1)) << ASHIFT) + ABASE;
@@ -2445,7 +2395,8 @@
                 if (task != null)
                     task.doExec();
                 if (root.status < 0 ||
-                    (u = (int)(ctl >>> 32)) >= 0 || (u >> UAC_SHIFT) >= 0)
+                    (config != 0 &&
+                     ((u = (int)(ctl >>> 32)) >= 0 || (u >> UAC_SHIFT) >= 0)))
                     break;
                 if (task == null) {
                     helpSignal(root, q.poolIndex);
@@ -2463,14 +2414,14 @@
      */
     static void externalHelpJoin(ForkJoinTask<?> t) {
         // Some hard-to-avoid overlap with tryExternalUnpush
-        ForkJoinPool p; WorkQueue[] ws; WorkQueue q, w; Submitter z;
-        ForkJoinTask<?>[] a;  int m, s, n;
+        ForkJoinPool p; WorkQueue[] ws; WorkQueue q, w;
+        ForkJoinTask<?>[] a;  int m, s, n, z;
         if (t != null &&
-            (z = submitters.get()) != null &&
-            (p = commonPool) != null &&
+            (z = ThreadLocalRandom.getProbe()) != 0 &&
+            (p = common) != null &&
             (ws = p.workQueues) != null &&
             (m = ws.length - 1) >= 0 &&
-            (q = ws[m & z.seed & SQMASK]) != null &&
+            (q = ws[m & z & SQMASK]) != null &&
             (a = q.array) != null) {
             int am = a.length - 1;
             if ((s = q.top) != q.base) {
@@ -2496,18 +2447,6 @@
         }
     }
 
-    /**
-     * Restricted version of helpQuiescePool for external callers
-     */
-    static void externalHelpQuiescePool() {
-        ForkJoinPool p; ForkJoinTask<?> t; WorkQueue q; int b;
-        if ((p = commonPool) != null &&
-            (q = p.findNonEmptyStealQueue(1)) != null &&
-            (b = q.base) - q.top < 0 &&
-            (t = q.pollAt(b)) != null)
-            t.doExec();
-    }
-
     // Exported methods
 
     // Constructors
@@ -2524,7 +2463,7 @@
      *         java.lang.RuntimePermission}{@code ("modifyThread")}
      */
     public ForkJoinPool() {
-        this(Runtime.getRuntime().availableProcessors(),
+        this(Math.min(MAX_CAP, Runtime.getRuntime().availableProcessors()),
              defaultForkJoinWorkerThreadFactory, null, false);
     }
 
@@ -2572,50 +2511,63 @@
      */
     public ForkJoinPool(int parallelism,
                         ForkJoinWorkerThreadFactory factory,
-                        Thread.UncaughtExceptionHandler handler,
+                        UncaughtExceptionHandler handler,
                         boolean asyncMode) {
+        this(checkParallelism(parallelism),
+             checkFactory(factory),
+             handler,
+             asyncMode,
+             "ForkJoinPool-" + nextPoolId() + "-worker-");
         checkPermission();
+    }
+
+    private static int checkParallelism(int parallelism) {
+        if (parallelism <= 0 || parallelism > MAX_CAP)
+            throw new IllegalArgumentException();
+        return parallelism;
+    }
+
+    private static ForkJoinWorkerThreadFactory checkFactory
+        (ForkJoinWorkerThreadFactory factory) {
         if (factory == null)
             throw new NullPointerException();
-        if (parallelism <= 0 || parallelism > MAX_CAP)
-            throw new IllegalArgumentException();
+        return factory;
+    }
+
+    /**
+     * Creates a {@code ForkJoinPool} with the given parameters, without
+     * any security checks or parameter validation.  Invoked directly by
+     * makeCommonPool.
+     */
+    private ForkJoinPool(int parallelism,
+                 ForkJoinWorkerThreadFactory factory,
+                         UncaughtExceptionHandler handler,
+                         boolean asyncMode,
+                         String workerNamePrefix) {
+        this.workerNamePrefix = workerNamePrefix;
         this.factory = factory;
         this.ueh = handler;
         this.config = parallelism | (asyncMode ? (FIFO_QUEUE << 16) : 0);
         long np = (long)(-parallelism); // offset ctl counts
         this.ctl = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
-        int pn = nextPoolId();
-        StringBuilder sb = new StringBuilder("ForkJoinPool-");
-        sb.append(Integer.toString(pn));
-        sb.append("-worker-");
-        this.workerNamePrefix = sb.toString();
-    }
-
-    /**
-     * Constructor for common pool, suitable only for static initialization.
-     * Basically the same as above, but uses smallest possible initial footprint.
-     */
-    ForkJoinPool(int parallelism, long ctl,
-                 ForkJoinWorkerThreadFactory factory,
-                 Thread.UncaughtExceptionHandler handler) {
-        this.config = parallelism;
-        this.ctl = ctl;
-        this.factory = factory;
-        this.ueh = handler;
-        this.workerNamePrefix = "ForkJoinPool.commonPool-worker-";
     }
 
     /**
      * Returns the common pool instance. This pool is statically
-     * constructed; its run state is unaffected by attempts to
-     * {@link #shutdown} or {@link #shutdownNow}.
+     * constructed; its run state is unaffected by attempts to {@link
+     * #shutdown} or {@link #shutdownNow}. However this pool and any
+     * ongoing processing are automatically terminated upon program
+     * {@link System#exit}.  Any program that relies on asynchronous
+     * task processing to complete before program termination should
+     * invoke {@code commonPool().}{@link #awaitQuiescence awaitQuiescence},
+     * before exit.
      *
      * @return the common pool instance
      * @since 1.8
      */
     public static ForkJoinPool commonPool() {
-        // assert commonPool != null : "static init error";
-        return commonPool;
+        // assert common != null : "static init error";
+        return common;
     }
 
     // Execution methods
@@ -2671,7 +2623,7 @@
         if (task instanceof ForkJoinTask<?>) // avoid re-wrap
             job = (ForkJoinTask<?>) task;
         else
-            job = new ForkJoinTask.AdaptedRunnableAction(task);
+            job = new ForkJoinTask.RunnableExecuteAction(task);
         externalPush(job);
     }
 
@@ -2738,27 +2690,23 @@
         // In previous versions of this class, this method constructed
         // a task to run ForkJoinTask.invokeAll, but now external
         // invocation of multiple tasks is at least as efficient.
-        List<ForkJoinTask<T>> fs = new ArrayList<ForkJoinTask<T>>(tasks.size());
-        // Workaround needed because method wasn't declared with
-        // wildcards in return type but should have been.
-        @SuppressWarnings({"unchecked", "rawtypes"})
-            List<Future<T>> futures = (List<Future<T>>) (List) fs;
+        ArrayList<Future<T>> futures = new ArrayList<Future<T>>(tasks.size());
 
         boolean done = false;
         try {
             for (Callable<T> t : tasks) {
                 ForkJoinTask<T> f = new ForkJoinTask.AdaptedCallable<T>(t);
+                futures.add(f);
                 externalPush(f);
-                fs.add(f);
             }
-            for (ForkJoinTask<T> f : fs)
-                f.quietlyJoin();
+            for (int i = 0, size = futures.size(); i < size; i++)
+                ((ForkJoinTask<?>)futures.get(i)).quietlyJoin();
             done = true;
             return futures;
         } finally {
             if (!done)
-                for (ForkJoinTask<T> f : fs)
-                    f.cancel(false);
+                for (int i = 0, size = futures.size(); i < size; i++)
+                    futures.get(i).cancel(false);
         }
     }
 
@@ -2777,7 +2725,7 @@
      *
      * @return the handler, or {@code null} if none
      */
-    public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() {
+    public UncaughtExceptionHandler getUncaughtExceptionHandler() {
         return ueh;
     }
 
@@ -2787,7 +2735,8 @@
      * @return the targeted parallelism level of this pool
      */
     public int getParallelism() {
-        return config & SMASK;
+        int par = (config & SMASK);
+        return (par > 0) ? par : 1;
     }
 
     /**
@@ -2797,7 +2746,7 @@
      * @since 1.8
      */
     public static int getCommonPoolParallelism() {
-        return commonPoolParallelism;
+        return commonParallelism;
     }
 
     /**
@@ -3055,7 +3004,7 @@
      * Possibly initiates an orderly shutdown in which previously
      * submitted tasks are executed, but no new tasks will be
      * accepted. Invocation has no effect on execution state if this
-     * is the {@link #commonPool}, and no additional effect if
+     * is the {@link #commonPool()}, and no additional effect if
      * already shut down.  Tasks that are in the process of being
      * submitted concurrently during the course of this method may or
      * may not be rejected.
@@ -3073,7 +3022,7 @@
     /**
      * Possibly attempts to cancel and/or stop all tasks, and reject
      * all subsequently submitted tasks.  Invocation has no effect on
-     * execution state if this is the {@link #commonPool}, and no
+     * execution state if this is the {@link #commonPool()}, and no
      * additional effect if already shut down. Otherwise, tasks that
      * are in the process of being submitted or executed concurrently
      * during the course of this method may or may not be
@@ -3136,9 +3085,10 @@
     /**
      * Blocks until all tasks have completed execution after a
      * shutdown request, or the timeout occurs, or the current thread
-     * is interrupted, whichever happens first. Note that the {@link
-     * #commonPool()} never terminates until program shutdown so
-     * this method will always time out.
+     * is interrupted, whichever happens first. Because the {@link
+     * #commonPool()} never terminates until program shutdown, when
+     * applied to the common pool, this method is equivalent to {@link
+     * #awaitQuiescence(long, TimeUnit)} but always returns {@code false}.
      *
      * @param timeout the maximum time to wait
      * @param unit the time unit of the timeout argument
@@ -3148,6 +3098,12 @@
      */
     public boolean awaitTermination(long timeout, TimeUnit unit)
         throws InterruptedException {
+        if (Thread.interrupted())
+            throw new InterruptedException();
+        if (this == common) {
+            awaitQuiescence(timeout, unit);
+            return false;
+        }
         long nanos = unit.toNanos(timeout);
         if (isTerminated())
             return true;
@@ -3167,6 +3123,62 @@
     }
 
     /**
+     * If called by a ForkJoinTask operating in this pool, equivalent
+     * in effect to {@link ForkJoinTask#helpQuiesce}. Otherwise,
+     * waits and/or attempts to assist performing tasks until this
+     * pool {@link #isQuiescent} or the indicated timeout elapses.
+     *
+     * @param timeout the maximum time to wait
+     * @param unit the time unit of the timeout argument
+     * @return {@code true} if quiescent; {@code false} if the
+     * timeout elapsed.
+     */
+    public boolean awaitQuiescence(long timeout, TimeUnit unit) {
+        long nanos = unit.toNanos(timeout);
+        ForkJoinWorkerThread wt;
+        Thread thread = Thread.currentThread();
+        if ((thread instanceof ForkJoinWorkerThread) &&
+            (wt = (ForkJoinWorkerThread)thread).pool == this) {
+            helpQuiescePool(wt.workQueue);
+            return true;
+        }
+        long startTime = System.nanoTime();
+        WorkQueue[] ws;
+        int r = 0, m;
+        boolean found = true;
+        while (!isQuiescent() && (ws = workQueues) != null &&
+               (m = ws.length - 1) >= 0) {
+            if (!found) {
+                if ((System.nanoTime() - startTime) > nanos)
+                    return false;
+                Thread.yield(); // cannot block
+            }
+            found = false;
+            for (int j = (m + 1) << 2; j >= 0; --j) {
+                ForkJoinTask<?> t; WorkQueue q; int b;
+                if ((q = ws[r++ & m]) != null && (b = q.base) - q.top < 0) {
+                    found = true;
+                    if ((t = q.pollAt(b)) != null) {
+                        if (q.base - q.top < 0)
+                            signalWork(q);
+                        t.doExec();
+                    }
+                    break;
+                }
+            }
+        }
+        return true;
+    }
+
+    /**
+     * Waits and/or attempts to assist performing tasks indefinitely
+     * until the {@link #commonPool()} {@link #isQuiescent}.
+     */
+    static void quiesceCommonPool() {
+        common.awaitQuiescence(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
+    }
+
+    /**
      * Interface for extending managed parallelism for tasks running
      * in {@link ForkJoinPool}s.
      *
@@ -3175,9 +3187,9 @@
      * not necessary. Method {@code block} blocks the current thread
      * if necessary (perhaps internally invoking {@code isReleasable}
      * before actually blocking). These actions are performed by any
-     * thread invoking {@link ForkJoinPool#managedBlock}.  The
-     * unusual methods in this API accommodate synchronizers that may,
-     * but don't usually, block for long periods. Similarly, they
+     * thread invoking {@link ForkJoinPool#managedBlock(ManagedBlocker)}.
+     * The unusual methods in this API accommodate synchronizers that
+     * may, but don't usually, block for long periods. Similarly, they
      * allow more efficient internal handling of cases in which
      * additional workers may be, but usually are not, needed to
      * ensure sufficient parallelism.  Toward this end,
@@ -3235,6 +3247,7 @@
 
         /**
          * Returns {@code true} if blocking is unnecessary.
+         * @return {@code true} if blocking is unnecessary
          */
         boolean isReleasable();
     }
@@ -3319,7 +3332,7 @@
     private static final long QLOCK;
 
     static {
-        int s; // initialize field offsets for CAS etc
+        // initialize field offsets for CAS etc
         try {
             U = sun.misc.Unsafe.getUnsafe();
             Class<?> k = ForkJoinPool.class;
@@ -3339,54 +3352,58 @@
                 (wk.getDeclaredField("qlock"));
             Class<?> ak = ForkJoinTask[].class;
             ABASE = U.arrayBaseOffset(ak);
-            s = U.arrayIndexScale(ak);
-            ASHIFT = 31 - Integer.numberOfLeadingZeros(s);
+            int scale = U.arrayIndexScale(ak);
+            if ((scale & (scale - 1)) != 0)
+                throw new Error("data type scale not a power of two");
+            ASHIFT = 31 - Integer.numberOfLeadingZeros(scale);
         } catch (Exception e) {
             throw new Error(e);
         }
-        if ((s & (s-1)) != 0)
-            throw new Error("data type scale not a power of two");
 
-        submitters = new ThreadLocal<Submitter>();
-        ForkJoinWorkerThreadFactory fac = defaultForkJoinWorkerThreadFactory =
+        defaultForkJoinWorkerThreadFactory =
             new DefaultForkJoinWorkerThreadFactory();
         modifyThreadPermission = new RuntimePermission("modifyThread");
 
-        /*
-         * Establish common pool parameters.  For extra caution,
-         * computations to set up common pool state are here; the
-         * constructor just assigns these values to fields.
-         */
+        common = java.security.AccessController.doPrivileged
+            (new java.security.PrivilegedAction<ForkJoinPool>() {
+                public ForkJoinPool run() { return makeCommonPool(); }});
+        int par = common.config; // report 1 even if threads disabled
+        commonParallelism = par > 0 ? par : 1;
+    }
 
-        int par = 0;
-        Thread.UncaughtExceptionHandler handler = null;
-        try {  // TBD: limit or report ignored exceptions?
+    /**
+     * Creates and returns the common pool, respecting user settings
+     * specified via system properties.
+     */
+    private static ForkJoinPool makeCommonPool() {
+        int parallelism = -1;
+        ForkJoinWorkerThreadFactory factory
+            = defaultForkJoinWorkerThreadFactory;
+        UncaughtExceptionHandler handler = null;
+        try {  // ignore exceptions in accesing/parsing properties
             String pp = System.getProperty
                 ("java.util.concurrent.ForkJoinPool.common.parallelism");
+            String fp = System.getProperty
+                ("java.util.concurrent.ForkJoinPool.common.threadFactory");
             String hp = System.getProperty
                 ("java.util.concurrent.ForkJoinPool.common.exceptionHandler");
-            String fp = System.getProperty
-                ("java.util.concurrent.ForkJoinPool.common.threadFactory");
+            if (pp != null)
+                parallelism = Integer.parseInt(pp);
             if (fp != null)
-                fac = ((ForkJoinWorkerThreadFactory)ClassLoader.
+                factory = ((ForkJoinWorkerThreadFactory)ClassLoader.
                        getSystemClassLoader().loadClass(fp).newInstance());
             if (hp != null)
-                handler = ((Thread.UncaughtExceptionHandler)ClassLoader.
+                handler = ((UncaughtExceptionHandler)ClassLoader.
                            getSystemClassLoader().loadClass(hp).newInstance());
-            if (pp != null)
-                par = Integer.parseInt(pp);
         } catch (Exception ignore) {
         }
 
-        if (par <= 0)
-            par = Runtime.getRuntime().availableProcessors();
-        if (par > MAX_CAP)
-            par = MAX_CAP;
-        commonPoolParallelism = par;
-        long np = (long)(-par); // precompute initial ctl value
-        long ct = ((np << AC_SHIFT) & AC_MASK) | ((np << TC_SHIFT) & TC_MASK);
-
-        commonPool = new ForkJoinPool(par, ct, fac, handler);
+        if (parallelism < 0)
+            parallelism = Runtime.getRuntime().availableProcessors();
+        if (parallelism > MAX_CAP)
+            parallelism = MAX_CAP;
+        return new ForkJoinPool(parallelism, factory, handler, false,
+                                "ForkJoinPool.commonPool-worker-");
     }
 
 }
--- a/src/share/classes/java/util/concurrent/ForkJoinTask.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/ForkJoinTask.java	Wed Feb 20 15:42:21 2013 -0800
@@ -435,7 +435,7 @@
     }
 
     /**
-     * Records exception and possibly propagates
+     * Records exception and possibly propagates.
      *
      * @return status on exit
      */
@@ -468,7 +468,7 @@
     }
 
     /**
-     * Removes exception node and clears status
+     * Removes exception node and clears status.
      */
     private void clearExceptionalCompletion() {
         int h = System.identityHashCode(this);
@@ -606,7 +606,7 @@
                 throw (Error)ex;
             if (ex instanceof RuntimeException)
                 throw (RuntimeException)ex;
-            throw uncheckedThrowable(ex, RuntimeException.class);
+            ForkJoinTask.<RuntimeException>uncheckedThrow(ex);
         }
     }
 
@@ -616,8 +616,9 @@
      * unchecked exceptions
      */
     @SuppressWarnings("unchecked") static <T extends Throwable>
-        T uncheckedThrowable(final Throwable t, final Class<T> c) {
-        return (T)t; // rely on vacuous cast
+        void uncheckedThrow(Throwable t) throws T {
+        if (t != null)
+            throw (T)t; // rely on vacuous cast
     }
 
     /**
@@ -652,7 +653,7 @@
         if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
             ((ForkJoinWorkerThread)t).workQueue.push(this);
         else
-            ForkJoinPool.commonPool.externalPush(this);
+            ForkJoinPool.common.externalPush(this);
         return this;
     }
 
@@ -828,7 +829,7 @@
      * <p>This method is designed to be invoked by <em>other</em>
      * tasks. To terminate the current task, you can just return or
      * throw an unchecked exception from its computation method, or
-     * invoke {@link #completeExceptionally}.
+     * invoke {@link #completeExceptionally(Throwable)}.
      *
      * @param mayInterruptIfRunning this value has no effect in the
      * default implementation because interrupts are not used to
@@ -978,8 +979,9 @@
         if (Thread.interrupted())
             throw new InterruptedException();
         // Messy in part because we measure in nanosecs, but wait in millisecs
-        int s; long ns, ms;
-        if ((s = status) >= 0 && (ns = unit.toNanos(timeout)) > 0L) {
+        int s; long ms;
+        long ns = unit.toNanos(timeout);
+        if ((s = status) >= 0 && ns > 0L) {
             long deadline = System.nanoTime() + ns;
             ForkJoinPool p = null;
             ForkJoinPool.WorkQueue w = null;
@@ -1075,7 +1077,7 @@
             wt.pool.helpQuiescePool(wt.workQueue);
         }
         else
-            ForkJoinPool.externalHelpQuiescePool();
+            ForkJoinPool.quiesceCommonPool();
     }
 
     /**
@@ -1362,6 +1364,24 @@
     }
 
     /**
+     * Adaptor for Runnables in which failure forces worker exception
+     */
+    static final class RunnableExecuteAction extends ForkJoinTask<Void> {
+        final Runnable runnable;
+        RunnableExecuteAction(Runnable runnable) {
+            if (runnable == null) throw new NullPointerException();
+            this.runnable = runnable;
+        }
+        public final Void getRawResult() { return null; }
+        public final void setRawResult(Void v) { }
+        public final boolean exec() { runnable.run(); return true; }
+        void internalPropagateException(Throwable ex) {
+            rethrow(ex); // rethrow outside exec() catches.
+        }
+        private static final long serialVersionUID = 5232453952276885070L;
+    }
+
+    /**
      * Adaptor for Callables
      */
     static final class AdaptedCallable<T> extends ForkJoinTask<T>
--- a/src/share/classes/java/util/concurrent/Future.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/Future.java	Wed Feb 20 15:42:21 2013 -0800
@@ -36,19 +36,19 @@
 package java.util.concurrent;
 
 /**
- * A <tt>Future</tt> represents the result of an asynchronous
+ * A {@code Future} represents the result of an asynchronous
  * computation.  Methods are provided to check if the computation is
  * complete, to wait for its completion, and to retrieve the result of
  * the computation.  The result can only be retrieved using method
- * <tt>get</tt> when the computation has completed, blocking if
+ * {@code get} when the computation has completed, blocking if
  * necessary until it is ready.  Cancellation is performed by the
- * <tt>cancel</tt> method.  Additional methods are provided to
+ * {@code cancel} method.  Additional methods are provided to
  * determine if the task completed normally or was cancelled. Once a
  * computation has completed, the computation cannot be cancelled.
- * If you would like to use a <tt>Future</tt> for the sake
+ * If you would like to use a {@code Future} for the sake
  * of cancellability but not provide a usable result, you can
  * declare types of the form {@code Future<?>} and
- * return <tt>null</tt> as a result of the underlying task.
+ * return {@code null} as a result of the underlying task.
  *
  * <p>
  * <b>Sample Usage</b> (Note that the following classes are all
@@ -72,9 +72,9 @@
  *   }
  * }}</pre>
  *
- * The {@link FutureTask} class is an implementation of <tt>Future</tt> that
- * implements <tt>Runnable</tt>, and so may be executed by an <tt>Executor</tt>.
- * For example, the above construction with <tt>submit</tt> could be replaced by:
+ * The {@link FutureTask} class is an implementation of {@code Future} that
+ * implements {@code Runnable}, and so may be executed by an {@code Executor}.
+ * For example, the above construction with {@code submit} could be replaced by:
  *  <pre> {@code
  * FutureTask<String> future =
  *   new FutureTask<String>(new Callable<String>() {
@@ -91,7 +91,7 @@
  * @see Executor
  * @since 1.5
  * @author Doug Lea
- * @param <V> The result type returned by this Future's <tt>get</tt> method
+ * @param <V> The result type returned by this Future's {@code get} method
  */
 public interface Future<V> {
 
@@ -99,41 +99,41 @@
      * Attempts to cancel execution of this task.  This attempt will
      * fail if the task has already completed, has already been cancelled,
      * or could not be cancelled for some other reason. If successful,
-     * and this task has not started when <tt>cancel</tt> is called,
+     * and this task has not started when {@code cancel} is called,
      * this task should never run.  If the task has already started,
-     * then the <tt>mayInterruptIfRunning</tt> parameter determines
+     * then the {@code mayInterruptIfRunning} parameter determines
      * whether the thread executing this task should be interrupted in
      * an attempt to stop the task.
      *
      * <p>After this method returns, subsequent calls to {@link #isDone} will
-     * always return <tt>true</tt>.  Subsequent calls to {@link #isCancelled}
-     * will always return <tt>true</tt> if this method returned <tt>true</tt>.
+     * always return {@code true}.  Subsequent calls to {@link #isCancelled}
+     * will always return {@code true} if this method returned {@code true}.
      *
-     * @param mayInterruptIfRunning <tt>true</tt> if the thread executing this
+     * @param mayInterruptIfRunning {@code true} if the thread executing this
      * task should be interrupted; otherwise, in-progress tasks are allowed
      * to complete
-     * @return <tt>false</tt> if the task could not be cancelled,
+     * @return {@code false} if the task could not be cancelled,
      * typically because it has already completed normally;
-     * <tt>true</tt> otherwise
+     * {@code true} otherwise
      */
     boolean cancel(boolean mayInterruptIfRunning);
 
     /**
-     * Returns <tt>true</tt> if this task was cancelled before it completed
+     * Returns {@code true} if this task was cancelled before it completed
      * normally.
      *
-     * @return <tt>true</tt> if this task was cancelled before it completed
+     * @return {@code true} if this task was cancelled before it completed
      */
     boolean isCancelled();
 
     /**
-     * Returns <tt>true</tt> if this task completed.
+     * Returns {@code true} if this task completed.
      *
      * Completion may be due to normal termination, an exception, or
      * cancellation -- in all of these cases, this method will return
-     * <tt>true</tt>.
+     * {@code true}.
      *
-     * @return <tt>true</tt> if this task completed
+     * @return {@code true} if this task completed
      */
     boolean isDone();
 
--- a/src/share/classes/java/util/concurrent/FutureTask.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/FutureTask.java	Wed Feb 20 15:42:21 2013 -0800
@@ -162,19 +162,23 @@
     }
 
     public boolean cancel(boolean mayInterruptIfRunning) {
-        if (state != NEW)
+        if (!(state == NEW &&
+              UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
+                  mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
             return false;
+        try {    // in case call to interrupt throws exception
         if (mayInterruptIfRunning) {
-            if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, INTERRUPTING))
-                return false;
+                try {
             Thread t = runner;
             if (t != null)
                 t.interrupt();
-            UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED); // final state
+                } finally { // final state
+                    UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
         }
-        else if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, CANCELLED))
-            return false;
+            }
+        } finally {
         finishCompletion();
+        }
         return true;
     }
 
--- a/src/share/classes/java/util/concurrent/LinkedTransferQueue.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/LinkedTransferQueue.java	Wed Feb 20 15:42:21 2013 -0800
@@ -36,11 +36,13 @@
 package java.util.concurrent;
 
 import java.util.AbstractQueue;
+import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.Iterator;
 import java.util.NoSuchElementException;
 import java.util.Queue;
+import java.util.concurrent.TimeUnit;
 import java.util.concurrent.locks.LockSupport;
 import java.util.Spliterator;
 import java.util.stream.Stream;
--- a/src/share/classes/java/util/concurrent/LongAdder.java	Wed Feb 20 17:20:17 2013 -0500
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,202 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-package java.util.concurrent;
-import java.util.concurrent.atomic.AtomicLong;
-import java.io.IOException;
-import java.io.Serializable;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-
-/**
- * One or more variables that together maintain an initially zero
- * {@code long} sum.  When updates (method {@link #add}) are contended
- * across threads, the set of variables may grow dynamically to reduce
- * contention. Method {@link #sum} (or, equivalently, {@link
- * #longValue}) returns the current total combined across the
- * variables maintaining the sum.
- *
- * <p> This class is usually preferable to {@link AtomicLong} when
- * multiple threads update a common sum that is used for purposes such
- * as collecting statistics, not for fine-grained synchronization
- * control.  Under low update contention, the two classes have similar
- * characteristics. But under high contention, expected throughput of
- * this class is significantly higher, at the expense of higher space
- * consumption.
- *
- * <p>This class extends {@link Number}, but does <em>not</em> define
- * methods such as {@code hashCode} and {@code compareTo} because
- * instances are expected to be mutated, and so are not useful as
- * collection keys.
- *
- * <p><em>jsr166e note: This class is targeted to be placed in
- * java.util.concurrent.atomic<em>
- *
- * @since 1.8
- * @author Doug Lea
- */
-public class LongAdder extends Striped64 implements Serializable {
-    private static final long serialVersionUID = 7249069246863182397L;
-
-    /**
-     * Version of plus for use in retryUpdate
-     */
-    final long fn(long v, long x) { return v + x; }
-
-    /**
-     * Creates a new adder with initial sum of zero.
-     */
-    public LongAdder() {
-    }
-
-    /**
-     * Adds the given value.
-     *
-     * @param x the value to add
-     */
-    public void add(long x) {
-        Cell[] as; long b, v; HashCode hc; Cell a; int n;
-        if ((as = cells) != null || !casBase(b = base, b + x)) {
-            boolean uncontended = true;
-            int h = (hc = threadHashCode.get()).code;
-            if (as == null || (n = as.length) < 1 ||
-                (a = as[(n - 1) & h]) == null ||
-                !(uncontended = a.cas(v = a.value, v + x)))
-                retryUpdate(x, hc, uncontended);
-        }
-    }
-
-    /**
-     * Equivalent to {@code add(1)}.
-     */
-    public void increment() {
-        add(1L);
-    }
-
-    /**
-     * Equivalent to {@code add(-1)}.
-     */
-    public void decrement() {
-        add(-1L);
-    }
-
-    /**
-     * Returns the current sum.  The returned value is <em>NOT</em> an
-     * atomic snapshot: Invocation in the absence of concurrent
-     * updates returns an accurate result, but concurrent updates that
-     * occur while the sum is being calculated might not be
-     * incorporated.
-     *
-     * @return the sum
-     */
-    public long sum() {
-        long sum = base;
-        Cell[] as = cells;
-        if (as != null) {
-            int n = as.length;
-            for (int i = 0; i < n; ++i) {
-                Cell a = as[i];
-                if (a != null)
-                    sum += a.value;
-            }
-        }
-        return sum;
-    }
-
-    /**
-     * Resets variables maintaining the sum to zero.  This method may
-     * be a useful alternative to creating a new adder, but is only
-     * effective if there are no concurrent updates.  Because this
-     * method is intrinsically racy, it should only be used when it is
-     * known that no threads are concurrently updating.
-     */
-    public void reset() {
-        internalReset(0L);
-    }
-
-    /**
-     * Equivalent in effect to {@link #sum} followed by {@link
-     * #reset}. This method may apply for example during quiescent
-     * points between multithreaded computations.  If there are
-     * updates concurrent with this method, the returned value is
-     * <em>not</em> guaranteed to be the final value occurring before
-     * the reset.
-     *
-     * @return the sum
-     */
-    public long sumThenReset() {
-        long sum = base;
-        Cell[] as = cells;
-        base = 0L;
-        if (as != null) {
-            int n = as.length;
-            for (int i = 0; i < n; ++i) {
-                Cell a = as[i];
-                if (a != null) {
-                    sum += a.value;
-                    a.value = 0L;
-                }
-            }
-        }
-        return sum;
-    }
-
-    /**
-     * Returns the String representation of the {@link #sum}.
-     * @return the String representation of the {@link #sum}
-     */
-    public String toString() {
-        return Long.toString(sum());
-    }
-
-    /**
-     * Equivalent to {@link #sum}.
-     *
-     * @return the sum
-     */
-    public long longValue() {
-        return sum();
-    }
-
-    /**
-     * Returns the {@link #sum} as an {@code int} after a narrowing
-     * primitive conversion.
-     */
-    public int intValue() {
-        return (int)sum();
-    }
-
-    /**
-     * Returns the {@link #sum} as a {@code float}
-     * after a widening primitive conversion.
-     */
-    public float floatValue() {
-        return (float)sum();
-    }
-
-    /**
-     * Returns the {@link #sum} as a {@code double} after a widening
-     * primitive conversion.
-     */
-    public double doubleValue() {
-        return (double)sum();
-    }
-
-    private void writeObject(java.io.ObjectOutputStream s)
-        throws java.io.IOException {
-        s.defaultWriteObject();
-        s.writeLong(sum());
-    }
-
-    private void readObject(ObjectInputStream s)
-        throws IOException, ClassNotFoundException {
-        s.defaultReadObject();
-        busy = 0;
-        cells = null;
-        base = s.readLong();
-    }
-
-}
--- a/src/share/classes/java/util/concurrent/LongMaxUpdater.java	Wed Feb 20 17:20:17 2013 -0500
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,186 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-package java.util.concurrent;
-import java.io.IOException;
-import java.io.Serializable;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-
-/**
- * One or more variables that together maintain a running {@code long}
- * maximum with initial value {@code Long.MIN_VALUE}.  When updates
- * (method {@link #update}) are contended across threads, the set of
- * variables may grow dynamically to reduce contention.  Method {@link
- * #max} (or, equivalently, {@link #longValue}) returns the current
- * maximum across the variables maintaining updates.
- *
- * <p>This class extends {@link Number}, but does <em>not</em> define
- * methods such as {@code hashCode} and {@code compareTo} because
- * instances are expected to be mutated, and so are not useful as
- * collection keys.
- *
- * <p><em>jsr166e note: This class is targeted to be placed in
- * java.util.concurrent.atomic<em>
- *
- * @since 1.8
- * @author Doug Lea
- */
-public class LongMaxUpdater extends Striped64 implements Serializable {
-    private static final long serialVersionUID = 7249069246863182397L;
-
-    /**
-     * Version of max for use in retryUpdate
-     */
-    final long fn(long v, long x) { return v > x ? v : x; }
-
-    /**
-     * Creates a new instance with initial maximum of {@code
-     * Long.MIN_VALUE}.
-     */
-    public LongMaxUpdater() {
-        base = Long.MIN_VALUE;
-    }
-
-    /**
-     * Updates the maximum to be at least the given value.
-     *
-     * @param x the value to update
-     */
-    public void update(long x) {
-        Cell[] as; long b, v; HashCode hc; Cell a; int n;
-        if ((as = cells) != null ||
-            (b = base) < x && !casBase(b, x)) {
-            boolean uncontended = true;
-            int h = (hc = threadHashCode.get()).code;
-            if (as == null || (n = as.length) < 1 ||
-                (a = as[(n - 1) & h]) == null ||
-                ((v = a.value) < x && !(uncontended = a.cas(v, x))))
-                retryUpdate(x, hc, uncontended);
-        }
-    }
-
-    /**
-     * Returns the current maximum.  The returned value is
-     * <em>NOT</em> an atomic snapshot: Invocation in the absence of
-     * concurrent updates returns an accurate result, but concurrent
-     * updates that occur while the value is being calculated might
-     * not be incorporated.
-     *
-     * @return the maximum
-     */
-    public long max() {
-        Cell[] as = cells;
-        long max = base;
-        if (as != null) {
-            int n = as.length;
-            long v;
-            for (int i = 0; i < n; ++i) {
-                Cell a = as[i];
-                if (a != null && (v = a.value) > max)
-                    max = v;
-            }
-        }
-        return max;
-    }
-
-    /**
-     * Resets variables maintaining updates to {@code Long.MIN_VALUE}.
-     * This method may be a useful alternative to creating a new
-     * updater, but is only effective if there are no concurrent
-     * updates.  Because this method is intrinsically racy, it should
-     * only be used when it is known that no threads are concurrently
-     * updating.
-     */
-    public void reset() {
-        internalReset(Long.MIN_VALUE);
-    }
-
-    /**
-     * Equivalent in effect to {@link #max} followed by {@link
-     * #reset}. This method may apply for example during quiescent
-     * points between multithreaded computations.  If there are
-     * updates concurrent with this method, the returned value is
-     * <em>not</em> guaranteed to be the final value occurring before
-     * the reset.
-     *
-     * @return the maximum
-     */
-    public long maxThenReset() {
-        Cell[] as = cells;
-        long max = base;
-        base = Long.MIN_VALUE;
-        if (as != null) {
-            int n = as.length;
-            for (int i = 0; i < n; ++i) {
-                Cell a = as[i];
-                if (a != null) {
-                    long v = a.value;
-                    a.value = Long.MIN_VALUE;
-                    if (v > max)
-                        max = v;
-                }
-            }
-        }
-        return max;
-    }
-
-    /**
-     * Returns the String representation of the {@link #max}.
-     * @return the String representation of the {@link #max}
-     */
-    public String toString() {
-        return Long.toString(max());
-    }
-
-    /**
-     * Equivalent to {@link #max}.
-     *
-     * @return the maximum
-     */
-    public long longValue() {
-        return max();
-    }
-
-    /**
-     * Returns the {@link #max} as an {@code int} after a narrowing
-     * primitive conversion.
-     */
-    public int intValue() {
-        return (int)max();
-    }
-
-    /**
-     * Returns the {@link #max} as a {@code float}
-     * after a widening primitive conversion.
-     */
-    public float floatValue() {
-        return (float)max();
-    }
-
-    /**
-     * Returns the {@link #max} as a {@code double} after a widening
-     * primitive conversion.
-     */
-    public double doubleValue() {
-        return (double)max();
-    }
-
-    private void writeObject(java.io.ObjectOutputStream s)
-        throws java.io.IOException {
-        s.defaultWriteObject();
-        s.writeLong(max());
-    }
-
-    private void readObject(ObjectInputStream s)
-        throws IOException, ClassNotFoundException {
-        s.defaultReadObject();
-        busy = 0;
-        cells = null;
-        base = s.readLong();
-    }
-
-}
--- a/src/share/classes/java/util/concurrent/Phaser.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/Phaser.java	Wed Feb 20 15:42:21 2013 -0800
@@ -300,18 +300,20 @@
     private static final int  PHASE_SHIFT     = 32;
     private static final int  UNARRIVED_MASK  = 0xffff;      // to mask ints
     private static final long PARTIES_MASK    = 0xffff0000L; // to mask longs
+    private static final long COUNTS_MASK     = 0xffffffffL;
     private static final long TERMINATION_BIT = 1L << 63;
 
     // some special values
     private static final int  ONE_ARRIVAL     = 1;
     private static final int  ONE_PARTY       = 1 << PARTIES_SHIFT;
+    private static final int  ONE_DEREGISTER  = ONE_ARRIVAL|ONE_PARTY;
     private static final int  EMPTY           = 1;
 
     // The following unpacking methods are usually manually inlined
 
     private static int unarrivedOf(long s) {
         int counts = (int)s;
-        return (counts == EMPTY) ? 0 : counts & UNARRIVED_MASK;
+        return (counts == EMPTY) ? 0 : (counts & UNARRIVED_MASK);
     }
 
     private static int partiesOf(long s) {
@@ -372,38 +374,45 @@
      * Manually tuned to speed up and minimize race windows for the
      * common case of just decrementing unarrived field.
      *
-     * @param deregister false for arrive, true for arriveAndDeregister
+     * @param adjust value to subtract from state;
+     *               ONE_ARRIVAL for arrive,
+     *               ONE_DEREGISTER for arriveAndDeregister
      */
-    private int doArrive(boolean deregister) {
-        int adj = deregister ? ONE_ARRIVAL|ONE_PARTY : ONE_ARRIVAL;
+    private int doArrive(int adjust) {
         final Phaser root = this.root;
         for (;;) {
             long s = (root == this) ? state : reconcileState();
             int phase = (int)(s >>> PHASE_SHIFT);
-            int counts = (int)s;
-            int unarrived = (counts & UNARRIVED_MASK) - 1;
             if (phase < 0)
                 return phase;
-            else if (counts == EMPTY || unarrived < 0) {
-                if (root == this || reconcileState() == s)
+            int counts = (int)s;
+            int unarrived = (counts == EMPTY) ? 0 : (counts & UNARRIVED_MASK);
+            if (unarrived <= 0)
                     throw new IllegalStateException(badArrive(s));
-            }
-            else if (UNSAFE.compareAndSwapLong(this, stateOffset, s, s-=adj)) {
-                if (unarrived == 0) {
+            if (UNSAFE.compareAndSwapLong(this, stateOffset, s, s-=adjust)) {
+                if (unarrived == 1) {
                     long n = s & PARTIES_MASK;  // base of next state
                     int nextUnarrived = (int)n >>> PARTIES_SHIFT;
-                    if (root != this)
-                        return parent.doArrive(nextUnarrived == 0);
+                    if (root == this) {
                     if (onAdvance(phase, nextUnarrived))
                         n |= TERMINATION_BIT;
                     else if (nextUnarrived == 0)
                         n |= EMPTY;
                     else
                         n |= nextUnarrived;
-                    n |= (long)((phase + 1) & MAX_PHASE) << PHASE_SHIFT;
+                        int nextPhase = (phase + 1) & MAX_PHASE;
+                        n |= (long)nextPhase << PHASE_SHIFT;
                     UNSAFE.compareAndSwapLong(this, stateOffset, s, n);
                     releaseWaiters(phase);
                 }
+                    else if (nextUnarrived == 0) { // propagate deregistration
+                        phase = parent.doArrive(ONE_DEREGISTER);
+                        UNSAFE.compareAndSwapLong(this, stateOffset,
+                                                  s, s | EMPTY);
+                    }
+                    else
+                        phase = parent.doArrive(ONE_ARRIVAL);
+                }
                 return phase;
             }
         }
@@ -417,42 +426,49 @@
      */
     private int doRegister(int registrations) {
         // adjustment to state
-        long adj = ((long)registrations << PARTIES_SHIFT) | registrations;
+        long adjust = ((long)registrations << PARTIES_SHIFT) | registrations;
         final Phaser parent = this.parent;
         int phase;
         for (;;) {
-            long s = state;
+            long s = (parent == null) ? state : reconcileState();
             int counts = (int)s;
             int parties = counts >>> PARTIES_SHIFT;
             int unarrived = counts & UNARRIVED_MASK;
             if (registrations > MAX_PARTIES - parties)
                 throw new IllegalStateException(badRegister(s));
-            else if ((phase = (int)(s >>> PHASE_SHIFT)) < 0)
+            phase = (int)(s >>> PHASE_SHIFT);
+            if (phase < 0)
                 break;
-            else if (counts != EMPTY) {             // not 1st registration
+            if (counts != EMPTY) {                  // not 1st registration
                 if (parent == null || reconcileState() == s) {
                     if (unarrived == 0)             // wait out advance
                         root.internalAwaitAdvance(phase, null);
                     else if (UNSAFE.compareAndSwapLong(this, stateOffset,
-                                                       s, s + adj))
+                                                       s, s + adjust))
                         break;
                 }
             }
             else if (parent == null) {              // 1st root registration
-                long next = ((long)phase << PHASE_SHIFT) | adj;
+                long next = ((long)phase << PHASE_SHIFT) | adjust;
                 if (UNSAFE.compareAndSwapLong(this, stateOffset, s, next))
                     break;
             }
             else {
                 synchronized (this) {               // 1st sub registration
                     if (state == s) {               // recheck under lock
-                        parent.doRegister(1);
-                        do {                        // force current phase
+                        phase = parent.doRegister(1);
+                        if (phase < 0)
+                            break;
+                        // finish registration whenever parent registration
+                        // succeeded, even when racing with termination,
+                        // since these are part of the same "transaction".
+                        while (!UNSAFE.compareAndSwapLong
+                               (this, stateOffset, s,
+                                ((long)phase << PHASE_SHIFT) | adjust)) {
+                            s = state;
                             phase = (int)(root.state >>> PHASE_SHIFT);
-                            // assert phase < 0 || (int)state == EMPTY;
-                        } while (!UNSAFE.compareAndSwapLong
-                                 (this, stateOffset, state,
-                                  ((long)phase << PHASE_SHIFT) | adj));
+                            // assert (int)s == EMPTY;
+                        }
                         break;
                     }
                 }
@@ -467,10 +483,6 @@
      * subphasers have not yet done so, in which case they must finish
      * their own advance by setting unarrived to parties (or if
      * parties is zero, resetting to unregistered EMPTY state).
-     * However, this method may also be called when "floating"
-     * subphasers with possibly some unarrived parties are merely
-     * catching up to current phase, in which case counts are
-     * unaffected.
      *
      * @return reconciled state
      */
@@ -478,16 +490,16 @@
         final Phaser root = this.root;
         long s = state;
         if (root != this) {
-            int phase, u, p;
-            // CAS root phase with current parties; possibly trip unarrived
+            int phase, p;
+            // CAS to root phase with current parties, tripping unarrived
             while ((phase = (int)(root.state >>> PHASE_SHIFT)) !=
                    (int)(s >>> PHASE_SHIFT) &&
                    !UNSAFE.compareAndSwapLong
                    (this, stateOffset, s,
                     s = (((long)phase << PHASE_SHIFT) |
-                         (s & PARTIES_MASK) |
-                         ((p = (int)s >>> PARTIES_SHIFT) == 0 ? EMPTY :
-                          (u = (int)s & UNARRIVED_MASK) == 0 ? p : u))))
+                         ((phase < 0) ? (s & COUNTS_MASK) :
+                          (((p = (int)s >>> PARTIES_SHIFT) == 0) ? EMPTY :
+                           ((s & PARTIES_MASK) | p))))))
                 s = state;
         }
         return s;
@@ -619,7 +631,7 @@
      * of unarrived parties would become negative
      */
     public int arrive() {
-        return doArrive(false);
+        return doArrive(ONE_ARRIVAL);
     }
 
     /**
@@ -639,7 +651,7 @@
      * of registered or unarrived parties would become negative
      */
     public int arriveAndDeregister() {
-        return doArrive(true);
+        return doArrive(ONE_DEREGISTER);
     }
 
     /**
@@ -666,17 +678,15 @@
         for (;;) {
             long s = (root == this) ? state : reconcileState();
             int phase = (int)(s >>> PHASE_SHIFT);
-            int counts = (int)s;
-            int unarrived = (counts & UNARRIVED_MASK) - 1;
             if (phase < 0)
                 return phase;
-            else if (counts == EMPTY || unarrived < 0) {
-                if (reconcileState() == s)
+            int counts = (int)s;
+            int unarrived = (counts == EMPTY) ? 0 : (counts & UNARRIVED_MASK);
+            if (unarrived <= 0)
                     throw new IllegalStateException(badArrive(s));
-            }
-            else if (UNSAFE.compareAndSwapLong(this, stateOffset, s,
+            if (UNSAFE.compareAndSwapLong(this, stateOffset, s,
                                                s -= ONE_ARRIVAL)) {
-                if (unarrived != 0)
+                if (unarrived > 1)
                     return root.internalAwaitAdvance(phase, null);
                 if (root != this)
                     return parent.arriveAndAwaitAdvance();
@@ -809,8 +819,8 @@
             if (UNSAFE.compareAndSwapLong(root, stateOffset,
                                           s, s | TERMINATION_BIT)) {
                 // signal all threads
-                releaseWaiters(0);
-                releaseWaiters(1);
+                releaseWaiters(0); // Waiters on evenQ
+                releaseWaiters(1); // Waiters on oddQ
                 return;
             }
         }
@@ -1016,7 +1026,7 @@
 
     /**
      * Possibly blocks and waits for phase to advance unless aborted.
-     * Call only from root node.
+     * Call only on root phaser.
      *
      * @param phase current phase
      * @param node if non-null, the wait node to track interrupt and timeout;
@@ -1024,6 +1034,7 @@
      * @return current phase
      */
     private int internalAwaitAdvance(int phase, QNode node) {
+        // assert root == this;
         releaseWaiters(phase-1);          // ensure old queue clean
         boolean queued = false;           // true when node is enqueued
         int lastUnarrived = 0;            // to increase spins upon change
@@ -1082,7 +1093,7 @@
         final boolean timed;
         boolean wasInterrupted;
         long nanos;
-        long lastTime;
+        final long deadline;
         volatile Thread thread; // nulled to cancel wait
         QNode next;
 
@@ -1093,7 +1104,7 @@
             this.interruptible = interruptible;
             this.nanos = nanos;
             this.timed = timed;
-            this.lastTime = timed ? System.nanoTime() : 0L;
+            this.deadline = timed ? System.nanoTime() + nanos : 0L;
             thread = Thread.currentThread();
         }
 
@@ -1112,9 +1123,7 @@
             }
             if (timed) {
                 if (nanos > 0L) {
-                    long now = System.nanoTime();
-                    nanos -= now - lastTime;
-                    lastTime = now;
+                    nanos = deadline - System.nanoTime();
                 }
                 if (nanos <= 0L) {
                     thread = null;
@@ -1129,7 +1138,7 @@
                 return true;
             else if (!timed)
                 LockSupport.park(this);
-            else if (nanos > 0)
+            else if (nanos > 0L)
                 LockSupport.parkNanos(this, nanos);
             return isReleasable();
         }
--- a/src/share/classes/java/util/concurrent/PriorityBlockingQueue.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/PriorityBlockingQueue.java	Wed Feb 20 15:42:21 2013 -0800
@@ -50,6 +50,7 @@
 import java.util.Spliterator;
 import java.util.stream.Stream;
 import java.util.stream.Streams;
+import java.util.function.Consumer;
 
 /**
  * An unbounded {@linkplain BlockingQueue blocking queue} that uses
--- a/src/share/classes/java/util/concurrent/RecursiveAction.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/RecursiveAction.java	Wed Feb 20 15:42:21 2013 -0800
@@ -34,7 +34,7 @@
  *     }
  *   }
  *   // implementation details follow:
- *   final static int THRESHOLD = 1000;
+ *   static final int THRESHOLD = 1000;
  *   void sortSequentially(int lo, int hi) {
  *     Arrays.sort(array, lo, hi);
  *   }
--- a/src/share/classes/java/util/concurrent/RecursiveTask.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/RecursiveTask.java	Wed Feb 20 15:42:21 2013 -0800
@@ -46,6 +46,7 @@
 
     /**
      * The main computation performed by this task.
+     * @return the result of the computation
      */
     protected abstract V compute();
 
--- a/src/share/classes/java/util/concurrent/RejectedExecutionException.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/RejectedExecutionException.java	Wed Feb 20 15:42:21 2013 -0800
@@ -46,14 +46,14 @@
     private static final long serialVersionUID = -375805702767069545L;
 
     /**
-     * Constructs a <tt>RejectedExecutionException</tt> with no detail message.
+     * Constructs a {@code RejectedExecutionException} with no detail message.
      * The cause is not initialized, and may subsequently be
      * initialized by a call to {@link #initCause(Throwable) initCause}.
      */
     public RejectedExecutionException() { }
 
     /**
-     * Constructs a <tt>RejectedExecutionException</tt> with the
+     * Constructs a {@code RejectedExecutionException} with the
      * specified detail message. The cause is not initialized, and may
      * subsequently be initialized by a call to {@link
      * #initCause(Throwable) initCause}.
@@ -65,7 +65,7 @@
     }
 
     /**
-     * Constructs a <tt>RejectedExecutionException</tt> with the
+     * Constructs a {@code RejectedExecutionException} with the
      * specified detail message and cause.
      *
      * @param  message the detail message
@@ -77,10 +77,10 @@
     }
 
     /**
-     * Constructs a <tt>RejectedExecutionException</tt> with the
+     * Constructs a {@code RejectedExecutionException} with the
      * specified cause.  The detail message is set to {@code (cause ==
      * null ? null : cause.toString())} (which typically contains
-     * the class and detail message of <tt>cause</tt>).
+     * the class and detail message of {@code cause}).
      *
      * @param  cause the cause (which is saved for later retrieval by the
      *         {@link #getCause()} method)
--- a/src/share/classes/java/util/concurrent/RunnableFuture.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/RunnableFuture.java	Wed Feb 20 15:42:21 2013 -0800
@@ -37,13 +37,13 @@
 
 /**
  * A {@link Future} that is {@link Runnable}. Successful execution of
- * the <tt>run</tt> method causes completion of the <tt>Future</tt>
+ * the {@code run} method causes completion of the {@code Future}
  * and allows access to its results.
  * @see FutureTask
  * @see Executor
  * @since 1.6
  * @author Doug Lea
- * @param <V> The result type returned by this Future's <tt>get</tt> method
+ * @param <V> The result type returned by this Future's {@code get} method
  */
 public interface RunnableFuture<V> extends Runnable, Future<V> {
     /**
--- a/src/share/classes/java/util/concurrent/RunnableScheduledFuture.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/RunnableScheduledFuture.java	Wed Feb 20 15:42:21 2013 -0800
@@ -37,13 +37,13 @@
 
 /**
  * A {@link ScheduledFuture} that is {@link Runnable}. Successful
- * execution of the <tt>run</tt> method causes completion of the
- * <tt>Future</tt> and allows access to its results.
+ * execution of the {@code run} method causes completion of the
+ * {@code Future} and allows access to its results.
  * @see FutureTask
  * @see Executor
  * @since 1.6
  * @author Doug Lea
- * @param <V> The result type returned by this Future's <tt>get</tt> method
+ * @param <V> The result type returned by this Future's {@code get} method
  */
 public interface RunnableScheduledFuture<V> extends RunnableFuture<V>, ScheduledFuture<V> {
 
--- a/src/share/classes/java/util/concurrent/ScheduledExecutorService.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/ScheduledExecutorService.java	Wed Feb 20 15:42:21 2013 -0800
@@ -39,26 +39,26 @@
  * An {@link ExecutorService} that can schedule commands to run after a given
  * delay, or to execute periodically.
  *
- * <p> The <tt>schedule</tt> methods create tasks with various delays
+ * <p> The {@code schedule} methods create tasks with various delays
  * and return a task object that can be used to cancel or check
- * execution. The <tt>scheduleAtFixedRate</tt> and
- * <tt>scheduleWithFixedDelay</tt> methods create and execute tasks
+ * execution. The {@code scheduleAtFixedRate} and
+ * {@code scheduleWithFixedDelay} methods create and execute tasks
  * that run periodically until cancelled.
  *
- * <p> Commands submitted using the {@link Executor#execute} and
- * {@link ExecutorService} <tt>submit</tt> methods are scheduled with
- * a requested delay of zero. Zero and negative delays (but not
- * periods) are also allowed in <tt>schedule</tt> methods, and are
+ * <p>Commands submitted using the {@link Executor#execute(Runnable)}
+ * and {@link ExecutorService} {@code submit} methods are scheduled
+ * with a requested delay of zero. Zero and negative delays (but not
+ * periods) are also allowed in {@code schedule} methods, and are
  * treated as requests for immediate execution.
  *
- * <p>All <tt>schedule</tt> methods accept <em>relative</em> delays and
+ * <p>All {@code schedule} methods accept <em>relative</em> delays and
  * periods as arguments, not absolute times or dates. It is a simple
  * matter to transform an absolute time represented as a {@link
  * java.util.Date} to the required form. For example, to schedule at
- * a certain future <tt>date</tt>, you can use: <tt>schedule(task,
+ * a certain future {@code date}, you can use: {@code schedule(task,
  * date.getTime() - System.currentTimeMillis(),
- * TimeUnit.MILLISECONDS)</tt>. Beware however that expiration of a
- * relative delay need not coincide with the current <tt>Date</tt> at
+ * TimeUnit.MILLISECONDS)}. Beware however that expiration of a
+ * relative delay need not coincide with the current {@code Date} at
  * which the task is enabled due to network time synchronization
  * protocols, clock drift, or other factors.
  *
@@ -101,8 +101,8 @@
      * @param delay the time from now to delay execution
      * @param unit the time unit of the delay parameter
      * @return a ScheduledFuture representing pending completion of
-     *         the task and whose <tt>get()</tt> method will return
-     *         <tt>null</tt> upon completion
+     *         the task and whose {@code get()} method will return
+     *         {@code null} upon completion
      * @throws RejectedExecutionException if the task cannot be
      *         scheduled for execution
      * @throws NullPointerException if command is null
@@ -129,8 +129,8 @@
      * Creates and executes a periodic action that becomes enabled first
      * after the given initial delay, and subsequently with the given
      * period; that is executions will commence after
-     * <tt>initialDelay</tt> then <tt>initialDelay+period</tt>, then
-     * <tt>initialDelay + 2 * period</tt>, and so on.
+     * {@code initialDelay} then {@code initialDelay+period}, then
+     * {@code initialDelay + 2 * period}, and so on.
      * If any execution of the task
      * encounters an exception, subsequent executions are suppressed.
      * Otherwise, the task will only terminate via cancellation or
@@ -143,7 +143,7 @@
      * @param period the period between successive executions
      * @param unit the time unit of the initialDelay and period parameters
      * @return a ScheduledFuture representing pending completion of
-     *         the task, and whose <tt>get()</tt> method will throw an
+     *         the task, and whose {@code get()} method will throw an
      *         exception upon cancellation
      * @throws RejectedExecutionException if the task cannot be
      *         scheduled for execution
@@ -170,7 +170,7 @@
      * execution and the commencement of the next
      * @param unit the time unit of the initialDelay and delay parameters
      * @return a ScheduledFuture representing pending completion of
-     *         the task, and whose <tt>get()</tt> method will throw an
+     *         the task, and whose {@code get()} method will throw an
      *         exception upon cancellation
      * @throws RejectedExecutionException if the task cannot be
      *         scheduled for execution
--- a/src/share/classes/java/util/concurrent/ScheduledThreadPoolExecutor.java	Wed Feb 20 17:20:17 2013 -0500
+++ b/src/share/classes/java/util/concurrent/ScheduledThreadPoolExecutor.java	Wed Feb 20 15:42:21 2013 -0800
@@ -81,7 +81,7 @@
  * without threads to handle tasks once they become eligible to run.
  *
  * <p><b>Extension notes:</b> This class overrides the
- * {@link ThreadPoolExecutor#execute execute} and
+ * {@link ThreadPoolExecutor#execute(Runnable) execute} and
  * {@link AbstractExecutorService#submit(Runnable) submit}
  * methods to generate internal {@link ScheduledFuture} objects to
  * control per-task delays and scheduling.  To preserve
@@ -315,7 +315,7 @@
      * is shut down, rejects the task. Otherwise adds task to queue
      * and starts a thread, if necessary, to run it.  (We cannot
      * prestart the thread to run the task because the task (probably)
-     * shouldn't be run yet,) If the pool is shut down while the task
+     * shouldn't be run yet.)  If the pool is shut down while the task
      * is being added, cancel and remove it if required by state and
      * run-after-shutdown parameters.
      *
@@ -654,7 +654,7 @@
      * {@code false} when already shutdown.
      * This value is by default {@code false}.
      *
-     * @param value if {@code true}, continue after shutdown, else don't.
+     * @param value if {@code true}, continue after shutdown, else don't
      * @see #getContinueExistingPeriodicTasksAfterShutdownPolicy
      */
     public void setContinueExistingPeriodicTasksAfterShutdownPolicy(boolean value) {
@@ -686,7 +686,7 @@
      * {@code false} when already shutdown.
      * This value is by default {@code true}.
      *
-     * @param value if {@code true}, execute after shutdown, else don't.
+     * @param value if {@code true}, execute after shutdown, else don't
      * @see #getExecuteExistingDelayedTasksAfterShutdownPolicy
      */
     public void setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean value) {
--- a/src/share/classes/java/util/concurrent/SequenceLock.java	Wed Feb 20 17:20:17 2013 -0500
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,638 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-package java.util.concurrent;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantLock;
-import java.util.concurrent.locks.Condition;
-import java.util.concurrent.locks.AbstractQueuedLongSynchronizer;
-import java.util.Collection;
-import java.io.ObjectOutputStream;
-import java.io.ObjectInputStream;
-import java.io.IOException;
-
-/**
- * A reentrant mutual exclusion {@link Lock} in which each lock
- * acquisition or release advances a sequence number.  When the
- * sequence number (accessible using {@link #getSequence()}) is odd,
- * the lock is held. When it is even (i.e., ({@code lock.getSequence()
- * & 1L) == 0L}), the lock is released. Method {@link
- * #awaitAvailability} can be used to await availability of the lock,
- * returning its current sequence number. Sequence numbers (as well as
- * reentrant hold counts) are of type {@code long} to ensure that they
- * will not wrap around until hundreds of years of use under current
- * processor rates.  A SequenceLock can be created with a specified
- * number of spins. Attempts to acquire the lock in method {@link
- * #lock} will retry at least the given number of times before
- * blocking. If not specified, a default, possibly platform-specific,
- * value is used.
- *
- * <p>Except for the lack of support for specified fairness policies,
- * or {@link Condition} objects, a SequenceLock can be used in the
- * same way as {@link ReentrantLock}. It provides similar status and
- * monitoring methods, such as {@link #isHeldByCurrentThread}.
- * SequenceLocks may be preferable in contexts in which multiple
- * threads invoke short read-only methods much more frequently than
- * fully locked methods.
- *
- * <p> Methods {@code awaitAvailability} and {@code getSequence} can
- * be used together to define (partially) optimistic read-only methods
- * that are usually more efficient than ReadWriteLocks when they
- * apply.  These methods should in general be structured as loops that
- * await lock availability, then read {@code volatile} fields into
- * local variables (and may further read other values derived from
- * these, for example the {@code length} of a {@code volatile} array),
- * and retry if the sequence number changed while doing so.
- * Alternatively, because {@code awaitAvailability} accommodates
- * reentrancy, a method can retry a bounded number of times before
- * switching to locking mode.  While conceptually straightforward,
- * expressing these ideas can be verbose. For example:
- *
- *  <pre> {@code
- * class Point {
- *   private volatile double x, y;
- *   private final SequenceLock sl = new SequenceLock();
- *
- *   // an exclusively locked method
- *   void move(double deltaX, double deltaY) {
- *     sl.lock();
- *     try {
- *       x += deltaX;
- *       y += deltaY;
- *     } finally {
- *       sl.unlock();
- *     }
- *   }
- *
- *   // A read-only method
- *   double distanceFromOriginV1() {
- *     double currentX, currentY;
- *     long seq;
- *     do {
- *       seq = sl.awaitAvailability();
- *       currentX = x;
- *       currentY = y;
- *     } while (sl.getSequence() != seq); // retry if sequence changed
- *     return Math.sqrt(currentX * currentX + currentY * currentY);
- *   }
- *
- *   // Uses bounded retries before locking
- *   double distanceFromOriginV2() {
- *     double currentX, currentY;
- *     long seq;
- *     int retries = RETRIES_BEFORE_LOCKING; // for example 8
- *     try {
- *       do {
- *         if (--retries < 0)
- *           sl.lock();
- *         seq = sl.awaitAvailability();
- *         currentX = x;
- *         currentY = y;
- *       } while (sl.getSequence() != seq);
- *     } finally {
- *       if (retries < 0)
- *         sl.unlock();
- *     }
- *     return Math.sqrt(currentX * currentX + currentY * currentY);
- *   }
- * }}</pre>
- *
- * @since 1.8
- * @author Doug Lea
- */
-public class SequenceLock implements Lock, java.io.Serializable {
-    private static final long serialVersionUID = 7373984872572414699L;
-
-    static final class Sync extends AbstractQueuedLongSynchronizer {
-        static final long serialVersionUID = 2540673546047039555L;
-
-        /**
-         * The number of times to spin in lock() and awaitAvailability().
-         */
-        final int spins;
-
-        /**
-         * The number of reentrant holds on this lock. Uses a long for
-         * compatibility with other AbstractQueuedLongSynchronizer
-         * operations. Accessed only by lock holder.
-         */
-        long holds;
-
-        Sync(int spins) { this.spins = spins; }
-
-        // overrides of AQLS methods
-
-        public final boolean isHeldExclusively() {
-            return (getState() & 1L) != 0L &&
-                getExclusiveOwnerThread() == Thread.currentThread();
-        }
-
-        public final boolean tryAcquire(long acquires) {
-            Thread current = Thread.currentThread();
-            long c = getState();
-            if ((c & 1L) == 0L) {
-                if (compareAndSetState(c, c + 1L)) {
-                    holds = acquires;
-                    setExclusiveOwnerThread(current);
-                    return true;
-                }
-            }
-            else if (current == getExclusiveOwnerThread()) {
-                holds += acquires;
-                return true;
-            }
-            return false;
-        }
-
-        public final boolean tryRelease(long releases) {
-            if (Thread.currentThread() != getExclusiveOwnerThread())
-                throw new IllegalMonitorStateException();
-            if ((holds -= releases) == 0L) {
-                setExclusiveOwnerThread(null);
-                setState(getState() + 1L);
-                return true;
-            }
-            return false;
-        }
-
-        public final long tryAcquireShared(long unused) {
-            return (((getState() & 1L) == 0L) ? 1L :
-                    (getExclusiveOwnerThread() == Thread.currentThread()) ? 0L:
-                    -1L);
-        }
-
-        public final boolean tryReleaseShared(long unused) {
-            return (getState() & 1L) == 0L;
-        }
-
-        public final Condition newCondition() {
-            throw new UnsupportedOperationException();
-        }
-
-        // Other methods in support of SequenceLock
-
-        final long getSequence() {
-            return getState();
-        }
-
-        final void lock() {
-            int k = spins;
-            while (!tryAcquire(1L)) {
-                if (k == 0) {
-                    acquire(1L);
-                    break;
-                }
-                --k;
-            }
-        }
-
-        final long awaitAvailability() {
-            long s;
-            while (((s = getState()) & 1L) != 0L &&
-                   getExclusiveOwnerThread() != Thread.currentThread()) {
-                acquireShared(1L);
-                releaseShared(1L);
-            }
-            return s;
-        }
-
-        final long tryAwaitAvailability(long nanos)
-            throws InterruptedException, TimeoutException {
-            Thread current = Thread.currentThread();
-            for (;;) {
-                long s = getState();
-                if ((s & 1L) == 0L || getExclusiveOwnerThread() == current) {
-                    releaseShared(1L);
-                    return s;
-                }
-                if (!tryAcquireSharedNanos(1L, nanos))
-                    throw new TimeoutException();
-                // since tryAcquireSharedNanos doesn't return seq
-                // retry with minimal wait time.
-                nanos = 1L;
-            }
-        }
-
-        final boolean isLocked() {
-            return (getState() & 1L) != 0L;
-        }
-
-        final Thread getOwner() {
-            return (getState() & 1L) == 0L ? null : getExclusiveOwnerThread();
-        }
-
-        final long getHoldCount() {
-            return isHeldExclusively() ? holds : 0;
-        }
-
-        private void readObject(ObjectInputStream s)
-            throws IOException, ClassNotFoundException {
-            s.defaultReadObject();
-            holds = 0L;
-            setState(0L); // reset to unlocked state
-        }
-    }
-
-    private final Sync sync;
-
-    /**
-     * The default spin value for constructor. Future versions of this
-     * class might choose platform-specific values.  Currently, except
-     * on uniprocessors, it is set to a small value that overcomes near
-     * misses between releases and acquires.
-     */
-    static final int DEFAULT_SPINS =
-        Runtime.getRuntime().availableProcessors() > 1 ? 64 : 0;
-
-    /**
-     * Creates an instance of {@code SequenceLock} with the default
-     * number of retry attempts to acquire the lock before blocking.
-     */
-    public SequenceLock() { sync = new Sync(DEFAULT_SPINS); }
-
-    /**
-     * Creates an instance of {@code SequenceLock} that will retry
-     * attempts to acquire the lock at least the given number times
-     * before blocking.
-     */
-    public SequenceLock(int spins) { sync = new Sync(spins); }
-
-    /**
-     * Returns the current sequence number of this lock.  The sequence
-     * number is advanced upon each acquire or release action. When
-     * this value is odd, the lock is held; when even, it is released.
-     *
-     * @return the current sequence number
-     */
-    public long getSequence() { return sync.getSequence(); }
-
-    /**
-     * Returns the current sequence number when the lock is, or
-     * becomes, available. A lock is available if it is either
-     * released, or is held by the current thread.  If the lock is not
-     * available, the current thread becomes disabled for thread
-     * scheduling purposes and lies dormant until the lock has been
-     * released by some other thread.
-     *
-     * @return the current sequence number
-     */
-    public long awaitAvailability() { return sync.awaitAvailability(); }
-
-    /**
-     * Returns the current sequence number if the lock is, or
-     * becomes, available within the specified waiting time.
-     *
-     * <p>If the lock is not available, the current thread becomes
-     * disabled for thread scheduling purposes and lies dormant until
-     * one of three things happens:
-     *
-     * <ul>
-     *
-     * <li>The lock becomes available, in which case the current
-     * sequence number is returned.
-     *
-     * <li>Some other thread {@linkplain Thread#interrupt interrupts}
-     * the current thread, in which case this method throws
-     * {@link InterruptedException}.
-     *
-     * <li>The specified waiting time elapses, in which case
-     * this method throws {@link TimeoutException}.
-     *
-     * </ul>
-     *
-     * @param timeout the time to wait for availability
-     * @param unit the time unit of the timeout argument
-     * @return the current sequence number if the lock is available
-     *         upon return from this method
-     * @throws InterruptedException if the current thread is interrupted
-     * @throws TimeoutException if the lock was not available within
-     * the specified waiting time
-     * @throws NullPointerException if the time unit is null
-     */
-    public long tryAwaitAvailability(long timeout, TimeUnit unit)
-        throws InterruptedException, TimeoutException {
-        return sync.tryAwaitAvailability(unit.toNanos(timeout));
-    }
-
-    /**
-     * Acquires the lock.
-     *
-     * <p>If the current thread already holds this lock then the hold count
-     * is incremented by one and the method returns immediately without
-     * incrementing the sequence number.
-     *
-     * <p>If this lock not held by another thread, this method
-     * increments the sequence number (which thus becomes an odd
-     * number), sets the lock hold count to one, and returns
-     * immediately.
-     *
-     * <p>If the lock is held by another thread then the current
-     * thread may retry acquiring this lock, depending on the {@code
-     * spin} count established in constructor.  If the lock is still
-     * not acquired, the current thread becomes disabled for thread
-     * scheduling purposes and lies dormant until enabled by
-     * some other thread rel