提交 381e10cf 编写于 作者: P psandoz

8019370: Sync j.u.c Fork/Join from 166 to tl

Reviewed-by: chegar, martin
Contributed-by: NDoug Lea <dl@cs.oswego.edu>
上级 605a051c
......@@ -38,19 +38,19 @@ import java.util.*;
/**
* 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
* <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 @@ import java.util.*;
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 @@ public abstract class AbstractExecutorService implements ExecutorService {
}
/**
* 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 @@ public abstract class AbstractExecutorService implements ExecutorService {
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 @@ public abstract class AbstractExecutorService implements ExecutorService {
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 @@ public abstract class AbstractExecutorService implements ExecutorService {
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 @@ public abstract class AbstractExecutorService implements ExecutorService {
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 @@ public abstract class AbstractExecutorService implements ExecutorService {
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 @@ public abstract class AbstractExecutorService implements ExecutorService {
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 @@ public abstract class AbstractExecutorService implements ExecutorService {
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);
}
}
......
......@@ -38,21 +38,21 @@ package java.util.concurrent;
/**
* 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.
* <p>The {@link Executors} class contains utility methods to
* 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> {
/**
......
......@@ -47,12 +47,12 @@ public class CancellationException extends IllegalStateException {
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
......
......@@ -1209,7 +1209,7 @@ public class CompletableFuture<T> implements Future<T> {
(r = a.result) != null &&
compareAndSet(0, 1)) {
if ((r instanceof AltResult) &&
(ex = ((AltResult)r).ex) != null) {
(ex = ((AltResult)r).ex) != null) {
try {
t = fn.apply(ex);
} catch (Throwable rex) {
......@@ -2892,7 +2892,7 @@ public class CompletableFuture<T> implements Future<T> {
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) {
if ((ex = ((AltResult)r).ex) != null) {
try {
t = fn.apply(ex);
} catch (Throwable rex) {
......
......@@ -38,17 +38,17 @@ package java.util.concurrent;
/**
* 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 @@ public interface CompletionService<V> {
* @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 @@ public interface CompletionService<V> {
/**
* 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 @@ public interface CompletionService<V> {
* 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
*/
......
......@@ -37,14 +37,15 @@ package java.util.concurrent;
/**
* A {@link ForkJoinTask} with a completion action performed when
* triggered and there are no remaining pending
* actions. CountedCompleters are in general more robust in the
* triggered and there are no remaining pending actions.
* CountedCompleters are in general more robust in the
* presence of subtask stalls and blockage than are other forms of
* ForkJoinTasks, but are less intuitive to program. Uses of
* 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 @@ package java.util.concurrent;
* <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 @@ package java.util.concurrent;
* 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>
*
......@@ -125,8 +128,8 @@ package java.util.concurrent;
* improve load balancing. In the recursive case, the second of each
* pair of subtasks to finish triggers completion of its parent
* (because no result combination is performed, the default no-op
* implementation of method {@code onCompletion} is not overridden). A
* static utility method sets up the base task and invokes it
* implementation of method {@code onCompletion} is not overridden).
* A static utility method sets up the base task and invokes it
* (here, implicitly using the {@link ForkJoinPool#commonPool()}).
*
* <pre> {@code
......@@ -181,12 +184,11 @@ package java.util.concurrent;
* }
* }</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> ...
......@@ -253,7 +255,7 @@ package java.util.concurrent;
* public static <E> E search(E[] array) {
* return new Searcher<E>(null, array, new AtomicReference<E>(), 0, array.length).invoke();
* }
*}}</pre>
* }}</pre>
*
* In this example, as well as others in which tasks have no other
* effects except to compareAndSet a common result, the trailing
......@@ -264,7 +266,7 @@ package java.util.concurrent;
*
* <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 @@ package java.util.concurrent;
* 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)
......@@ -386,7 +388,7 @@ package java.util.concurrent;
*
* <p><b>Triggers.</b> Some CountedCompleters are themselves never
* forked, but instead serve as bits of plumbing in other designs;
* including those in which the completion of one of more async tasks
* including those in which the completion of one or more async tasks
* triggers another async task. For example:
*
* <pre> {@code
......@@ -460,27 +462,28 @@ public abstract class CountedCompleter<T> extends ForkJoinTask<T> {
* (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}
* 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
* ForkJoinTask#isCompletedAbnormally}. The return value of this
* method controls further propagation: If {@code true} and this
* task has a completer, then this completer is also completed
* exceptionally. The default implementation of this method does
* nothing except return {@code true}.
* Performs an action when method {@link
* #completeExceptionally(Throwable)} is invoked or method {@link
* #compute} throws an exception, and this task has not already
* otherwise completed normally. On entry to this method, this task
* {@link ForkJoinTask#isCompletedAbnormally}. The return value
* of this method controls further propagation: If {@code true}
* and this task has a completer that has not completed, then that
* completer is also completed exceptionally, with the same
* exception as this completer. The default implementation of
* this method does nothing except return {@code true}.
*
* @param ex the exception
* @param caller the task invoking this method (which may
* be this task itself).
* @return true if this exception should be propagated to this
* task's completer, if one exists.
* be this task itself)
* @return {@code true} if this exception should be propagated to this
* task's completer, if one exists
*/
public boolean onExceptionalCompletion(Throwable ex, CountedCompleter<?> caller) {
return true;
......@@ -520,8 +523,7 @@ public abstract class CountedCompleter<T> extends ForkJoinTask<T> {
* @param delta the value to add
*/
public final void addToPendingCount(int delta) {
int c; // note: can replace with intrinsic in jdk8
do {} while (!U.compareAndSwapInt(this, PENDING, c = pending, c+delta));
U.getAndAddInt(this, PENDING, delta);
}
/**
......@@ -530,7 +532,7 @@ public abstract class CountedCompleter<T> extends ForkJoinTask<T> {
*
* @param expected the expected value
* @param count the new value
* @return true if successful
* @return {@code true} if successful
*/
public final boolean compareAndSetPendingCount(int expected, int count) {
return U.compareAndSwapInt(this, PENDING, expected, count);
......@@ -564,9 +566,9 @@ public abstract class CountedCompleter<T> extends ForkJoinTask<T> {
/**
* 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 @@ public abstract class CountedCompleter<T> extends ForkJoinTask<T> {
/**
* 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,15 @@ public abstract class CountedCompleter<T> extends ForkJoinTask<T> {
}
/**
* 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}. This method does not modify
* the pending count.
*
* <p>This method may be useful when forcing completion as soon as
* any one (versus all) of several subtask results are obtained.
......@@ -632,7 +636,6 @@ public abstract class CountedCompleter<T> extends ForkJoinTask<T> {
p.tryComplete();
}
/**
* If this task's pending count is zero, returns this task;
* otherwise decrements its pending count and returns {@code
......@@ -653,8 +656,8 @@ public abstract class CountedCompleter<T> extends ForkJoinTask<T> {
/**
* 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:
*
......@@ -690,14 +693,35 @@ public abstract class CountedCompleter<T> extends ForkJoinTask<T> {
}
}
/**
* If this task has not completed, attempts to process at most the
* given number of other unprocessed tasks for which this task is
* on the completion path, if any are known to exist.
*
* @param maxTasks the maximum number of tasks to process. If
* less than or equal to zero, then no tasks are
* processed.
*/
public final void helpComplete(int maxTasks) {
Thread t; ForkJoinWorkerThread wt;
if (maxTasks > 0 && status >= 0) {
if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
(wt = (ForkJoinWorkerThread)t).pool.
helpComplete(wt.workQueue, this, maxTasks);
else
ForkJoinPool.common.externalHelpComplete(this, maxTasks);
}
}
/**
* Supports ForkJoinTask exception propagation.
*/
void internalPropagateException(Throwable ex) {
CountedCompleter<?> a = this, s = a;
while (a.onExceptionalCompletion(ex, s) &&
(a = (s = a).completer) != null && a.status >= 0)
a.recordExceptionalCompletion(ex);
(a = (s = a).completer) != null && a.status >= 0 &&
a.recordExceptionalCompletion(ex) == EXCEPTIONAL)
;
}
/**
......
......@@ -48,14 +48,14 @@ public class ExecutionException extends Exception {
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 @@ public class ExecutionException extends Exception {
}
/**
* 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 @@ public class ExecutionException extends Exception {
}
/**
* 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}).
......
......@@ -39,9 +39,9 @@ package java.util.concurrent;
* 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 @@ package java.util.concurrent;
* ...
* </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 @@ package java.util.concurrent;
* }
* }}</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 @@ package java.util.concurrent;
* }
* }}</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 @@ public interface Executor {
/**
* 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);
......
......@@ -42,21 +42,21 @@ import java.util.Collection;
* 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 @@ import java.util.Collection;
* }
* }}</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 @@ public interface ExecutorService extends Executor {
* 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 @@ public interface ExecutorService extends Executor {
* 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 @@ public interface ExecutorService extends Executor {
*
* @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,15 +213,15 @@ public interface ExecutorService extends Executor {
/**
* 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
* <p>Note: The {@link Executors} class includes a set of methods
* that can convert some other common closure-like objects,
* for example, {@link java.security.PrivilegedAction} to
* {@link Callable} form so they can be submitted.
......@@ -236,7 +236,7 @@ public interface ExecutorService extends Executor {
/**
* 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 @@ public interface ExecutorService extends Executor {
/**
* 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 @@ public interface ExecutorService extends Executor {
/**
* 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 @@ public interface ExecutorService extends Executor {
* 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 @@ public interface ExecutorService extends Executor {
* 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 @@ public interface ExecutorService extends Executor {
* @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 @@ public interface ExecutorService extends Executor {
* @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 @@ public interface ExecutorService extends Executor {
* @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
......
......@@ -62,7 +62,7 @@ import sun.security.util.SecurityConstants;
* 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 @@ public class Executors {
/**
* 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
......@@ -91,11 +91,48 @@ public class Executors {
new LinkedBlockingQueue<Runnable>());
}
/**
* 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
* @see #newWorkStealingPool(int)
* @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 +162,7 @@ public class Executors {
* 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 +178,7 @@ public class Executors {
* 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 +201,7 @@ public class Executors {
* 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 +243,7 @@ public class Executors {
* 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 +260,7 @@ public class Executors {
* 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 +277,7 @@ public class Executors {
* 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 +289,9 @@ public class Executors {
* 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 +301,6 @@ public class Executors {
return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
}
/**
* Returns an object that delegates all defined {@link
* ExecutorService} methods to the given executor, but not any
......@@ -272,7 +308,7 @@ public class Executors {
* 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 +324,7 @@ public class Executors {
* 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 +339,9 @@ public class Executors {
* 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,30 +360,31 @@ public class Executors {
* 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
* <p>Note that while tasks running within such threads will have
* the same access control and class loader settings as the
* current thread, they need not have the same {@link
* java.lang.ThreadLocal} or {@link
* 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 +394,7 @@ public class Executors {
* 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 +408,7 @@ public class Executors {
/**
* 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 +449,17 @@ public class Executors {
}
/**
* 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 +468,23 @@ public class Executors {
}
/**
* 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
*
* @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 +736,6 @@ public class Executors {
}
}
/** Cannot instantiate. */
private Executors() {}
}
......@@ -165,7 +165,7 @@ import java.lang.reflect.Constructor;
* 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. To support such usages a
* are not statically structured as DAGs. To support such usages, a
* ForkJoinTask may be atomically <em>tagged</em> with a {@code short}
* value using {@link #setForkJoinTaskTag} or {@link
* #compareAndSetForkJoinTaskTag} and checked using {@link
......@@ -314,25 +314,35 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
*/
private int externalAwaitDone() {
int s;
ForkJoinPool.externalHelpJoin(this);
boolean interrupted = false;
while ((s = status) >= 0) {
if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
synchronized (this) {
if (status >= 0) {
try {
wait();
} catch (InterruptedException ie) {
interrupted = true;
ForkJoinPool cp = ForkJoinPool.common;
if ((s = status) >= 0) {
if (cp != null) {
if (this instanceof CountedCompleter)
s = cp.externalHelpComplete((CountedCompleter<?>)this, Integer.MAX_VALUE);
else if (cp.tryExternalUnpush(this))
s = doExec();
}
if (s >= 0 && (s = status) >= 0) {
boolean interrupted = false;
do {
if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
synchronized (this) {
if (status >= 0) {
try {
wait();
} catch (InterruptedException ie) {
interrupted = true;
}
}
else
notifyAll();
}
}
else
notifyAll();
}
} while ((s = status) >= 0);
if (interrupted)
Thread.currentThread().interrupt();
}
}
if (interrupted)
Thread.currentThread().interrupt();
return s;
}
......@@ -341,9 +351,15 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
*/
private int externalInterruptibleAwaitDone() throws InterruptedException {
int s;
ForkJoinPool cp = ForkJoinPool.common;
if (Thread.interrupted())
throw new InterruptedException();
ForkJoinPool.externalHelpJoin(this);
if ((s = status) >= 0 && cp != null) {
if (this instanceof CountedCompleter)
cp.externalHelpComplete((CountedCompleter<?>)this, Integer.MAX_VALUE);
else if (cp.tryExternalUnpush(this))
doExec();
}
while ((s = status) >= 0) {
if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
synchronized (this) {
......@@ -357,7 +373,6 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
return s;
}
/**
* Implementation for join, get, quietlyJoin. Directly handles
* only cases of already-completed, external wait, and
......@@ -629,14 +644,9 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
/**
* A version of "sneaky throw" to relay exceptions
*/
static void rethrow(final Throwable ex) {
if (ex != null) {
if (ex instanceof Error)
throw (Error)ex;
if (ex instanceof RuntimeException)
throw (RuntimeException)ex;
static void rethrow(Throwable ex) {
if (ex != null)
ForkJoinTask.<RuntimeException>uncheckedThrow(ex);
}
}
/**
......@@ -646,8 +656,7 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
*/
@SuppressWarnings("unchecked") static <T extends Throwable>
void uncheckedThrow(Throwable t) throws T {
if (t != null)
throw (T)t; // rely on vacuous cast
throw (T)t; // rely on vacuous cast
}
/**
......@@ -1010,6 +1019,7 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
// Messy in part because we measure in nanosecs, but wait in millisecs
int s; long ms;
long ns = unit.toNanos(timeout);
ForkJoinPool cp;
if ((s = status) >= 0 && ns > 0L) {
long deadline = System.nanoTime() + ns;
ForkJoinPool p = null;
......@@ -1021,8 +1031,12 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
w = wt.workQueue;
p.helpJoinOnce(w, this); // no retries on failure
}
else
ForkJoinPool.externalHelpJoin(this);
else if ((cp = ForkJoinPool.common) != null) {
if (this instanceof CountedCompleter)
cp.externalHelpComplete((CountedCompleter<?>)this, Integer.MAX_VALUE);
else if (cp.tryExternalUnpush(this))
doExec();
}
boolean canBlock = false;
boolean interrupted = false;
try {
......@@ -1030,7 +1044,7 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
if (w != null && w.qlock < 0)
cancelIgnoringExceptions(this);
else if (!canBlock) {
if (p == null || p.tryCompensate())
if (p == null || p.tryCompensate(p.ctl))
canBlock = true;
}
else {
......@@ -1171,7 +1185,7 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
Thread t;
return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ?
((ForkJoinWorkerThread)t).workQueue.tryUnpush(this) :
ForkJoinPool.tryExternalUnpush(this));
ForkJoinPool.common.tryExternalUnpush(this));
}
/**
......@@ -1340,7 +1354,7 @@ public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
*
* @param e the expected tag value
* @param tag the new tag value
* @return true if successful; i.e., the current value was
* @return {@code true} if successful; i.e., the current value was
* equal to e and is now tag.
* @since 1.8
*/
......
......@@ -43,8 +43,8 @@ package java.util.concurrent;
* scheduling or execution. However, you can override initialization
* and termination methods surrounding the main task processing loop.
* If you do create such a subclass, you will also need to supply a
* custom {@link ForkJoinPool.ForkJoinWorkerThreadFactory} to use it
* in a {@code ForkJoinPool}.
* custom {@link ForkJoinPool.ForkJoinWorkerThreadFactory} to
* {@linkplain ForkJoinPool#ForkJoinPool use it} in a {@code ForkJoinPool}.
*
* @since 1.7
* @author Doug Lea
......@@ -89,16 +89,17 @@ public class ForkJoinWorkerThread extends Thread {
}
/**
* Returns the index number of this thread in its pool. The
* returned value ranges from zero to the maximum number of
* threads (minus one) that have ever been created in the pool.
* This method may be useful for applications that track status or
* collect results per-worker rather than per-task.
* Returns the unique index number of this thread in its pool.
* The returned value ranges from zero to the maximum number of
* threads (minus one) that may exist in the pool, and does not
* change during the lifetime of the thread. This method may be
* useful for applications that track status or collect results
* per-worker-thread rather than per-task.
*
* @return the index number
*/
public int getPoolIndex() {
return workQueue.poolIndex;
return workQueue.poolIndex >>> 1; // ignore odd/even tag bit
}
/**
......
......@@ -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 @@ package java.util.concurrent;
* }
* }}</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 @@ package java.util.concurrent;
* @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 @@ public interface Future<V> {
* 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();
......
......@@ -162,19 +162,23 @@ public class FutureTask<V> implements RunnableFuture<V> {
}
public boolean cancel(boolean mayInterruptIfRunning) {
if (state != NEW)
if (!(state == NEW &&
UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
return false;
if (mayInterruptIfRunning) {
if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, INTERRUPTING))
return false;
Thread t = runner;
if (t != null)
t.interrupt();
UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED); // final state
try { // in case call to interrupt throws exception
if (mayInterruptIfRunning) {
try {
Thread t = runner;
if (t != null)
t.interrupt();
} finally { // final state
UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
}
}
} finally {
finishCompletion();
}
else if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, CANCELLED))
return false;
finishCompletion();
return true;
}
......@@ -288,7 +292,7 @@ public class FutureTask<V> implements RunnableFuture<V> {
* designed for use with tasks that intrinsically execute more
* than once.
*
* @return true if successfully run and reset
* @return {@code true} if successfully run and reset
*/
protected boolean runAndReset() {
if (state != NEW ||
......
......@@ -63,7 +63,7 @@ package java.util.concurrent;
* }
* }
* // implementation details follow:
* final static int THRESHOLD = 1000;
* static final int THRESHOLD = 1000;
* void sortSequentially(int lo, int hi) {
* Arrays.sort(array, lo, hi);
* }
......@@ -140,21 +140,21 @@ package java.util.concurrent;
* int h = hi;
* Applyer right = null;
* while (h - l > 1 && getSurplusQueuedTaskCount() <= 3) {
* int mid = (l + h) >>> 1;
* right = new Applyer(array, mid, h, right);
* right.fork();
* h = mid;
* int mid = (l + h) >>> 1;
* right = new Applyer(array, mid, h, right);
* right.fork();
* h = mid;
* }
* double sum = atLeaf(l, h);
* while (right != null) {
* if (right.tryUnfork()) // directly calculate if not stolen
* sum += right.atLeaf(right.lo, right.hi);
* if (right.tryUnfork()) // directly calculate if not stolen
* sum += right.atLeaf(right.lo, right.hi);
* else {
* right.join();
* sum += right.result;
* }
* right = right.next;
* }
* right.join();
* sum += right.result;
* }
* right = right.next;
* }
* result = sum;
* }
* }}</pre>
......
......@@ -46,7 +46,7 @@ package java.util.concurrent;
* Fibonacci(int n) { this.n = n; }
* Integer compute() {
* if (n <= 1)
* return n;
* return n;
* Fibonacci f1 = new Fibonacci(n - 1);
* f1.fork();
* Fibonacci f2 = new Fibonacci(n - 2);
......@@ -75,6 +75,7 @@ public abstract class RecursiveTask<V> extends ForkJoinTask<V> {
/**
* The main computation performed by this task.
* @return the result of the computation
*/
protected abstract V compute();
......
......@@ -46,14 +46,14 @@ public class RejectedExecutionException extends RuntimeException {
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 @@ public class RejectedExecutionException extends RuntimeException {
}
/**
* 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 @@ public class RejectedExecutionException extends RuntimeException {
}
/**
* 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)
......
......@@ -37,13 +37,13 @@ package java.util.concurrent;
/**
* 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> {
/**
......
......@@ -37,22 +37,22 @@ package java.util.concurrent;
/**
* 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> {
/**
* Returns true if this is a periodic task. A periodic task may
* Returns {@code true} if this task is periodic. A periodic task may
* re-run according to some schedule. A non-periodic task can be
* run only once.
*
* @return true if this task is periodic
* @return {@code true} if this task is periodic
*/
boolean isPeriodic();
}
......@@ -39,30 +39,30 @@ package java.util.concurrent;
* 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.
*
* The {@link Executors} class provides convenient factory methods for
* <p>The {@link Executors} class provides convenient factory methods for
* the ScheduledExecutorService implementations provided in this package.
*
* <h3>Usage Example</h3>
......@@ -101,8 +101,8 @@ public interface ScheduledExecutorService extends ExecutorService {
* @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 @@ public interface ScheduledExecutorService extends ExecutorService {
* 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 @@ public interface ScheduledExecutorService extends ExecutorService {
* @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 @@ public interface ScheduledExecutorService extends ExecutorService {
* 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
......
......@@ -81,7 +81,7 @@ import java.util.*;
* 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
......@@ -256,9 +256,9 @@ public class ScheduledThreadPoolExecutor
}
/**
* Returns true if this is a periodic (not a one-shot) action.
* Returns {@code true} if this is a periodic (not a one-shot) action.
*
* @return true if periodic
* @return {@code true} if periodic
*/
public boolean isPeriodic() {
return period != 0;
......@@ -315,7 +315,7 @@ public class ScheduledThreadPoolExecutor
* 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 @@ public class ScheduledThreadPoolExecutor
* {@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 @@ public class ScheduledThreadPoolExecutor
* {@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) {
......@@ -1081,7 +1081,8 @@ public class ScheduledThreadPoolExecutor
long delay = first.getDelay(NANOSECONDS);
if (delay <= 0)
return finishPoll(first);
else if (leader != null)
first = null; // don't retain ref while waiting
if (leader != null)
available.await();
else {
Thread thisThread = Thread.currentThread();
......@@ -1121,6 +1122,7 @@ public class ScheduledThreadPoolExecutor
return finishPoll(first);
if (nanos <= 0)
return null;
first = null; // don't retain ref while waiting
if (nanos < delay || leader != null)
nanos = available.awaitNanos(nanos);
else {
......
......@@ -75,22 +75,23 @@ import java.util.*;
* corePoolSize (see {@link #getCorePoolSize}) and
* maximumPoolSize (see {@link #getMaximumPoolSize}).
*
* When a new task is submitted in method {@link #execute}, and fewer
* than corePoolSize threads are running, a new thread is created to
* handle the request, even if other worker threads are idle. If
* there are more than corePoolSize but less than maximumPoolSize
* threads running, a new thread will be created only if the queue is
* full. By setting corePoolSize and maximumPoolSize the same, you
* create a fixed-size thread pool. By setting maximumPoolSize to an
* essentially unbounded value such as {@code Integer.MAX_VALUE}, you
* allow the pool to accommodate an arbitrary number of concurrent
* tasks. Most typically, core and maximum pool sizes are set only
* upon construction, but they may also be changed dynamically using
* {@link #setCorePoolSize} and {@link #setMaximumPoolSize}. </dd>
* When a new task is submitted in method {@link #execute(Runnable)},
* and fewer than corePoolSize threads are running, a new thread is
* created to handle the request, even if other worker threads are
* idle. If there are more than corePoolSize but less than
* maximumPoolSize threads running, a new thread will be created only
* if the queue is full. By setting corePoolSize and maximumPoolSize
* the same, you create a fixed-size thread pool. By setting
* maximumPoolSize to an essentially unbounded value such as {@code
* Integer.MAX_VALUE}, you allow the pool to accommodate an arbitrary
* number of concurrent tasks. Most typically, core and maximum pool
* sizes are set only upon construction, but they may also be changed
* dynamically using {@link #setCorePoolSize} and {@link
* #setMaximumPoolSize}. </dd>
*
* <dt>On-demand construction</dt>
*
* <dd> By default, even core threads are initially created and
* <dd>By default, even core threads are initially created and
* started only when new tasks arrive, but this can be overridden
* dynamically using method {@link #prestartCoreThread} or {@link
* #prestartAllCoreThreads}. You probably want to prestart threads if
......@@ -117,17 +118,17 @@ import java.util.*;
*
* <dd>If the pool currently has more than corePoolSize threads,
* excess threads will be terminated if they have been idle for more
* than the keepAliveTime (see {@link #getKeepAliveTime}). This
* provides a means of reducing resource consumption when the pool is
* not being actively used. If the pool becomes more active later, new
* threads will be constructed. This parameter can also be changed
* dynamically using method {@link #setKeepAliveTime}. Using a value
* of {@code Long.MAX_VALUE} {@link TimeUnit#NANOSECONDS} effectively
* disables idle threads from ever terminating prior to shut down. By
* default, the keep-alive policy applies only when there are more
* than corePoolSizeThreads. But method {@link
* #allowCoreThreadTimeOut(boolean)} can be used to apply this
* time-out policy to core threads as well, so long as the
* than the keepAliveTime (see {@link #getKeepAliveTime(TimeUnit)}).
* This provides a means of reducing resource consumption when the
* pool is not being actively used. If the pool becomes more active
* later, new threads will be constructed. This parameter can also be
* changed dynamically using method {@link #setKeepAliveTime(long,
* TimeUnit)}. Using a value of {@code Long.MAX_VALUE} {@link
* TimeUnit#NANOSECONDS} effectively disables idle threads from ever
* terminating prior to shut down. By default, the keep-alive policy
* applies only when there are more than corePoolSize threads. But
* method {@link #allowCoreThreadTimeOut(boolean)} can be used to
* apply this time-out policy to core threads as well, so long as the
* keepAliveTime value is non-zero. </dd>
*
* <dt>Queuing</dt>
......@@ -197,14 +198,14 @@ import java.util.*;
*
* <dt>Rejected tasks</dt>
*
* <dd> New tasks submitted in method {@link #execute} will be
* <em>rejected</em> when the Executor has been shut down, and also
* when the Executor uses finite bounds for both maximum threads and
* work queue capacity, and is saturated. In either case, the {@code
* execute} method invokes the {@link
* RejectedExecutionHandler#rejectedExecution} method of its {@link
* RejectedExecutionHandler}. Four predefined handler policies are
* provided:
* <dd>New tasks submitted in method {@link #execute(Runnable)} will be
* <em>rejected</em> when the Executor has been shut down, and also when
* the Executor uses finite bounds for both maximum threads and work queue
* capacity, and is saturated. In either case, the {@code execute} method
* invokes the {@link
* RejectedExecutionHandler#rejectedExecution(Runnable, ThreadPoolExecutor)}
* method of its {@link RejectedExecutionHandler}. Four predefined handler
* policies are provided:
*
* <ol>
*
......@@ -234,30 +235,31 @@ import java.util.*;
*
* <dt>Hook methods</dt>
*
* <dd>This class provides {@code protected} overridable {@link
* #beforeExecute} and {@link #afterExecute} methods that are called
* <dd>This class provides {@code protected} overridable
* {@link #beforeExecute(Thread, Runnable)} and
* {@link #afterExecute(Runnable, Throwable)} methods that are called
* before and after execution of each task. These can be used to
* manipulate the execution environment; for example, reinitializing
* ThreadLocals, gathering statistics, or adding log
* entries. Additionally, method {@link #terminated} can be overridden
* to perform any special processing that needs to be done once the
* Executor has fully terminated.
* ThreadLocals, gathering statistics, or adding log entries.
* Additionally, method {@link #terminated} can be overridden to perform
* any special processing that needs to be done once the Executor has
* fully terminated.
*
* <p>If hook or callback methods throw exceptions, internal worker
* threads may in turn fail and abruptly terminate.</dd>
*
* <dt>Queue maintenance</dt>
*
* <dd> Method {@link #getQueue} allows access to the work queue for
* purposes of monitoring and debugging. Use of this method for any
* other purpose is strongly discouraged. Two supplied methods,
* {@link #remove} and {@link #purge} are available to assist in
* storage reclamation when large numbers of queued tasks become
* cancelled.</dd>
* <dd>Method {@link #getQueue()} allows access to the work queue
* for purposes of monitoring and debugging. Use of this method for
* any other purpose is strongly discouraged. Two supplied methods,
* {@link #remove(Runnable)} and {@link #purge} are available to
* assist in storage reclamation when large numbers of queued tasks
* become cancelled.</dd>
*
* <dt>Finalization</dt>
*
* <dd> A pool that is no longer referenced in a program <em>AND</em>
* <dd>A pool that is no longer referenced in a program <em>AND</em>
* has no remaining threads will be {@code shutdown} automatically. If
* you would like to ensure that unreferenced pools are reclaimed even
* if users forget to call {@link #shutdown}, then you must arrange
......@@ -267,7 +269,7 @@ import java.util.*;
*
* </dl>
*
* <p> <b>Extension example</b>. Most extensions of this class
* <p><b>Extension example</b>. Most extensions of this class
* override one or more of the protected hook methods. For example,
* here is a subclass that adds a simple pause/resume feature:
*
......@@ -336,7 +338,7 @@ public class ThreadPoolExecutor extends AbstractExecutorService {
* bookkeeping before terminating. The user-visible pool size is
* reported as the current size of the workers set.
*
* The runState provides the main lifecyle control, taking on values:
* The runState provides the main lifecycle control, taking on values:
*
* RUNNING: Accept new tasks and process queued tasks
* SHUTDOWN: Don't accept new tasks, but process queued tasks
......@@ -406,14 +408,14 @@ public class ThreadPoolExecutor extends AbstractExecutorService {
}
/**
* Attempt to CAS-increment the workerCount field of ctl.
* Attempts to CAS-increment the workerCount field of ctl.
*/
private boolean compareAndIncrementWorkerCount(int expect) {
return ctl.compareAndSet(expect, expect + 1);
}
/**
* Attempt to CAS-decrement the workerCount field of ctl.
* Attempts to CAS-decrement the workerCount field of ctl.
*/
private boolean compareAndDecrementWorkerCount(int expect) {
return ctl.compareAndSet(expect, expect - 1);
......@@ -498,7 +500,7 @@ public class ThreadPoolExecutor extends AbstractExecutorService {
* We go further and preserve pool invariants even in the face of
* errors such as OutOfMemoryError, that might be thrown while
* trying to create threads. Such errors are rather common due to
* the need to allocate a native stack in Thread#start, and users
* the need to allocate a native stack in Thread.start, and users
* will want to perform clean pool shutdown to clean up. There
* will likely be enough memory available for the cleanup code to
* complete without encountering yet another OutOfMemoryError.
......@@ -848,7 +850,7 @@ public class ThreadPoolExecutor extends AbstractExecutorService {
*/
private List<Runnable> drainQueue() {
BlockingQueue<Runnable> q = workQueue;
List<Runnable> taskList = new ArrayList<Runnable>();
ArrayList<Runnable> taskList = new ArrayList<Runnable>();
q.drainTo(taskList);
if (!q.isEmpty()) {
for (Runnable r : q.toArray(new Runnable[0])) {
......@@ -873,7 +875,7 @@ public class ThreadPoolExecutor extends AbstractExecutorService {
* factory fails to create a thread when asked. If the thread
* creation fails, either due to the thread factory returning
* null, or due to an exception (typically OutOfMemoryError in
* Thread#start), we roll back cleanly.
* Thread.start()), we roll back cleanly.
*
* @param firstTask the task the new thread should run first (or
* null if none). Workers are created with an initial first task
......@@ -920,17 +922,16 @@ public class ThreadPoolExecutor extends AbstractExecutorService {
boolean workerAdded = false;
Worker w = null;
try {
final ReentrantLock mainLock = this.mainLock;
w = new Worker(firstTask);
final Thread t = w.thread;
if (t != null) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
// Recheck while holding lock.
// Back out on ThreadFactory failure or if
// shut down before lock acquired.
int c = ctl.get();
int rs = runStateOf(c);
int rs = runStateOf(ctl.get());
if (rs < SHUTDOWN ||
(rs == SHUTDOWN && firstTask == null)) {
......@@ -1029,7 +1030,8 @@ public class ThreadPoolExecutor extends AbstractExecutorService {
* 4. This worker timed out waiting for a task, and timed-out
* workers are subject to termination (that is,
* {@code allowCoreThreadTimeOut || workerCount > corePoolSize})
* both before and after the timed wait.
* both before and after the timed wait, and if the queue is
* non-empty, this worker is not the last thread in the pool.
*
* @return task, or null if the worker must exit, in which case
* workerCount is decremented
......@@ -1037,7 +1039,6 @@ public class ThreadPoolExecutor extends AbstractExecutorService {
private Runnable getTask() {
boolean timedOut = false; // Did the last poll() time out?
retry:
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
......@@ -1048,20 +1049,16 @@ public class ThreadPoolExecutor extends AbstractExecutorService {
return null;
}
boolean timed; // Are workers subject to culling?
int wc = workerCountOf(c);
for (;;) {
int wc = workerCountOf(c);
timed = allowCoreThreadTimeOut || wc > corePoolSize;
// Are workers subject to culling?
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
if (wc <= maximumPoolSize && ! (timedOut && timed))
break;
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c))
return null;
c = ctl.get(); // Re-read ctl
if (runStateOf(c) != rs)
continue retry;
// else CAS failed due to workerCount change; retry inner loop
continue;
}
try {
......@@ -1090,9 +1087,9 @@ public class ThreadPoolExecutor extends AbstractExecutorService {
* usually leads processWorkerExit to replace this thread.
*
* 2. Before running any task, the lock is acquired to prevent
* other pool interrupts while the task is executing, and
* clearInterruptsForTaskRun called to ensure that unless pool is
* stopping, this thread does not have its interrupt set.
* other pool interrupts while the task is executing, and then we
* ensure that unless pool is stopping, this thread does not have
* its interrupt set.
*
* 3. Each task run is preceded by a call to beforeExecute, which
* might throw an exception, in which case we cause thread to die
......@@ -1100,12 +1097,12 @@ public class ThreadPoolExecutor extends AbstractExecutorService {
* the task.
*
* 4. Assuming beforeExecute completes normally, we run the task,
* gathering any of its thrown exceptions to send to
* afterExecute. We separately handle RuntimeException, Error
* (both of which the specs guarantee that we trap) and arbitrary
* Throwables. Because we cannot rethrow Throwables within
* Runnable.run, we wrap them within Errors on the way out (to the
* thread's UncaughtExceptionHandler). Any thrown exception also
* gathering any of its thrown exceptions to send to afterExecute.
* We separately handle RuntimeException, Error (both of which the
* specs guarantee that we trap) and arbitrary Throwables.
* Because we cannot rethrow Throwables within Runnable.run, we
* wrap them within Errors on the way out (to the thread's
* UncaughtExceptionHandler). Any thrown exception also
* conservatively causes thread to die.
*
* 5. After task.run completes, we call afterExecute, which may
......@@ -1443,7 +1440,7 @@ public class ThreadPoolExecutor extends AbstractExecutorService {
* ignored or suppressed interruption, causing this executor not
* to properly terminate.
*
* @return true if terminating but not yet terminated
* @return {@code true} if terminating but not yet terminated
*/
public boolean isTerminating() {
int c = ctl.get();
......@@ -1497,7 +1494,7 @@ public class ThreadPoolExecutor extends AbstractExecutorService {
* Returns the thread factory used to create new threads.
*
* @return the current thread factory
* @see #setThreadFactory
* @see #setThreadFactory(ThreadFactory)
*/
public ThreadFactory getThreadFactory() {
return threadFactory;
......@@ -1520,7 +1517,7 @@ public class ThreadPoolExecutor extends AbstractExecutorService {
* Returns the current handler for unexecutable tasks.
*
* @return the current handler
* @see #setRejectedExecutionHandler
* @see #setRejectedExecutionHandler(RejectedExecutionHandler)
*/
public RejectedExecutionHandler getRejectedExecutionHandler() {
return handler;
......@@ -1692,7 +1689,7 @@ public class ThreadPoolExecutor extends AbstractExecutorService {
* @param unit the time unit of the {@code time} argument
* @throws IllegalArgumentException if {@code time} less than zero or
* if {@code time} is zero and {@code allowsCoreThreadTimeOut}
* @see #getKeepAliveTime
* @see #getKeepAliveTime(TimeUnit)
*/
public void setKeepAliveTime(long time, TimeUnit unit) {
if (time < 0)
......@@ -1713,7 +1710,7 @@ public class ThreadPoolExecutor extends AbstractExecutorService {
*
* @param unit the desired time unit of the result
* @return the time limit
* @see #setKeepAliveTime
* @see #setKeepAliveTime(long, TimeUnit)
*/
public long getKeepAliveTime(TimeUnit unit) {
return unit.convert(keepAliveTime, TimeUnit.NANOSECONDS);
......@@ -1738,7 +1735,7 @@ public class ThreadPoolExecutor extends AbstractExecutorService {
* present, thus causing it not to be run if it has not already
* started.
*
* <p> This method may be useful as one part of a cancellation
* <p>This method may be useful as one part of a cancellation
* scheme. It may fail to remove tasks that have been converted
* into other forms before being placed on the internal queue. For
* example, a task entered using {@code submit} might be
......@@ -1747,7 +1744,7 @@ public class ThreadPoolExecutor extends AbstractExecutorService {
* remove those Futures that have been cancelled.
*
* @param task the task to remove
* @return true if the task was removed
* @return {@code true} if the task was removed
*/
public boolean remove(Runnable task) {
boolean removed = workQueue.remove(task);
......@@ -2042,7 +2039,7 @@ public class ThreadPoolExecutor extends AbstractExecutorService {
*
* @param r the runnable task requested to be executed
* @param e the executor attempting to execute this task
* @throws RejectedExecutionException always.
* @throws RejectedExecutionException always
*/
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
throw new RejectedExecutionException("Task " + r.toString() +
......@@ -2099,4 +2096,3 @@ public class ThreadPoolExecutor extends AbstractExecutorService {
}
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册