--- jsr166/src/jsr166y/ForkJoinTask.java 2010/07/07 19:52:31 1.49
+++ jsr166/src/jsr166y/ForkJoinTask.java 2011/02/22 10:50:51 1.75
@@ -6,15 +6,26 @@
package jsr166y;
-import java.util.concurrent.*;
-
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.RandomAccess;
import java.util.Map;
-import java.util.WeakHashMap;
+import java.lang.ref.WeakReference;
+import java.lang.ref.ReferenceQueue;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Future;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.RunnableFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.locks.ReentrantLock;
+import java.lang.reflect.Constructor;
/**
* Abstract base class for tasks that run within a {@link ForkJoinPool}.
@@ -28,10 +39,10 @@ import java.util.WeakHashMap;
* start other subtasks. As indicated by the name of this class,
* many programs using {@code ForkJoinTask} employ only methods
* {@link #fork} and {@link #join}, or derivatives such as {@link
- * #invokeAll}. However, this class also provides a number of other
- * methods that can come into play in advanced usages, as well as
- * extension mechanics that allow support of new forms of fork/join
- * processing.
+ * #invokeAll(ForkJoinTask...) invokeAll}. However, this class also
+ * provides a number of other methods that can come into play in
+ * advanced usages, as well as extension mechanics that allow
+ * support of new forms of fork/join processing.
*
*
A {@code ForkJoinTask} is a lightweight form of {@link Future}.
* The efficiency of {@code ForkJoinTask}s stems from a set of
@@ -58,7 +69,11 @@ import java.util.WeakHashMap;
* rethrown to callers attempting to join them. These exceptions may
* additionally include {@link RejectedExecutionException} stemming
* from internal resource exhaustion, such as failure to allocate
- * internal task queues.
+ * internal task queues. Rethrown exceptions behave in the same way as
+ * regular exceptions, but, when possible, contain stack traces (as
+ * displayed for example using {@code ex.printStackTrace()}) of both
+ * the thread that initiated the computation as well as the thread
+ * actually encountering the exception; minimally only the latter.
*
*
The primary method for awaiting completion and extracting
* results of a task is {@link #join}, but there are several variants:
@@ -100,7 +115,17 @@ import java.util.WeakHashMap;
* ForkJoinTasks (as may be determined using method {@link
* #inForkJoinPool}). Attempts to invoke them in other contexts
* result in exceptions or errors, possibly including
- * ClassCastException.
+ * {@code ClassCastException}.
+ *
+ *
Method {@link #join} and its variants are appropriate for use
+ * only when completion dependencies are acyclic; that is, the
+ * parallel computation can be described as a directed acyclic graph
+ * (DAG). Otherwise, executions may encounter a form of deadlock as
+ * tasks cyclically wait for each other. However, this framework
+ * supports other methods and techniques (for example the use of
+ * {@link Phaser}, {@link #helpQuiesce}, and {@link #complete}) that
+ * may be of use in constructing custom subclasses for problems that
+ * are not statically structured as DAGs.
*
*
Most base support methods are {@code final}, to prevent
* overriding of implementations that are intrinsically tied to the
@@ -116,9 +141,10 @@ import java.util.WeakHashMap;
* computation. Large tasks should be split into smaller subtasks,
* usually via recursive decomposition. As a very rough rule of thumb,
* a task should perform more than 100 and less than 10000 basic
- * computational steps. If tasks are too big, then parallelism cannot
- * improve throughput. If too small, then memory and internal task
- * maintenance overhead may overwhelm processing.
+ * computational steps, and should avoid indefinite looping. If tasks
+ * are too big, then parallelism cannot improve throughput. If too
+ * small, then memory and internal task maintenance overhead may
+ * overwhelm processing.
*
*
This class provides {@code adapt} methods for {@link Runnable}
* and {@link Callable}, that may be of use when mixing execution of
@@ -147,112 +173,120 @@ public abstract class ForkJoinTask im
* in a way that flows well in javadocs.
*/
- /**
- * Run control status bits packed into a single int to minimize
- * footprint and to ensure atomicity (via CAS). Status is
- * initially zero, and takes on nonnegative values until
- * completed, upon which status holds value COMPLETED. CANCELLED,
- * or EXCEPTIONAL. Tasks undergoing blocking waits by other
- * threads have the SIGNAL bit set. Completion of a stolen task
- * with SIGNAL set awakens any waiters via notifyAll. Even though
- * suboptimal for some purposes, we use basic builtin wait/notify
- * to take advantage of "monitor inflation" in JVMs that we would
- * otherwise need to emulate to avoid adding further per-task
- * bookkeeping overhead. We want these monitors to be "fat",
- * i.e., not use biasing or thin-lock techniques, so use some odd
- * coding idioms that tend to avoid them.
+ /*
+ * The status field holds run control status bits packed into a
+ * single int to minimize footprint and to ensure atomicity (via
+ * CAS). Status is initially zero, and takes on nonnegative
+ * values until completed, upon which status holds value
+ * NORMAL, CANCELLED, or EXCEPTIONAL. Tasks undergoing blocking
+ * waits by other threads have the SIGNAL bit set. Completion of
+ * a stolen task with SIGNAL set awakens any waiters via
+ * notifyAll. Even though suboptimal for some purposes, we use
+ * basic builtin wait/notify to take advantage of "monitor
+ * inflation" in JVMs that we would otherwise need to emulate to
+ * avoid adding further per-task bookkeeping overhead. We want
+ * these monitors to be "fat", i.e., not use biasing or thin-lock
+ * techniques, so use some odd coding idioms that tend to avoid
+ * them.
*/
- volatile int status; // accessed directly by pool and workers
+ /** The run status of this task */
+ volatile int status; // accessed directly by pool and workers
private static final int NORMAL = -1;
private static final int CANCELLED = -2;
private static final int EXCEPTIONAL = -3;
private static final int SIGNAL = 1;
/**
- * Table of exceptions thrown by tasks, to enable reporting by
- * callers. Because exceptions are rare, we don't directly keep
- * them with task objects, but instead use a weak ref table. Note
- * that cancellation exceptions don't appear in the table, but are
- * instead recorded as status values.
- * TODO: Use ConcurrentReferenceHashMap
- */
- static final Map, Throwable> exceptionMap =
- Collections.synchronizedMap
- (new WeakHashMap, Throwable>());
-
- // Maintaining completion status
-
- /**
* Marks completion and wakes up threads waiting to join this task,
* also clearing signal request bits.
*
* @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
- * @return status on exit
+ * @return completion status on exit
*/
private int setCompletion(int completion) {
- int s;
- while ((s = status) >= 0) {
+ for (int s;;) {
+ if ((s = status) < 0)
+ return s;
if (UNSAFE.compareAndSwapInt(this, statusOffset, s, completion)) {
- if (s == SIGNAL)
+ if (s != 0)
synchronized (this) { notifyAll(); }
return completion;
}
}
- return s;
}
/**
- * Record exception and set exceptional completion
- * @return status on exit
+ * Tries to block a worker thread until completed or timed out.
+ * Uses Object.wait time argument conventions.
+ * May fail on contention or interrupt.
+ *
+ * @param millis if > 0, wait time.
*/
- private int setExceptionalCompletion(Throwable rex) {
- exceptionMap.put(this, rex);
- return setCompletion(EXCEPTIONAL);
+ final void tryAwaitDone(long millis) {
+ int s;
+ try {
+ if (((s = status) > 0 ||
+ (s == 0 &&
+ UNSAFE.compareAndSwapInt(this, statusOffset, 0, SIGNAL))) &&
+ status > 0) {
+ synchronized (this) {
+ if (status > 0)
+ wait(millis);
+ }
+ }
+ } catch (InterruptedException ie) {
+ // caller must check termination
+ }
}
/**
- * Blocks a worker thread until completion. Called only by pool.
+ * Blocks a non-worker-thread until completion.
+ * @return status upon completion
*/
- final int internalAwaitDone() {
+ private int externalAwaitDone() {
int s;
- while ((s = status) >= 0) {
- synchronized(this) {
- if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)) {
- do {
+ if ((s = status) >= 0) {
+ boolean interrupted = false;
+ synchronized (this) {
+ while ((s = status) >= 0) {
+ if (s == 0)
+ UNSAFE.compareAndSwapInt(this, statusOffset,
+ 0, SIGNAL);
+ else {
try {
wait();
} catch (InterruptedException ie) {
- cancelIfTerminating();
+ interrupted = true;
}
- } while ((s = status) >= 0);
- break;
+ }
}
}
+ if (interrupted)
+ Thread.currentThread().interrupt();
}
return s;
}
/**
- * Blocks a non-worker-thread until completion.
- * @return status on exit
+ * Blocks a non-worker-thread until completion or interruption or timeout.
*/
- private int externalAwaitDone() {
+ private int externalInterruptibleAwaitDone(long millis)
+ throws InterruptedException {
int s;
- while ((s = status) >= 0) {
- synchronized(this) {
- if (UNSAFE.compareAndSwapInt(this, statusOffset, s, SIGNAL)){
- boolean interrupted = false;
- do {
- try {
- wait();
- } catch (InterruptedException ie) {
- interrupted = true;
- }
- } while ((s = status) >= 0);
- if (interrupted)
- Thread.currentThread().interrupt();
- break;
+ if (Thread.interrupted())
+ throw new InterruptedException();
+ if ((s = status) >= 0) {
+ synchronized (this) {
+ while ((s = status) >= 0) {
+ if (s == 0)
+ UNSAFE.compareAndSwapInt(this, statusOffset,
+ 0, SIGNAL);
+ else {
+ wait(millis);
+ if (millis > 0L)
+ break;
+ }
}
}
}
@@ -260,35 +294,34 @@ public abstract class ForkJoinTask im
}
/**
- * Unless done, calls exec and records status if completed, but
- * doesn't wait for completion otherwise. Primary execution method
- * for ForkJoinWorkerThread.
+ * Primary execution method for stolen tasks. Unless done, calls
+ * exec and records status if completed, but doesn't wait for
+ * completion otherwise.
*/
- final void tryExec() {
- try {
- if (status < 0 || !exec())
+ final void doExec() {
+ if (status >= 0) {
+ boolean completed;
+ try {
+ completed = exec();
+ } catch (Throwable rex) {
+ setExceptionalCompletion(rex);
return;
- } catch (Throwable rex) {
- setExceptionalCompletion(rex);
- return;
+ }
+ if (completed)
+ setCompletion(NORMAL); // must be outside try block
}
- setCompletion(NORMAL); // must be outside try block
}
/**
- * If not done and this task is next in worker queue, runs it,
- * else waits for it.
- * @return status on exit
+ * Primary mechanics for join, get, quietlyJoin.
+ * @return status upon completion
*/
private int doJoin() {
- int stat;
- if ((stat = status) < 0)
- return stat;
- Thread t = Thread.currentThread();
- ForkJoinWorkerThread w;
- if (t instanceof ForkJoinWorkerThread) {
- if ((w = (ForkJoinWorkerThread) t).unpushTask(this)) {
- boolean completed;
+ Thread t; ForkJoinWorkerThread w; int s; boolean completed;
+ if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
+ if ((s = status) < 0)
+ return s;
+ if ((w = (ForkJoinWorkerThread)t).unpushTask(this)) {
try {
completed = exec();
} catch (Throwable rex) {
@@ -297,41 +330,241 @@ public abstract class ForkJoinTask im
if (completed)
return setCompletion(NORMAL);
}
- w.joinTask(this);
- return status;
+ return w.joinTask(this);
}
- return externalAwaitDone();
+ else
+ return externalAwaitDone();
}
/**
- * Unless done, calls exec and records status if completed, or
- * waits for completion otherwise.
- * @return status on exit
+ * Primary mechanics for invoke, quietlyInvoke.
+ * @return status upon completion
*/
private int doInvoke() {
- int stat;
- if ((stat = status) >= 0) {
- boolean completed;
- try {
- completed = exec();
- } catch (Throwable rex) {
- return setExceptionalCompletion(rex);
+ int s; boolean completed;
+ if ((s = status) < 0)
+ return s;
+ try {
+ completed = exec();
+ } catch (Throwable rex) {
+ return setExceptionalCompletion(rex);
+ }
+ if (completed)
+ return setCompletion(NORMAL);
+ else
+ return doJoin();
+ }
+
+ // Exception table support
+
+ /**
+ * Table of exceptions thrown by tasks, to enable reporting by
+ * callers. Because exceptions are rare, we don't directly keep
+ * them with task objects, but instead use a weak ref table. Note
+ * that cancellation exceptions don't appear in the table, but are
+ * instead recorded as status values.
+ *
+ * Note: These statics are initialized below in static block.
+ */
+ private static final ExceptionNode[] exceptionTable;
+ private static final ReentrantLock exceptionTableLock;
+ private static final ReferenceQueue