1 |
|
/* |
2 |
|
* Written by Doug Lea with assistance from members of JCP JSR-166 |
3 |
|
* Expert Group and released to the public domain, as explained at |
4 |
< |
* http://creativecommons.org/licenses/publicdomain |
4 |
> |
* http://creativecommons.org/publicdomain/zero/1.0/ |
5 |
|
*/ |
6 |
|
|
7 |
|
package jsr166y; |
8 |
+ |
|
9 |
|
import java.io.Serializable; |
10 |
< |
import java.util.*; |
11 |
< |
import java.util.concurrent.*; |
12 |
< |
import java.util.concurrent.atomic.*; |
13 |
< |
import sun.misc.Unsafe; |
14 |
< |
import java.lang.reflect.*; |
10 |
> |
import java.util.Collection; |
11 |
> |
import java.util.List; |
12 |
> |
import java.util.RandomAccess; |
13 |
> |
import java.lang.ref.WeakReference; |
14 |
> |
import java.lang.ref.ReferenceQueue; |
15 |
> |
import java.util.concurrent.Callable; |
16 |
> |
import java.util.concurrent.CancellationException; |
17 |
> |
import java.util.concurrent.ExecutionException; |
18 |
> |
import java.util.concurrent.Future; |
19 |
> |
import java.util.concurrent.RejectedExecutionException; |
20 |
> |
import java.util.concurrent.RunnableFuture; |
21 |
> |
import java.util.concurrent.TimeUnit; |
22 |
> |
import java.util.concurrent.TimeoutException; |
23 |
> |
import java.util.concurrent.locks.ReentrantLock; |
24 |
> |
import java.lang.reflect.Constructor; |
25 |
|
|
26 |
|
/** |
27 |
< |
* Abstract base class for tasks that run within a ForkJoinPool. A |
28 |
< |
* ForkJoinTask is a thread-like entity that is much lighter weight |
29 |
< |
* than a normal thread. Huge numbers of tasks and subtasks may be |
30 |
< |
* hosted by a small number of actual threads in a ForkJoinPool, |
31 |
< |
* at the price of some usage limitations. |
32 |
< |
* |
33 |
< |
* <p> ForkJoinTasks are forms of <tt>Futures</tt> supporting a |
34 |
< |
* limited range of use. The "lightness" of ForkJoinTasks is due to a |
35 |
< |
* set of restrictions (that are only partially statically |
36 |
< |
* enforceable) reflecting their intended use as computational tasks |
37 |
< |
* calculating pure functions or operating on purely isolated objects. |
38 |
< |
* The primary coordination mechanisms supported for ForkJoinTasks are |
39 |
< |
* <tt>fork</tt>, that arranges asynchronous execution, and |
40 |
< |
* <tt>join</tt>, that doesn't proceed until the task's result has |
41 |
< |
* been computed. (Cancellation is also supported). The computation |
42 |
< |
* defined in the <tt>compute</tt> method should avoid |
43 |
< |
* <tt>synchronized</tt> methods or blocks, and should minimize |
44 |
< |
* blocking synchronization apart from joining other tasks or using |
45 |
< |
* synchronizers such as Phasers that are advertised to cooperate with |
46 |
< |
* fork/join scheduling. Tasks should also not perform blocking IO, |
47 |
< |
* and should ideally access variables that are completely independent |
48 |
< |
* of those accessed by other running tasks. Minor breaches of these |
49 |
< |
* restrictions, for example using shared output streams, may be |
50 |
< |
* tolerable in practice, but frequent use may result in poor |
51 |
< |
* performance, and the potential to indefinitely stall if the number |
52 |
< |
* of threads not waiting for external synchronization becomes |
53 |
< |
* exhausted. This usage restriction is in part enforced by not |
54 |
< |
* permitting checked exceptions such as IOExceptions to be |
55 |
< |
* thrown. However, computations may still encounter unchecked |
56 |
< |
* exceptions, that are rethrown to callers attempting join |
57 |
< |
* them. These exceptions may additionally include |
58 |
< |
* RejectedExecutionExceptions stemming from internal resource |
59 |
< |
* exhaustion such as failure to allocate internal task queues. |
60 |
< |
* |
61 |
< |
* <p> The <tt>ForkJoinTask</tt> class is not usually directly |
62 |
< |
* subclassed. Instead, you subclass one of the abstract classes that |
63 |
< |
* support different styles of fork/join processing. Normally, a |
64 |
< |
* concrete ForkJoinTask subclass declares fields comprising its |
65 |
< |
* parameters, established in a constructor, and then defines a |
66 |
< |
* <tt>compute</tt> method that somehow uses the control methods |
67 |
< |
* supplied by this base class. While these methods have |
68 |
< |
* <tt>public</tt> access, some of them may only be called from within |
69 |
< |
* other ForkJoinTasks. Attempts to invoke them in other contexts |
70 |
< |
* result in exceptions or errors including ClassCastException. The |
71 |
< |
* only way to invoke a "main" driver task is to submit it to a |
72 |
< |
* ForkJoinPool. Once started, this will usually in turn start other |
73 |
< |
* subtasks. |
74 |
< |
* |
75 |
< |
* <p>Most base support methods are <tt>final</tt> because their |
76 |
< |
* implementations are intrinsically tied to the underlying |
77 |
< |
* lightweight task scheduling framework, and so cannot be overridden. |
78 |
< |
* Developers creating new basic styles of fork/join processing should |
79 |
< |
* minimally implement protected methods <tt>exec</tt>, |
80 |
< |
* <tt>setRawResult</tt>, and <tt>getRawResult</tt>, while also |
81 |
< |
* introducing an abstract computational method that can be |
82 |
< |
* implemented in its subclasses. To support such extensions, |
83 |
< |
* instances of ForkJoinTasks maintain an atomically updated |
84 |
< |
* <tt>short</tt> representing user-defined control state. Control |
85 |
< |
* state is guaranteed initially to be zero, and to be negative upon |
86 |
< |
* completion, but may otherwise be used for any other control |
87 |
< |
* purposes, such as maintaining join counts. The {@link |
88 |
< |
* ForkJoinWorkerThread} class supports additional inspection and |
89 |
< |
* tuning methods that can be useful when developing extensions. |
27 |
> |
* Abstract base class for tasks that run within a {@link ForkJoinPool}. |
28 |
> |
* A {@code ForkJoinTask} is a thread-like entity that is much |
29 |
> |
* lighter weight than a normal thread. Huge numbers of tasks and |
30 |
> |
* subtasks may be hosted by a small number of actual threads in a |
31 |
> |
* ForkJoinPool, at the price of some usage limitations. |
32 |
> |
* |
33 |
> |
* <p>A "main" {@code ForkJoinTask} begins execution when submitted |
34 |
> |
* to a {@link ForkJoinPool}. Once started, it will usually in turn |
35 |
> |
* start other subtasks. As indicated by the name of this class, |
36 |
> |
* many programs using {@code ForkJoinTask} employ only methods |
37 |
> |
* {@link #fork} and {@link #join}, or derivatives such as {@link |
38 |
> |
* #invokeAll(ForkJoinTask...) invokeAll}. However, this class also |
39 |
> |
* provides a number of other methods that can come into play in |
40 |
> |
* advanced usages, as well as extension mechanics that allow |
41 |
> |
* support of new forms of fork/join processing. |
42 |
> |
* |
43 |
> |
* <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}. |
44 |
> |
* The efficiency of {@code ForkJoinTask}s stems from a set of |
45 |
> |
* restrictions (that are only partially statically enforceable) |
46 |
> |
* reflecting their intended use as computational tasks calculating |
47 |
> |
* pure functions or operating on purely isolated objects. The |
48 |
> |
* primary coordination mechanisms are {@link #fork}, that arranges |
49 |
> |
* asynchronous execution, and {@link #join}, that doesn't proceed |
50 |
> |
* until the task's result has been computed. Computations should |
51 |
> |
* avoid {@code synchronized} methods or blocks, and should minimize |
52 |
> |
* other blocking synchronization apart from joining other tasks or |
53 |
> |
* using synchronizers such as Phasers that are advertised to |
54 |
> |
* cooperate with fork/join scheduling. Tasks should also not perform |
55 |
> |
* blocking IO, and should ideally access variables that are |
56 |
> |
* completely independent of those accessed by other running |
57 |
> |
* tasks. Minor breaches of these restrictions, for example using |
58 |
> |
* shared output streams, may be tolerable in practice, but frequent |
59 |
> |
* use may result in poor performance, and the potential to |
60 |
> |
* indefinitely stall if the number of threads not waiting for IO or |
61 |
> |
* other external synchronization becomes exhausted. This usage |
62 |
> |
* restriction is in part enforced by not permitting checked |
63 |
> |
* exceptions such as {@code IOExceptions} to be thrown. However, |
64 |
> |
* computations may still encounter unchecked exceptions, that are |
65 |
> |
* rethrown to callers attempting to join them. These exceptions may |
66 |
> |
* additionally include {@link RejectedExecutionException} stemming |
67 |
> |
* from internal resource exhaustion, such as failure to allocate |
68 |
> |
* internal task queues. Rethrown exceptions behave in the same way as |
69 |
> |
* regular exceptions, but, when possible, contain stack traces (as |
70 |
> |
* displayed for example using {@code ex.printStackTrace()}) of both |
71 |
> |
* the thread that initiated the computation as well as the thread |
72 |
> |
* actually encountering the exception; minimally only the latter. |
73 |
> |
* |
74 |
> |
* <p>The primary method for awaiting completion and extracting |
75 |
> |
* results of a task is {@link #join}, but there are several variants: |
76 |
> |
* The {@link Future#get} methods support interruptible and/or timed |
77 |
> |
* waits for completion and report results using {@code Future} |
78 |
> |
* conventions. Method {@link #invoke} is semantically |
79 |
> |
* equivalent to {@code fork(); join()} but always attempts to begin |
80 |
> |
* execution in the current thread. The "<em>quiet</em>" forms of |
81 |
> |
* these methods do not extract results or report exceptions. These |
82 |
> |
* may be useful when a set of tasks are being executed, and you need |
83 |
> |
* to delay processing of results or exceptions until all complete. |
84 |
> |
* Method {@code invokeAll} (available in multiple versions) |
85 |
> |
* performs the most common form of parallel invocation: forking a set |
86 |
> |
* of tasks and joining them all. |
87 |
> |
* |
88 |
> |
* <p>The execution status of tasks may be queried at several levels |
89 |
> |
* of detail: {@link #isDone} is true if a task completed in any way |
90 |
> |
* (including the case where a task was cancelled without executing); |
91 |
> |
* {@link #isCompletedNormally} is true if a task completed without |
92 |
> |
* cancellation or encountering an exception; {@link #isCancelled} is |
93 |
> |
* true if the task was cancelled (in which case {@link #getException} |
94 |
> |
* returns a {@link java.util.concurrent.CancellationException}); and |
95 |
> |
* {@link #isCompletedAbnormally} is true if a task was either |
96 |
> |
* cancelled or encountered an exception, in which case {@link |
97 |
> |
* #getException} will return either the encountered exception or |
98 |
> |
* {@link java.util.concurrent.CancellationException}. |
99 |
> |
* |
100 |
> |
* <p>The ForkJoinTask class is not usually directly subclassed. |
101 |
> |
* Instead, you subclass one of the abstract classes that support a |
102 |
> |
* particular style of fork/join processing, typically {@link |
103 |
> |
* RecursiveAction} for computations that do not return results, or |
104 |
> |
* {@link RecursiveTask} for those that do. Normally, a concrete |
105 |
> |
* ForkJoinTask subclass declares fields comprising its parameters, |
106 |
> |
* established in a constructor, and then defines a {@code compute} |
107 |
> |
* method that somehow uses the control methods supplied by this base |
108 |
> |
* class. While these methods have {@code public} access (to allow |
109 |
> |
* instances of different task subclasses to call each other's |
110 |
> |
* methods), some of them may only be called from within other |
111 |
> |
* ForkJoinTasks (as may be determined using method {@link |
112 |
> |
* #inForkJoinPool}). Attempts to invoke them in other contexts |
113 |
> |
* result in exceptions or errors, possibly including |
114 |
> |
* {@code ClassCastException}. |
115 |
> |
* |
116 |
> |
* <p>Method {@link #join} and its variants are appropriate for use |
117 |
> |
* only when completion dependencies are acyclic; that is, the |
118 |
> |
* parallel computation can be described as a directed acyclic graph |
119 |
> |
* (DAG). Otherwise, executions may encounter a form of deadlock as |
120 |
> |
* tasks cyclically wait for each other. However, this framework |
121 |
> |
* supports other methods and techniques (for example the use of |
122 |
> |
* {@link Phaser}, {@link #helpQuiesce}, and {@link #complete}) that |
123 |
> |
* may be of use in constructing custom subclasses for problems that |
124 |
> |
* are not statically structured as DAGs. |
125 |
> |
* |
126 |
> |
* <p>Most base support methods are {@code final}, to prevent |
127 |
> |
* overriding of implementations that are intrinsically tied to the |
128 |
> |
* underlying lightweight task scheduling framework. Developers |
129 |
> |
* creating new basic styles of fork/join processing should minimally |
130 |
> |
* implement {@code protected} methods {@link #exec}, {@link |
131 |
> |
* #setRawResult}, and {@link #getRawResult}, while also introducing |
132 |
> |
* an abstract computational method that can be implemented in its |
133 |
> |
* subclasses, possibly relying on other {@code protected} methods |
134 |
> |
* provided by this class. |
135 |
|
* |
136 |
|
* <p>ForkJoinTasks should perform relatively small amounts of |
137 |
< |
* computations, othewise splitting into smaller tasks. As a very |
138 |
< |
* rough rule of thumb, a task should perform more than 100 and less |
139 |
< |
* than 10000 basic computational steps. If tasks are too big, then |
140 |
< |
* parellelism cannot improve throughput. If too small, then memory |
141 |
< |
* and internal task maintenance overhead may overwhelm processing. |
142 |
< |
* |
143 |
< |
* <p>ForkJoinTasks are <tt>Serializable</tt>, which enables them to |
144 |
< |
* be used in extensions such as remote execution frameworks. However, |
145 |
< |
* it is in general safe to serialize tasks only before or after, but |
146 |
< |
* not during execution. Serialization is not relied on during |
147 |
< |
* execution itself. |
137 |
> |
* computation. Large tasks should be split into smaller subtasks, |
138 |
> |
* usually via recursive decomposition. As a very rough rule of thumb, |
139 |
> |
* a task should perform more than 100 and less than 10000 basic |
140 |
> |
* computational steps, and should avoid indefinite looping. If tasks |
141 |
> |
* are too big, then parallelism cannot improve throughput. If too |
142 |
> |
* small, then memory and internal task maintenance overhead may |
143 |
> |
* overwhelm processing. |
144 |
> |
* |
145 |
> |
* <p>This class provides {@code adapt} methods for {@link Runnable} |
146 |
> |
* and {@link Callable}, that may be of use when mixing execution of |
147 |
> |
* {@code ForkJoinTasks} with other kinds of tasks. When all tasks are |
148 |
> |
* of this form, consider using a pool constructed in <em>asyncMode</em>. |
149 |
> |
* |
150 |
> |
* <p>ForkJoinTasks are {@code Serializable}, which enables them to be |
151 |
> |
* used in extensions such as remote execution frameworks. It is |
152 |
> |
* sensible to serialize tasks only before or after, but not during, |
153 |
> |
* execution. Serialization is not relied on during execution itself. |
154 |
> |
* |
155 |
> |
* @since 1.7 |
156 |
> |
* @author Doug Lea |
157 |
|
*/ |
158 |
|
public abstract class ForkJoinTask<V> implements Future<V>, Serializable { |
94 |
– |
/** |
95 |
– |
* Status field holding all run status. We pack this into a single |
96 |
– |
* int both to minimize footprint overhead and to ensure atomicity |
97 |
– |
* (updates are via CAS). |
98 |
– |
* |
99 |
– |
* Status is initially zero, and takes on nonnegative values until |
100 |
– |
* completed, upon which status holds COMPLETED. CANCELLED, or |
101 |
– |
* EXCEPTIONAL, which use the top 3 bits. Tasks undergoing |
102 |
– |
* blocking waits by other threads have SIGNAL_MASK bits set -- |
103 |
– |
* bit 15 for external (nonFJ) waits, and the rest a count of |
104 |
– |
* waiting FJ threads. (This representation relies on |
105 |
– |
* ForkJoinPool max thread limits). Completion of a stolen task |
106 |
– |
* with SIGNAL_MASK bits set awakens waiter via notifyAll. Even |
107 |
– |
* though suboptimal for some purposes, we use basic builtin |
108 |
– |
* wait/notify to take advantage of "monitor inflation" in JVMs |
109 |
– |
* that we would otherwise need to emulate to avoid adding further |
110 |
– |
* per-task bookkeeping overhead. Note that bits 16-28 are |
111 |
– |
* currently unused. Also value 0x80000000 is available as spare |
112 |
– |
* completion value. |
113 |
– |
*/ |
114 |
– |
volatile int status; // accessed directy by pool and workers |
115 |
– |
|
116 |
– |
static final int COMPLETION_MASK = 0xe0000000; |
117 |
– |
static final int NORMAL = 0xe0000000; // == mask |
118 |
– |
static final int CANCELLED = 0xc0000000; |
119 |
– |
static final int EXCEPTIONAL = 0xa0000000; |
120 |
– |
static final int SIGNAL_MASK = 0x0000ffff; |
121 |
– |
static final int INTERNAL_SIGNAL_MASK = 0x00007fff; |
122 |
– |
static final int EXTERNAL_SIGNAL = 0x00008000; // top bit of low word |
123 |
– |
|
124 |
– |
/** |
125 |
– |
* Table of exceptions thrown by tasks, to enable reporting by |
126 |
– |
* callers. Because exceptions are rare, we don't directly keep |
127 |
– |
* them with task objects, but instead us a weak ref table. Note |
128 |
– |
* that cancellation exceptions don't appear in the table, but are |
129 |
– |
* instead recorded as status values. |
130 |
– |
* Todo: Use ConcurrentReferenceHashMap |
131 |
– |
*/ |
132 |
– |
static final Map<ForkJoinTask<?>, Throwable> exceptionMap = |
133 |
– |
Collections.synchronizedMap |
134 |
– |
(new WeakHashMap<ForkJoinTask<?>, Throwable>()); |
135 |
– |
|
136 |
– |
// within-package utilities |
137 |
– |
|
138 |
– |
/** |
139 |
– |
* Get current worker thread, or null if not a worker thread |
140 |
– |
*/ |
141 |
– |
static ForkJoinWorkerThread getWorker() { |
142 |
– |
Thread t = Thread.currentThread(); |
143 |
– |
return ((t instanceof ForkJoinWorkerThread)? |
144 |
– |
(ForkJoinWorkerThread)t : null); |
145 |
– |
} |
146 |
– |
|
147 |
– |
/** |
148 |
– |
* Get pool of current worker thread, or null if not a worker thread |
149 |
– |
*/ |
150 |
– |
static ForkJoinPool getWorkerPool() { |
151 |
– |
Thread t = Thread.currentThread(); |
152 |
– |
return ((t instanceof ForkJoinWorkerThread)? |
153 |
– |
((ForkJoinWorkerThread)t).pool : null); |
154 |
– |
} |
155 |
– |
|
156 |
– |
final boolean casStatus(int cmp, int val) { |
157 |
– |
return _unsafe.compareAndSwapInt(this, statusOffset, cmp, val); |
158 |
– |
} |
159 |
– |
|
160 |
– |
/** |
161 |
– |
* Workaround for not being able to rethrow unchecked exceptions. |
162 |
– |
*/ |
163 |
– |
static void rethrowException(Throwable ex) { |
164 |
– |
if (ex != null) |
165 |
– |
_unsafe.throwException(ex); |
166 |
– |
} |
159 |
|
|
160 |
< |
// Setting completion status |
160 |
> |
/* |
161 |
> |
* See the internal documentation of class ForkJoinPool for a |
162 |
> |
* general implementation overview. ForkJoinTasks are mainly |
163 |
> |
* responsible for maintaining their "status" field amidst relays |
164 |
> |
* to methods in ForkJoinWorkerThread and ForkJoinPool. |
165 |
> |
* |
166 |
> |
* The methods of this class are more-or-less layered into |
167 |
> |
* (1) basic status maintenance |
168 |
> |
* (2) execution and awaiting completion |
169 |
> |
* (3) user-level methods that additionally report results. |
170 |
> |
* This is sometimes hard to see because this file orders exported |
171 |
> |
* methods in a way that flows well in javadocs. |
172 |
> |
*/ |
173 |
> |
|
174 |
> |
/* |
175 |
> |
* The status field holds run control status bits packed into a |
176 |
> |
* single int to minimize footprint and to ensure atomicity (via |
177 |
> |
* CAS). Status is initially zero, and takes on nonnegative |
178 |
> |
* values until completed, upon which status holds value |
179 |
> |
* NORMAL, CANCELLED, or EXCEPTIONAL. Tasks undergoing blocking |
180 |
> |
* waits by other threads have the SIGNAL bit set. Completion of |
181 |
> |
* a stolen task with SIGNAL set awakens any waiters via |
182 |
> |
* notifyAll. Even though suboptimal for some purposes, we use |
183 |
> |
* basic builtin wait/notify to take advantage of "monitor |
184 |
> |
* inflation" in JVMs that we would otherwise need to emulate to |
185 |
> |
* avoid adding further per-task bookkeeping overhead. We want |
186 |
> |
* these monitors to be "fat", i.e., not use biasing or thin-lock |
187 |
> |
* techniques, so use some odd coding idioms that tend to avoid |
188 |
> |
* them. |
189 |
> |
*/ |
190 |
> |
|
191 |
> |
/** The run status of this task */ |
192 |
> |
volatile int status; // accessed directly by pool and workers |
193 |
> |
private static final int NORMAL = -1; |
194 |
> |
private static final int CANCELLED = -2; |
195 |
> |
private static final int EXCEPTIONAL = -3; |
196 |
> |
private static final int SIGNAL = 1; |
197 |
|
|
198 |
|
/** |
199 |
< |
* Mark completion and wake up threads waiting to join this task. |
199 |
> |
* Marks completion and wakes up threads waiting to join this task, |
200 |
> |
* also clearing signal request bits. |
201 |
> |
* |
202 |
|
* @param completion one of NORMAL, CANCELLED, EXCEPTIONAL |
203 |
+ |
* @return completion status on exit |
204 |
|
*/ |
205 |
< |
final void setCompletion(int completion) { |
206 |
< |
ForkJoinPool pool = getWorkerPool(); |
207 |
< |
if (pool != null) { |
208 |
< |
int s; // Clear signal bits while setting completion status |
209 |
< |
do;while ((s = status) >= 0 && !casStatus(s, completion)); |
210 |
< |
|
211 |
< |
if ((s & SIGNAL_MASK) != 0) { |
212 |
< |
if ((s &= INTERNAL_SIGNAL_MASK) != 0) |
182 |
< |
pool.updateRunningCount(s); |
183 |
< |
synchronized(this) { notifyAll(); } |
205 |
> |
private int setCompletion(int completion) { |
206 |
> |
for (int s;;) { |
207 |
> |
if ((s = status) < 0) |
208 |
> |
return s; |
209 |
> |
if (UNSAFE.compareAndSwapInt(this, statusOffset, s, completion)) { |
210 |
> |
if (s != 0) |
211 |
> |
synchronized (this) { notifyAll(); } |
212 |
> |
return completion; |
213 |
|
} |
214 |
|
} |
186 |
– |
else |
187 |
– |
externallySetCompletion(completion); |
215 |
|
} |
216 |
|
|
217 |
|
/** |
218 |
< |
* Version of setCompletion for non-FJ threads. Leaves signal |
219 |
< |
* bits for unblocked threads to adjust, and always notifies. |
218 |
> |
* Tries to block a worker thread until completed or timed out. |
219 |
> |
* Uses Object.wait time argument conventions. |
220 |
> |
* May fail on contention or interrupt. |
221 |
> |
* |
222 |
> |
* @param millis if > 0, wait time. |
223 |
|
*/ |
224 |
< |
private void externallySetCompletion(int completion) { |
224 |
> |
final void tryAwaitDone(long millis) { |
225 |
|
int s; |
196 |
– |
do;while ((s = status) >= 0 && |
197 |
– |
!casStatus(s, (s & SIGNAL_MASK) | completion)); |
198 |
– |
synchronized(this) { notifyAll(); } |
199 |
– |
} |
200 |
– |
|
201 |
– |
/** |
202 |
– |
* Sets status to indicate normal completion |
203 |
– |
*/ |
204 |
– |
final void setNormalCompletion() { |
205 |
– |
// Try typical fast case -- single CAS, no signal, not already done. |
206 |
– |
// Manually expand casStatus to improve chances of inlining it |
207 |
– |
if (!_unsafe.compareAndSwapInt(this, statusOffset, 0, NORMAL)) |
208 |
– |
setCompletion(NORMAL); |
209 |
– |
} |
210 |
– |
|
211 |
– |
// internal waiting and notification |
212 |
– |
|
213 |
– |
/** |
214 |
– |
* Performs the actual monitor wait for awaitDone |
215 |
– |
*/ |
216 |
– |
private void doAwaitDone() { |
217 |
– |
// Minimize lock bias and in/de-flation effects by maximizing |
218 |
– |
// chances of waiting inside sync |
226 |
|
try { |
227 |
< |
while (status >= 0) |
228 |
< |
synchronized(this) { if (status >= 0) wait(); } |
229 |
< |
} catch (InterruptedException ie) { |
230 |
< |
onInterruptedWait(); |
231 |
< |
} |
232 |
< |
} |
233 |
< |
|
227 |
< |
/** |
228 |
< |
* Performs the actual monitor wait for awaitDone |
229 |
< |
*/ |
230 |
< |
private void doAwaitDone(long startTime, long nanos) { |
231 |
< |
synchronized(this) { |
232 |
< |
try { |
233 |
< |
while (status >= 0) { |
234 |
< |
long nt = nanos - System.nanoTime() - startTime; |
235 |
< |
if (nt <= 0) |
236 |
< |
break; |
237 |
< |
wait(nt / 1000000, (int)(nt % 1000000)); |
227 |
> |
if (((s = status) > 0 || |
228 |
> |
(s == 0 && |
229 |
> |
UNSAFE.compareAndSwapInt(this, statusOffset, 0, SIGNAL))) && |
230 |
> |
status > 0) { |
231 |
> |
synchronized (this) { |
232 |
> |
if (status > 0) |
233 |
> |
wait(millis); |
234 |
|
} |
239 |
– |
} catch (InterruptedException ie) { |
240 |
– |
onInterruptedWait(); |
235 |
|
} |
236 |
+ |
} catch (InterruptedException ie) { |
237 |
+ |
// caller must check termination |
238 |
|
} |
239 |
|
} |
240 |
|
|
245 |
– |
// Awaiting completion |
246 |
– |
|
241 |
|
/** |
242 |
< |
* Sets status to indicate there is joiner, then waits for join, |
243 |
< |
* surrounded with pool notifications. |
250 |
< |
* @return status upon exit |
242 |
> |
* Blocks a non-worker-thread until completion. |
243 |
> |
* @return status upon completion |
244 |
|
*/ |
245 |
< |
final int awaitDone(ForkJoinWorkerThread w, boolean maintainParallelism) { |
253 |
< |
ForkJoinPool pool = w == null? null : w.pool; |
245 |
> |
private int externalAwaitDone() { |
246 |
|
int s; |
247 |
< |
while ((s = status) >= 0) { |
248 |
< |
if (casStatus(s, pool == null? s|EXTERNAL_SIGNAL : s+1)) { |
249 |
< |
if (pool == null || !pool.preJoin(this, maintainParallelism)) |
250 |
< |
doAwaitDone(); |
251 |
< |
if (((s = status) & INTERNAL_SIGNAL_MASK) != 0) |
252 |
< |
adjustPoolCountsOnUnblock(pool); |
253 |
< |
break; |
247 |
> |
if ((s = status) >= 0) { |
248 |
> |
boolean interrupted = false; |
249 |
> |
synchronized (this) { |
250 |
> |
while ((s = status) >= 0) { |
251 |
> |
if (s == 0) |
252 |
> |
UNSAFE.compareAndSwapInt(this, statusOffset, |
253 |
> |
0, SIGNAL); |
254 |
> |
else { |
255 |
> |
try { |
256 |
> |
wait(); |
257 |
> |
} catch (InterruptedException ie) { |
258 |
> |
interrupted = true; |
259 |
> |
} |
260 |
> |
} |
261 |
> |
} |
262 |
|
} |
263 |
+ |
if (interrupted) |
264 |
+ |
Thread.currentThread().interrupt(); |
265 |
|
} |
266 |
|
return s; |
267 |
|
} |
268 |
|
|
269 |
|
/** |
270 |
< |
* Timed version of awaitDone |
269 |
< |
* @return status upon exit |
270 |
> |
* Blocks a non-worker-thread until completion or interruption or timeout. |
271 |
|
*/ |
272 |
< |
final int awaitDone(ForkJoinWorkerThread w, long nanos) { |
273 |
< |
ForkJoinPool pool = w == null? null : w.pool; |
272 |
> |
private int externalInterruptibleAwaitDone(long millis) |
273 |
> |
throws InterruptedException { |
274 |
|
int s; |
275 |
< |
while ((s = status) >= 0) { |
276 |
< |
if (casStatus(s, pool == null? s|EXTERNAL_SIGNAL : s+1)) { |
277 |
< |
long startTime = System.nanoTime(); |
278 |
< |
if (pool == null || !pool.preJoin(this, false)) |
279 |
< |
doAwaitDone(startTime, nanos); |
280 |
< |
if ((s = status) >= 0) { |
281 |
< |
adjustPoolCountsOnCancelledWait(pool); |
282 |
< |
s = status; |
275 |
> |
if (Thread.interrupted()) |
276 |
> |
throw new InterruptedException(); |
277 |
> |
if ((s = status) >= 0) { |
278 |
> |
synchronized (this) { |
279 |
> |
while ((s = status) >= 0) { |
280 |
> |
if (s == 0) |
281 |
> |
UNSAFE.compareAndSwapInt(this, statusOffset, |
282 |
> |
0, SIGNAL); |
283 |
> |
else { |
284 |
> |
wait(millis); |
285 |
> |
if (millis > 0L) |
286 |
> |
break; |
287 |
> |
} |
288 |
|
} |
283 |
– |
if (s < 0 && (s & INTERNAL_SIGNAL_MASK) != 0) |
284 |
– |
adjustPoolCountsOnUnblock(pool); |
285 |
– |
break; |
289 |
|
} |
290 |
|
} |
291 |
|
return s; |
292 |
|
} |
293 |
|
|
294 |
|
/** |
295 |
< |
* Notify pool that thread is unblocked. Called by signalled |
296 |
< |
* threads when woken by non-FJ threads (which is atypical). |
295 |
> |
* Primary execution method for stolen tasks. Unless done, calls |
296 |
> |
* exec and records status if completed, but doesn't wait for |
297 |
> |
* completion otherwise. |
298 |
|
*/ |
299 |
< |
private void adjustPoolCountsOnUnblock(ForkJoinPool pool) { |
300 |
< |
int s; |
301 |
< |
do;while ((s = status) < 0 && !casStatus(s, s & COMPLETION_MASK)); |
302 |
< |
if (pool != null && (s &= INTERNAL_SIGNAL_MASK) != 0) |
303 |
< |
pool.updateRunningCount(s); |
299 |
> |
final void doExec() { |
300 |
> |
if (status >= 0) { |
301 |
> |
boolean completed; |
302 |
> |
try { |
303 |
> |
completed = exec(); |
304 |
> |
} catch (Throwable rex) { |
305 |
> |
setExceptionalCompletion(rex); |
306 |
> |
return; |
307 |
> |
} |
308 |
> |
if (completed) |
309 |
> |
setCompletion(NORMAL); // must be outside try block |
310 |
> |
} |
311 |
|
} |
312 |
|
|
313 |
|
/** |
314 |
< |
* Notify pool to adjust counts on cancelled or timed out wait |
314 |
> |
* Primary mechanics for join, get, quietlyJoin. |
315 |
> |
* @return status upon completion |
316 |
|
*/ |
317 |
< |
private void adjustPoolCountsOnCancelledWait(ForkJoinPool pool) { |
318 |
< |
if (pool != null) { |
319 |
< |
int s; |
320 |
< |
while ((s = status) >= 0 && (s & INTERNAL_SIGNAL_MASK) != 0) { |
321 |
< |
if (casStatus(s, s - 1)) { |
322 |
< |
pool.updateRunningCount(1); |
323 |
< |
break; |
317 |
> |
private int doJoin() { |
318 |
> |
Thread t; ForkJoinWorkerThread w; int s; boolean completed; |
319 |
> |
if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) { |
320 |
> |
if ((s = status) < 0) |
321 |
> |
return s; |
322 |
> |
if ((w = (ForkJoinWorkerThread)t).unpushTask(this)) { |
323 |
> |
try { |
324 |
> |
completed = exec(); |
325 |
> |
} catch (Throwable rex) { |
326 |
> |
return setExceptionalCompletion(rex); |
327 |
|
} |
328 |
+ |
if (completed) |
329 |
+ |
return setCompletion(NORMAL); |
330 |
|
} |
331 |
+ |
return w.joinTask(this); |
332 |
|
} |
333 |
+ |
else |
334 |
+ |
return externalAwaitDone(); |
335 |
|
} |
336 |
|
|
337 |
< |
private void onInterruptedWait() { |
338 |
< |
Thread t = Thread.currentThread(); |
339 |
< |
if (t instanceof ForkJoinWorkerThread) { |
340 |
< |
ForkJoinWorkerThread w = (ForkJoinWorkerThread)t; |
341 |
< |
if (w.isTerminating()) |
342 |
< |
cancelIgnoreExceptions(); |
343 |
< |
} |
344 |
< |
else { // re-interrupt |
345 |
< |
try { |
346 |
< |
t.interrupt(); |
347 |
< |
} catch (SecurityException ignore) { |
348 |
< |
} |
337 |
> |
/** |
338 |
> |
* Primary mechanics for invoke, quietlyInvoke. |
339 |
> |
* @return status upon completion |
340 |
> |
*/ |
341 |
> |
private int doInvoke() { |
342 |
> |
int s; boolean completed; |
343 |
> |
if ((s = status) < 0) |
344 |
> |
return s; |
345 |
> |
try { |
346 |
> |
completed = exec(); |
347 |
> |
} catch (Throwable rex) { |
348 |
> |
return setExceptionalCompletion(rex); |
349 |
|
} |
350 |
+ |
if (completed) |
351 |
+ |
return setCompletion(NORMAL); |
352 |
+ |
else |
353 |
+ |
return doJoin(); |
354 |
|
} |
355 |
|
|
356 |
< |
// Recording and reporting exceptions |
356 |
> |
// Exception table support |
357 |
|
|
358 |
< |
private void setDoneExceptionally(Throwable rex) { |
359 |
< |
exceptionMap.put(this, rex); |
360 |
< |
setCompletion(EXCEPTIONAL); |
361 |
< |
} |
358 |
> |
/** |
359 |
> |
* Table of exceptions thrown by tasks, to enable reporting by |
360 |
> |
* callers. Because exceptions are rare, we don't directly keep |
361 |
> |
* them with task objects, but instead use a weak ref table. Note |
362 |
> |
* that cancellation exceptions don't appear in the table, but are |
363 |
> |
* instead recorded as status values. |
364 |
> |
* |
365 |
> |
* Note: These statics are initialized below in static block. |
366 |
> |
*/ |
367 |
> |
private static final ExceptionNode[] exceptionTable; |
368 |
> |
private static final ReentrantLock exceptionTableLock; |
369 |
> |
private static final ReferenceQueue<Object> exceptionTableRefQueue; |
370 |
|
|
371 |
|
/** |
372 |
< |
* Throws the exception associated with status s; |
341 |
< |
* @throws the exception |
372 |
> |
* Fixed capacity for exceptionTable. |
373 |
|
*/ |
374 |
< |
private void reportException(int s) { |
344 |
< |
if ((s &= COMPLETION_MASK) < NORMAL) { |
345 |
< |
if (s == CANCELLED) |
346 |
< |
throw new CancellationException(); |
347 |
< |
else |
348 |
< |
rethrowException(exceptionMap.get(this)); |
349 |
< |
} |
350 |
< |
} |
374 |
> |
private static final int EXCEPTION_MAP_CAPACITY = 32; |
375 |
|
|
376 |
|
/** |
377 |
< |
* Returns result or throws exception using j.u.c.Future conventions |
378 |
< |
* Only call when isDone known to be true. |
377 |
> |
* Key-value nodes for exception table. The chained hash table |
378 |
> |
* uses identity comparisons, full locking, and weak references |
379 |
> |
* for keys. The table has a fixed capacity because it only |
380 |
> |
* maintains task exceptions long enough for joiners to access |
381 |
> |
* them, so should never become very large for sustained |
382 |
> |
* periods. However, since we do not know when the last joiner |
383 |
> |
* completes, we must use weak references and expunge them. We do |
384 |
> |
* so on each operation (hence full locking). Also, some thread in |
385 |
> |
* any ForkJoinPool will call helpExpungeStaleExceptions when its |
386 |
> |
* pool becomes isQuiescent. |
387 |
|
*/ |
388 |
< |
private V reportFutureResult() |
389 |
< |
throws ExecutionException, InterruptedException { |
390 |
< |
int s = status & COMPLETION_MASK; |
391 |
< |
if (s < NORMAL) { |
392 |
< |
Throwable ex; |
393 |
< |
if (s == CANCELLED) |
394 |
< |
throw new CancellationException(); |
395 |
< |
if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null) |
396 |
< |
throw new ExecutionException(ex); |
365 |
< |
if (Thread.interrupted()) |
366 |
< |
throw new InterruptedException(); |
388 |
> |
static final class ExceptionNode extends WeakReference<ForkJoinTask<?>>{ |
389 |
> |
final Throwable ex; |
390 |
> |
ExceptionNode next; |
391 |
> |
final long thrower; // use id not ref to avoid weak cycles |
392 |
> |
ExceptionNode(ForkJoinTask<?> task, Throwable ex, ExceptionNode next) { |
393 |
> |
super(task, exceptionTableRefQueue); |
394 |
> |
this.ex = ex; |
395 |
> |
this.next = next; |
396 |
> |
this.thrower = Thread.currentThread().getId(); |
397 |
|
} |
368 |
– |
return getRawResult(); |
398 |
|
} |
399 |
|
|
400 |
|
/** |
401 |
< |
* Returns result or throws exception using j.u.c.Future conventions |
402 |
< |
* with timeouts |
401 |
> |
* Records exception and sets exceptional completion. |
402 |
> |
* |
403 |
> |
* @return status on exit |
404 |
|
*/ |
405 |
< |
private V reportTimedFutureResult() |
406 |
< |
throws InterruptedException, ExecutionException, TimeoutException { |
407 |
< |
Throwable ex; |
408 |
< |
int s = status & COMPLETION_MASK; |
409 |
< |
if (s == NORMAL) |
410 |
< |
return getRawResult(); |
411 |
< |
if (s == CANCELLED) |
412 |
< |
throw new CancellationException(); |
413 |
< |
if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null) |
414 |
< |
throw new ExecutionException(ex); |
415 |
< |
if (Thread.interrupted()) |
416 |
< |
throw new InterruptedException(); |
417 |
< |
throw new TimeoutException(); |
405 |
> |
private int setExceptionalCompletion(Throwable ex) { |
406 |
> |
int h = System.identityHashCode(this); |
407 |
> |
final ReentrantLock lock = exceptionTableLock; |
408 |
> |
lock.lock(); |
409 |
> |
try { |
410 |
> |
expungeStaleExceptions(); |
411 |
> |
ExceptionNode[] t = exceptionTable; |
412 |
> |
int i = h & (t.length - 1); |
413 |
> |
for (ExceptionNode e = t[i]; ; e = e.next) { |
414 |
> |
if (e == null) { |
415 |
> |
t[i] = new ExceptionNode(this, ex, t[i]); |
416 |
> |
break; |
417 |
> |
} |
418 |
> |
if (e.get() == this) // already present |
419 |
> |
break; |
420 |
> |
} |
421 |
> |
} finally { |
422 |
> |
lock.unlock(); |
423 |
> |
} |
424 |
> |
return setCompletion(EXCEPTIONAL); |
425 |
|
} |
426 |
|
|
390 |
– |
// internal execution methods |
391 |
– |
|
427 |
|
/** |
428 |
< |
* Calls exec, recording completion, and rethrowing exception if |
394 |
< |
* encountered. Caller should normally check status before calling |
395 |
< |
* @return true if completed normally |
428 |
> |
* Removes exception node and clears status |
429 |
|
*/ |
430 |
< |
private boolean tryExec() { |
431 |
< |
try { // try block must contain only call to exec |
432 |
< |
if (!exec()) |
433 |
< |
return false; |
434 |
< |
} catch (Throwable rex) { |
435 |
< |
setDoneExceptionally(rex); |
436 |
< |
rethrowException(rex); |
437 |
< |
return false; // not reached |
430 |
> |
private void clearExceptionalCompletion() { |
431 |
> |
int h = System.identityHashCode(this); |
432 |
> |
final ReentrantLock lock = exceptionTableLock; |
433 |
> |
lock.lock(); |
434 |
> |
try { |
435 |
> |
ExceptionNode[] t = exceptionTable; |
436 |
> |
int i = h & (t.length - 1); |
437 |
> |
ExceptionNode e = t[i]; |
438 |
> |
ExceptionNode pred = null; |
439 |
> |
while (e != null) { |
440 |
> |
ExceptionNode next = e.next; |
441 |
> |
if (e.get() == this) { |
442 |
> |
if (pred == null) |
443 |
> |
t[i] = next; |
444 |
> |
else |
445 |
> |
pred.next = next; |
446 |
> |
break; |
447 |
> |
} |
448 |
> |
pred = e; |
449 |
> |
e = next; |
450 |
> |
} |
451 |
> |
expungeStaleExceptions(); |
452 |
> |
status = 0; |
453 |
> |
} finally { |
454 |
> |
lock.unlock(); |
455 |
|
} |
406 |
– |
setNormalCompletion(); |
407 |
– |
return true; |
456 |
|
} |
457 |
|
|
458 |
|
/** |
459 |
< |
* Main execution method used by worker threads. Invokes |
460 |
< |
* base computation unless already complete |
459 |
> |
* Returns a rethrowable exception for the given task, if |
460 |
> |
* available. To provide accurate stack traces, if the exception |
461 |
> |
* was not thrown by the current thread, we try to create a new |
462 |
> |
* exception of the same type as the one thrown, but with the |
463 |
> |
* recorded exception as its cause. If there is no such |
464 |
> |
* constructor, we instead try to use a no-arg constructor, |
465 |
> |
* followed by initCause, to the same effect. If none of these |
466 |
> |
* apply, or any fail due to other exceptions, we return the |
467 |
> |
* recorded exception, which is still correct, although it may |
468 |
> |
* contain a misleading stack trace. |
469 |
> |
* |
470 |
> |
* @return the exception, or null if none |
471 |
|
*/ |
472 |
< |
final void quietlyExec() { |
473 |
< |
if (status >= 0) { |
472 |
> |
private Throwable getThrowableException() { |
473 |
> |
if (status != EXCEPTIONAL) |
474 |
> |
return null; |
475 |
> |
int h = System.identityHashCode(this); |
476 |
> |
ExceptionNode e; |
477 |
> |
final ReentrantLock lock = exceptionTableLock; |
478 |
> |
lock.lock(); |
479 |
> |
try { |
480 |
> |
expungeStaleExceptions(); |
481 |
> |
ExceptionNode[] t = exceptionTable; |
482 |
> |
e = t[h & (t.length - 1)]; |
483 |
> |
while (e != null && e.get() != this) |
484 |
> |
e = e.next; |
485 |
> |
} finally { |
486 |
> |
lock.unlock(); |
487 |
> |
} |
488 |
> |
Throwable ex; |
489 |
> |
if (e == null || (ex = e.ex) == null) |
490 |
> |
return null; |
491 |
> |
if (e.thrower != Thread.currentThread().getId()) { |
492 |
> |
Class<? extends Throwable> ec = ex.getClass(); |
493 |
|
try { |
494 |
< |
if (!exec()) |
495 |
< |
return; |
496 |
< |
} catch(Throwable rex) { |
497 |
< |
setDoneExceptionally(rex); |
498 |
< |
return; |
494 |
> |
Constructor<?> noArgCtor = null; |
495 |
> |
Constructor<?>[] cs = ec.getConstructors();// public ctors only |
496 |
> |
for (int i = 0; i < cs.length; ++i) { |
497 |
> |
Constructor<?> c = cs[i]; |
498 |
> |
Class<?>[] ps = c.getParameterTypes(); |
499 |
> |
if (ps.length == 0) |
500 |
> |
noArgCtor = c; |
501 |
> |
else if (ps.length == 1 && ps[0] == Throwable.class) |
502 |
> |
return (Throwable)(c.newInstance(ex)); |
503 |
> |
} |
504 |
> |
if (noArgCtor != null) { |
505 |
> |
Throwable wx = (Throwable)(noArgCtor.newInstance()); |
506 |
> |
wx.initCause(ex); |
507 |
> |
return wx; |
508 |
> |
} |
509 |
> |
} catch (Exception ignore) { |
510 |
|
} |
423 |
– |
setNormalCompletion(); |
511 |
|
} |
512 |
+ |
return ex; |
513 |
|
} |
514 |
|
|
515 |
|
/** |
516 |
< |
* Calls exec, recording but not rethrowing exception |
429 |
< |
* Caller should normally check status before calling |
430 |
< |
* @return true if completed normally |
516 |
> |
* Poll stale refs and remove them. Call only while holding lock. |
517 |
|
*/ |
518 |
< |
private boolean tryQuietlyInvoke() { |
519 |
< |
try { |
520 |
< |
if (!exec()) |
521 |
< |
return false; |
522 |
< |
} catch (Throwable rex) { |
523 |
< |
setDoneExceptionally(rex); |
524 |
< |
return false; |
518 |
> |
private static void expungeStaleExceptions() { |
519 |
> |
for (Object x; (x = exceptionTableRefQueue.poll()) != null;) { |
520 |
> |
if (x instanceof ExceptionNode) { |
521 |
> |
ForkJoinTask<?> key = ((ExceptionNode)x).get(); |
522 |
> |
ExceptionNode[] t = exceptionTable; |
523 |
> |
int i = System.identityHashCode(key) & (t.length - 1); |
524 |
> |
ExceptionNode e = t[i]; |
525 |
> |
ExceptionNode pred = null; |
526 |
> |
while (e != null) { |
527 |
> |
ExceptionNode next = e.next; |
528 |
> |
if (e == x) { |
529 |
> |
if (pred == null) |
530 |
> |
t[i] = next; |
531 |
> |
else |
532 |
> |
pred.next = next; |
533 |
> |
break; |
534 |
> |
} |
535 |
> |
pred = e; |
536 |
> |
e = next; |
537 |
> |
} |
538 |
> |
} |
539 |
|
} |
440 |
– |
setNormalCompletion(); |
441 |
– |
return true; |
540 |
|
} |
541 |
|
|
542 |
|
/** |
543 |
< |
* Cancel, ignoring any exceptions it throws |
543 |
> |
* If lock is available, poll stale refs and remove them. |
544 |
> |
* Called from ForkJoinPool when pools become quiescent. |
545 |
|
*/ |
546 |
< |
final void cancelIgnoreExceptions() { |
547 |
< |
try { |
548 |
< |
cancel(false); |
549 |
< |
} catch(Throwable ignore) { |
546 |
> |
static final void helpExpungeStaleExceptions() { |
547 |
> |
final ReentrantLock lock = exceptionTableLock; |
548 |
> |
if (lock.tryLock()) { |
549 |
> |
try { |
550 |
> |
expungeStaleExceptions(); |
551 |
> |
} finally { |
552 |
> |
lock.unlock(); |
553 |
> |
} |
554 |
|
} |
555 |
|
} |
556 |
|
|
557 |
+ |
/** |
558 |
+ |
* Report the result of invoke or join; called only upon |
559 |
+ |
* non-normal return of internal versions. |
560 |
+ |
*/ |
561 |
+ |
private V reportResult() { |
562 |
+ |
int s; Throwable ex; |
563 |
+ |
if ((s = status) == CANCELLED) |
564 |
+ |
throw new CancellationException(); |
565 |
+ |
if (s == EXCEPTIONAL && (ex = getThrowableException()) != null) |
566 |
+ |
UNSAFE.throwException(ex); |
567 |
+ |
return getRawResult(); |
568 |
+ |
} |
569 |
+ |
|
570 |
|
// public methods |
571 |
|
|
572 |
|
/** |
573 |
|
* Arranges to asynchronously execute this task. While it is not |
574 |
|
* necessarily enforced, it is a usage error to fork a task more |
575 |
< |
* than once unless it has completed and been reinitialized. This |
576 |
< |
* method may be invoked only from within other ForkJoinTask |
577 |
< |
* computations. Attempts to invoke in other contexts result in |
578 |
< |
* exceptions or errors including ClassCastException. |
575 |
> |
* than once unless it has completed and been reinitialized. |
576 |
> |
* Subsequent modifications to the state of this task or any data |
577 |
> |
* it operates on are not necessarily consistently observable by |
578 |
> |
* any thread other than the one executing it unless preceded by a |
579 |
> |
* call to {@link #join} or related methods, or a call to {@link |
580 |
> |
* #isDone} returning {@code true}. |
581 |
> |
* |
582 |
> |
* <p>This method may be invoked only from within {@code |
583 |
> |
* ForkJoinPool} computations (as may be determined using method |
584 |
> |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
585 |
> |
* result in exceptions or errors, possibly including {@code |
586 |
> |
* ClassCastException}. |
587 |
> |
* |
588 |
> |
* @return {@code this}, to simplify usage |
589 |
|
*/ |
590 |
< |
public final void fork() { |
591 |
< |
((ForkJoinWorkerThread)(Thread.currentThread())).pushTask(this); |
590 |
> |
public final ForkJoinTask<V> fork() { |
591 |
> |
((ForkJoinWorkerThread) Thread.currentThread()) |
592 |
> |
.pushTask(this); |
593 |
> |
return this; |
594 |
|
} |
595 |
|
|
596 |
|
/** |
597 |
< |
* Returns the result of the computation when it is ready. |
598 |
< |
* This method differs from <tt>get</tt> in that abnormal |
599 |
< |
* completion results in RuntimeExceptions or Errors, not |
600 |
< |
* ExecutionExceptions. |
597 |
> |
* Returns the result of the computation when it {@link #isDone is |
598 |
> |
* done}. This method differs from {@link #get()} in that |
599 |
> |
* abnormal completion results in {@code RuntimeException} or |
600 |
> |
* {@code Error}, not {@code ExecutionException}, and that |
601 |
> |
* interrupts of the calling thread do <em>not</em> cause the |
602 |
> |
* method to abruptly return by throwing {@code |
603 |
> |
* InterruptedException}. |
604 |
|
* |
605 |
|
* @return the computed result |
606 |
|
*/ |
607 |
|
public final V join() { |
608 |
< |
ForkJoinWorkerThread w = getWorker(); |
609 |
< |
if (w == null || status < 0 || !w.unpushTask(this) || !tryExec()) |
610 |
< |
reportException(awaitDone(w, true)); |
611 |
< |
return getRawResult(); |
481 |
< |
} |
482 |
< |
|
483 |
< |
public final V get() throws InterruptedException, ExecutionException { |
484 |
< |
ForkJoinWorkerThread w = getWorker(); |
485 |
< |
if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke()) |
486 |
< |
awaitDone(w, true); |
487 |
< |
return reportFutureResult(); |
488 |
< |
} |
489 |
< |
|
490 |
< |
public final V get(long timeout, TimeUnit unit) |
491 |
< |
throws InterruptedException, ExecutionException, TimeoutException { |
492 |
< |
ForkJoinWorkerThread w = getWorker(); |
493 |
< |
if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke()) |
494 |
< |
awaitDone(w, unit.toNanos(timeout)); |
495 |
< |
return reportTimedFutureResult(); |
608 |
> |
if (doJoin() != NORMAL) |
609 |
> |
return reportResult(); |
610 |
> |
else |
611 |
> |
return getRawResult(); |
612 |
|
} |
613 |
|
|
614 |
|
/** |
615 |
< |
* Possibly executes other tasks until this task is ready, then |
616 |
< |
* returns the result of the computation. This method may be more |
617 |
< |
* efficient than <tt>join</tt>, but is only applicable when there |
618 |
< |
* are no potemtial dependencies between continuation of the |
619 |
< |
* current task and that of any other task that might be executed |
504 |
< |
* while helping. (This usually holds for pure divide-and-conquer |
505 |
< |
* tasks). |
615 |
> |
* Commences performing this task, awaits its completion if |
616 |
> |
* necessary, and returns its result, or throws an (unchecked) |
617 |
> |
* {@code RuntimeException} or {@code Error} if the underlying |
618 |
> |
* computation did so. |
619 |
> |
* |
620 |
|
* @return the computed result |
621 |
|
*/ |
622 |
< |
public final V helpJoin() { |
623 |
< |
ForkJoinWorkerThread w = (ForkJoinWorkerThread)(Thread.currentThread()); |
624 |
< |
if (status < 0 || !w.unpushTask(this) || !tryExec()) |
625 |
< |
reportException(w.helpJoinTask(this)); |
626 |
< |
return getRawResult(); |
622 |
> |
public final V invoke() { |
623 |
> |
if (doInvoke() != NORMAL) |
624 |
> |
return reportResult(); |
625 |
> |
else |
626 |
> |
return getRawResult(); |
627 |
|
} |
628 |
|
|
629 |
|
/** |
630 |
< |
* Performs this task, awaits its completion if necessary, and |
631 |
< |
* return its result. |
632 |
< |
* @throws Throwable (a RuntimeException, Error, or unchecked |
633 |
< |
* exception) if the underlying computation did so. |
634 |
< |
* @return the computed result |
630 |
> |
* Forks the given tasks, returning when {@code isDone} holds for |
631 |
> |
* each task or an (unchecked) exception is encountered, in which |
632 |
> |
* case the exception is rethrown. If more than one task |
633 |
> |
* encounters an exception, then this method throws any one of |
634 |
> |
* these exceptions. If any task encounters an exception, the |
635 |
> |
* other may be cancelled. However, the execution status of |
636 |
> |
* individual tasks is not guaranteed upon exceptional return. The |
637 |
> |
* status of each task may be obtained using {@link |
638 |
> |
* #getException()} and related methods to check if they have been |
639 |
> |
* cancelled, completed normally or exceptionally, or left |
640 |
> |
* unprocessed. |
641 |
> |
* |
642 |
> |
* <p>This method may be invoked only from within {@code |
643 |
> |
* ForkJoinPool} computations (as may be determined using method |
644 |
> |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
645 |
> |
* result in exceptions or errors, possibly including {@code |
646 |
> |
* ClassCastException}. |
647 |
> |
* |
648 |
> |
* @param t1 the first task |
649 |
> |
* @param t2 the second task |
650 |
> |
* @throws NullPointerException if any task is null |
651 |
|
*/ |
652 |
< |
public final V invoke() { |
653 |
< |
if (status >= 0 && tryExec()) |
654 |
< |
return getRawResult(); |
655 |
< |
else |
526 |
< |
return join(); |
652 |
> |
public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) { |
653 |
> |
t2.fork(); |
654 |
> |
t1.invoke(); |
655 |
> |
t2.join(); |
656 |
|
} |
657 |
|
|
658 |
|
/** |
659 |
< |
* Joins this task, without returning its result or throwing an |
660 |
< |
* exception. This method may be useful when processing |
661 |
< |
* collections of tasks when some have been cancelled or otherwise |
662 |
< |
* known to have aborted. |
659 |
> |
* Forks the given tasks, returning when {@code isDone} holds for |
660 |
> |
* each task or an (unchecked) exception is encountered, in which |
661 |
> |
* case the exception is rethrown. If more than one task |
662 |
> |
* encounters an exception, then this method throws any one of |
663 |
> |
* these exceptions. If any task encounters an exception, others |
664 |
> |
* may be cancelled. However, the execution status of individual |
665 |
> |
* tasks is not guaranteed upon exceptional return. The status of |
666 |
> |
* each task may be obtained using {@link #getException()} and |
667 |
> |
* related methods to check if they have been cancelled, completed |
668 |
> |
* normally or exceptionally, or left unprocessed. |
669 |
> |
* |
670 |
> |
* <p>This method may be invoked only from within {@code |
671 |
> |
* ForkJoinPool} computations (as may be determined using method |
672 |
> |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
673 |
> |
* result in exceptions or errors, possibly including {@code |
674 |
> |
* ClassCastException}. |
675 |
> |
* |
676 |
> |
* @param tasks the tasks |
677 |
> |
* @throws NullPointerException if any task is null |
678 |
|
*/ |
679 |
< |
public final void quietlyJoin() { |
680 |
< |
if (status >= 0) { |
681 |
< |
ForkJoinWorkerThread w = getWorker(); |
682 |
< |
if (w == null || !w.unpushTask(this) || !tryQuietlyInvoke()) |
683 |
< |
awaitDone(w, true); |
679 |
> |
public static void invokeAll(ForkJoinTask<?>... tasks) { |
680 |
> |
Throwable ex = null; |
681 |
> |
int last = tasks.length - 1; |
682 |
> |
for (int i = last; i >= 0; --i) { |
683 |
> |
ForkJoinTask<?> t = tasks[i]; |
684 |
> |
if (t == null) { |
685 |
> |
if (ex == null) |
686 |
> |
ex = new NullPointerException(); |
687 |
> |
} |
688 |
> |
else if (i != 0) |
689 |
> |
t.fork(); |
690 |
> |
else if (t.doInvoke() < NORMAL && ex == null) |
691 |
> |
ex = t.getException(); |
692 |
|
} |
693 |
+ |
for (int i = 1; i <= last; ++i) { |
694 |
+ |
ForkJoinTask<?> t = tasks[i]; |
695 |
+ |
if (t != null) { |
696 |
+ |
if (ex != null) |
697 |
+ |
t.cancel(false); |
698 |
+ |
else if (t.doJoin() < NORMAL) |
699 |
+ |
ex = t.getException(); |
700 |
+ |
} |
701 |
+ |
} |
702 |
+ |
if (ex != null) |
703 |
+ |
UNSAFE.throwException(ex); |
704 |
|
} |
705 |
|
|
706 |
|
/** |
707 |
< |
* Possibly executes other tasks until this task is ready. |
707 |
> |
* Forks all tasks in the specified collection, returning when |
708 |
> |
* {@code isDone} holds for each task or an (unchecked) exception |
709 |
> |
* is encountered, in which case the exception is rethrown. If |
710 |
> |
* more than one task encounters an exception, then this method |
711 |
> |
* throws any one of these exceptions. If any task encounters an |
712 |
> |
* exception, others may be cancelled. However, the execution |
713 |
> |
* status of individual tasks is not guaranteed upon exceptional |
714 |
> |
* return. The status of each task may be obtained using {@link |
715 |
> |
* #getException()} and related methods to check if they have been |
716 |
> |
* cancelled, completed normally or exceptionally, or left |
717 |
> |
* unprocessed. |
718 |
> |
* |
719 |
> |
* <p>This method may be invoked only from within {@code |
720 |
> |
* ForkJoinPool} computations (as may be determined using method |
721 |
> |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
722 |
> |
* result in exceptions or errors, possibly including {@code |
723 |
> |
* ClassCastException}. |
724 |
> |
* |
725 |
> |
* @param tasks the collection of tasks |
726 |
> |
* @return the tasks argument, to simplify usage |
727 |
> |
* @throws NullPointerException if tasks or any element are null |
728 |
|
*/ |
729 |
< |
public final void quietlyHelpJoin() { |
730 |
< |
if (status >= 0) { |
731 |
< |
ForkJoinWorkerThread w = |
732 |
< |
(ForkJoinWorkerThread)(Thread.currentThread()); |
733 |
< |
if (!w.unpushTask(this) || !tryQuietlyInvoke()) |
734 |
< |
w.helpJoinTask(this); |
729 |
> |
public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) { |
730 |
> |
if (!(tasks instanceof RandomAccess) || !(tasks instanceof List<?>)) { |
731 |
> |
invokeAll(tasks.toArray(new ForkJoinTask<?>[tasks.size()])); |
732 |
> |
return tasks; |
733 |
> |
} |
734 |
> |
@SuppressWarnings("unchecked") |
735 |
> |
List<? extends ForkJoinTask<?>> ts = |
736 |
> |
(List<? extends ForkJoinTask<?>>) tasks; |
737 |
> |
Throwable ex = null; |
738 |
> |
int last = ts.size() - 1; |
739 |
> |
for (int i = last; i >= 0; --i) { |
740 |
> |
ForkJoinTask<?> t = ts.get(i); |
741 |
> |
if (t == null) { |
742 |
> |
if (ex == null) |
743 |
> |
ex = new NullPointerException(); |
744 |
> |
} |
745 |
> |
else if (i != 0) |
746 |
> |
t.fork(); |
747 |
> |
else if (t.doInvoke() < NORMAL && ex == null) |
748 |
> |
ex = t.getException(); |
749 |
> |
} |
750 |
> |
for (int i = 1; i <= last; ++i) { |
751 |
> |
ForkJoinTask<?> t = ts.get(i); |
752 |
> |
if (t != null) { |
753 |
> |
if (ex != null) |
754 |
> |
t.cancel(false); |
755 |
> |
else if (t.doJoin() < NORMAL) |
756 |
> |
ex = t.getException(); |
757 |
> |
} |
758 |
|
} |
759 |
+ |
if (ex != null) |
760 |
+ |
UNSAFE.throwException(ex); |
761 |
+ |
return tasks; |
762 |
|
} |
763 |
|
|
764 |
|
/** |
765 |
< |
* Performs this task and awaits its completion if necessary, |
766 |
< |
* without returning its result or throwing an exception. This |
767 |
< |
* method may be useful when processing collections of tasks when |
768 |
< |
* some have been cancelled or otherwise known to have aborted. |
765 |
> |
* Attempts to cancel execution of this task. This attempt will |
766 |
> |
* fail if the task has already completed or could not be |
767 |
> |
* cancelled for some other reason. If successful, and this task |
768 |
> |
* has not started when {@code cancel} is called, execution of |
769 |
> |
* this task is suppressed. After this method returns |
770 |
> |
* successfully, unless there is an intervening call to {@link |
771 |
> |
* #reinitialize}, subsequent calls to {@link #isCancelled}, |
772 |
> |
* {@link #isDone}, and {@code cancel} will return {@code true} |
773 |
> |
* and calls to {@link #join} and related methods will result in |
774 |
> |
* {@code CancellationException}. |
775 |
> |
* |
776 |
> |
* <p>This method may be overridden in subclasses, but if so, must |
777 |
> |
* still ensure that these properties hold. In particular, the |
778 |
> |
* {@code cancel} method itself must not throw exceptions. |
779 |
> |
* |
780 |
> |
* <p>This method is designed to be invoked by <em>other</em> |
781 |
> |
* tasks. To terminate the current task, you can just return or |
782 |
> |
* throw an unchecked exception from its computation method, or |
783 |
> |
* invoke {@link #completeExceptionally}. |
784 |
> |
* |
785 |
> |
* @param mayInterruptIfRunning this value has no effect in the |
786 |
> |
* default implementation because interrupts are not used to |
787 |
> |
* control cancellation. |
788 |
> |
* |
789 |
> |
* @return {@code true} if this task is now cancelled |
790 |
|
*/ |
791 |
< |
public final void quietlyInvoke() { |
792 |
< |
if (status >= 0 && !tryQuietlyInvoke()) |
563 |
< |
quietlyJoin(); |
791 |
> |
public boolean cancel(boolean mayInterruptIfRunning) { |
792 |
> |
return setCompletion(CANCELLED) == CANCELLED; |
793 |
|
} |
794 |
|
|
795 |
|
/** |
796 |
< |
* Returns true if the computation performed by this task has |
797 |
< |
* completed (or has been cancelled). |
798 |
< |
* @return true if this computation has completed |
796 |
> |
* Cancels, ignoring any exceptions thrown by cancel. Used during |
797 |
> |
* worker and pool shutdown. Cancel is spec'ed not to throw any |
798 |
> |
* exceptions, but if it does anyway, we have no recourse during |
799 |
> |
* shutdown, so guard against this case. |
800 |
|
*/ |
801 |
+ |
final void cancelIgnoringExceptions() { |
802 |
+ |
try { |
803 |
+ |
cancel(false); |
804 |
+ |
} catch (Throwable ignore) { |
805 |
+ |
} |
806 |
+ |
} |
807 |
+ |
|
808 |
|
public final boolean isDone() { |
809 |
|
return status < 0; |
810 |
|
} |
811 |
|
|
575 |
– |
/** |
576 |
– |
* Returns true if this task was cancelled. |
577 |
– |
* @return true if this task was cancelled |
578 |
– |
*/ |
812 |
|
public final boolean isCancelled() { |
813 |
< |
return (status & COMPLETION_MASK) == CANCELLED; |
813 |
> |
return status == CANCELLED; |
814 |
|
} |
815 |
|
|
816 |
|
/** |
817 |
< |
* Returns true if this task threw an exception or was cancelled |
818 |
< |
* @return true if this task threw an exception or was cancelled |
817 |
> |
* Returns {@code true} if this task threw an exception or was cancelled. |
818 |
> |
* |
819 |
> |
* @return {@code true} if this task threw an exception or was cancelled |
820 |
|
*/ |
821 |
< |
public final boolean completedAbnormally() { |
822 |
< |
return (status & COMPLETION_MASK) < NORMAL; |
821 |
> |
public final boolean isCompletedAbnormally() { |
822 |
> |
return status < NORMAL; |
823 |
|
} |
824 |
|
|
825 |
|
/** |
826 |
< |
* Returns the exception thrown by the base computation, or a |
827 |
< |
* CancellationException if cancelled, or null if none or if the |
828 |
< |
* method has not yet completed. |
829 |
< |
* @return the exception, or null if none |
826 |
> |
* Returns {@code true} if this task completed without throwing an |
827 |
> |
* exception and was not cancelled. |
828 |
> |
* |
829 |
> |
* @return {@code true} if this task completed without throwing an |
830 |
> |
* exception and was not cancelled |
831 |
|
*/ |
832 |
< |
public final Throwable getException() { |
833 |
< |
int s = status & COMPLETION_MASK; |
599 |
< |
if (s >= NORMAL) |
600 |
< |
return null; |
601 |
< |
if (s == CANCELLED) |
602 |
< |
return new CancellationException(); |
603 |
< |
return exceptionMap.get(this); |
832 |
> |
public final boolean isCompletedNormally() { |
833 |
> |
return status == NORMAL; |
834 |
|
} |
835 |
|
|
836 |
|
/** |
837 |
< |
* Asserts that the results of this task's computation will not be |
838 |
< |
* used. If a cancellation occurs before this task is processed, |
839 |
< |
* then its <tt>compute</tt> method will not be executed, |
610 |
< |
* <tt>isCancelled</tt> will report true, and <tt>join</tt> will |
611 |
< |
* result in a CancellationException being thrown. Otherwise, when |
612 |
< |
* cancellation races with completion, there are no guarantees |
613 |
< |
* about whether <tt>isCancelled</tt> will report true, whether |
614 |
< |
* <tt>join</tt> will return normally or via an exception, or |
615 |
< |
* whether these behaviors will remain consistent upon repeated |
616 |
< |
* invocation. |
617 |
< |
* |
618 |
< |
* <p>This method may be overridden in subclasses, but if so, must |
619 |
< |
* still ensure that these minimal properties hold. In particular, |
620 |
< |
* the cancel method itself must not throw exceptions. |
621 |
< |
* |
622 |
< |
* <p> This method is designed to be invoked by <em>other</em> |
623 |
< |
* tasks. To terminate the current task, you can just return or |
624 |
< |
* throw an unchecked exception from its computation method, or |
625 |
< |
* invoke <tt>completeExceptionally(someException)</tt>. |
626 |
< |
* |
627 |
< |
* @param mayInterruptIfRunning this value is ignored in the |
628 |
< |
* default implementation because tasks are not in general |
629 |
< |
* cancelled via interruption. |
837 |
> |
* Returns the exception thrown by the base computation, or a |
838 |
> |
* {@code CancellationException} if cancelled, or {@code null} if |
839 |
> |
* none or if the method has not yet completed. |
840 |
|
* |
841 |
< |
* @return true if this task is now cancelled |
841 |
> |
* @return the exception, or {@code null} if none |
842 |
|
*/ |
843 |
< |
public boolean cancel(boolean mayInterruptIfRunning) { |
844 |
< |
setCompletion(CANCELLED); |
845 |
< |
return (status & COMPLETION_MASK) == CANCELLED; |
843 |
> |
public final Throwable getException() { |
844 |
> |
int s = status; |
845 |
> |
return ((s >= NORMAL) ? null : |
846 |
> |
(s == CANCELLED) ? new CancellationException() : |
847 |
> |
getThrowableException()); |
848 |
|
} |
849 |
|
|
850 |
|
/** |
851 |
|
* Completes this task abnormally, and if not already aborted or |
852 |
|
* cancelled, causes it to throw the given exception upon |
853 |
< |
* <tt>join</tt> and related operations. This method may be used |
853 |
> |
* {@code join} and related operations. This method may be used |
854 |
|
* to induce exceptions in asynchronous tasks, or to force |
855 |
< |
* completion of tasks that would not otherwise complete. This |
856 |
< |
* method is overridable, but overridden versions must invoke |
857 |
< |
* <tt>super</tt> implementation to maintain guarantees. |
858 |
< |
* @param ex the exception to throw. If this exception is |
859 |
< |
* not a RuntimeException or Error, the actual exception thrown |
860 |
< |
* will be a RuntimeException with cause ex. |
855 |
> |
* completion of tasks that would not otherwise complete. Its use |
856 |
> |
* in other situations is discouraged. This method is |
857 |
> |
* overridable, but overridden versions must invoke {@code super} |
858 |
> |
* implementation to maintain guarantees. |
859 |
> |
* |
860 |
> |
* @param ex the exception to throw. If this exception is not a |
861 |
> |
* {@code RuntimeException} or {@code Error}, the actual exception |
862 |
> |
* thrown will be a {@code RuntimeException} with cause {@code ex}. |
863 |
|
*/ |
864 |
|
public void completeExceptionally(Throwable ex) { |
865 |
< |
setDoneExceptionally((ex instanceof RuntimeException) || |
866 |
< |
(ex instanceof Error)? ex : |
867 |
< |
new RuntimeException(ex)); |
865 |
> |
setExceptionalCompletion((ex instanceof RuntimeException) || |
866 |
> |
(ex instanceof Error) ? ex : |
867 |
> |
new RuntimeException(ex)); |
868 |
|
} |
869 |
|
|
870 |
|
/** |
871 |
|
* Completes this task, and if not already aborted or cancelled, |
872 |
< |
* returning a <tt>null</tt> result upon <tt>join</tt> and related |
873 |
< |
* operations. This method may be used to provide results for |
874 |
< |
* asynchronous tasks, or to provide alternative handling for |
875 |
< |
* tasks that would not otherwise complete normally. |
872 |
> |
* returning the given value as the result of subsequent |
873 |
> |
* invocations of {@code join} and related operations. This method |
874 |
> |
* may be used to provide results for asynchronous tasks, or to |
875 |
> |
* provide alternative handling for tasks that would not otherwise |
876 |
> |
* complete normally. Its use in other situations is |
877 |
> |
* discouraged. This method is overridable, but overridden |
878 |
> |
* versions must invoke {@code super} implementation to maintain |
879 |
> |
* guarantees. |
880 |
|
* |
881 |
< |
* @param value the result value for this task. |
881 |
> |
* @param value the result value for this task |
882 |
|
*/ |
883 |
|
public void complete(V value) { |
884 |
|
try { |
885 |
|
setRawResult(value); |
886 |
< |
} catch(Throwable rex) { |
887 |
< |
setDoneExceptionally(rex); |
886 |
> |
} catch (Throwable rex) { |
887 |
> |
setExceptionalCompletion(rex); |
888 |
|
return; |
889 |
|
} |
890 |
< |
setNormalCompletion(); |
890 |
> |
setCompletion(NORMAL); |
891 |
> |
} |
892 |
> |
|
893 |
> |
/** |
894 |
> |
* Waits if necessary for the computation to complete, and then |
895 |
> |
* retrieves its result. |
896 |
> |
* |
897 |
> |
* @return the computed result |
898 |
> |
* @throws CancellationException if the computation was cancelled |
899 |
> |
* @throws ExecutionException if the computation threw an |
900 |
> |
* exception |
901 |
> |
* @throws InterruptedException if the current thread is not a |
902 |
> |
* member of a ForkJoinPool and was interrupted while waiting |
903 |
> |
*/ |
904 |
> |
public final V get() throws InterruptedException, ExecutionException { |
905 |
> |
int s = (Thread.currentThread() instanceof ForkJoinWorkerThread) ? |
906 |
> |
doJoin() : externalInterruptibleAwaitDone(0L); |
907 |
> |
Throwable ex; |
908 |
> |
if (s == CANCELLED) |
909 |
> |
throw new CancellationException(); |
910 |
> |
if (s == EXCEPTIONAL && (ex = getThrowableException()) != null) |
911 |
> |
throw new ExecutionException(ex); |
912 |
> |
return getRawResult(); |
913 |
> |
} |
914 |
> |
|
915 |
> |
/** |
916 |
> |
* Waits if necessary for at most the given time for the computation |
917 |
> |
* to complete, and then retrieves its result, if available. |
918 |
> |
* |
919 |
> |
* @param timeout the maximum time to wait |
920 |
> |
* @param unit the time unit of the timeout argument |
921 |
> |
* @return the computed result |
922 |
> |
* @throws CancellationException if the computation was cancelled |
923 |
> |
* @throws ExecutionException if the computation threw an |
924 |
> |
* exception |
925 |
> |
* @throws InterruptedException if the current thread is not a |
926 |
> |
* member of a ForkJoinPool and was interrupted while waiting |
927 |
> |
* @throws TimeoutException if the wait timed out |
928 |
> |
*/ |
929 |
> |
public final V get(long timeout, TimeUnit unit) |
930 |
> |
throws InterruptedException, ExecutionException, TimeoutException { |
931 |
> |
Thread t = Thread.currentThread(); |
932 |
> |
if (t instanceof ForkJoinWorkerThread) { |
933 |
> |
ForkJoinWorkerThread w = (ForkJoinWorkerThread) t; |
934 |
> |
long nanos = unit.toNanos(timeout); |
935 |
> |
if (status >= 0) { |
936 |
> |
boolean completed = false; |
937 |
> |
if (w.unpushTask(this)) { |
938 |
> |
try { |
939 |
> |
completed = exec(); |
940 |
> |
} catch (Throwable rex) { |
941 |
> |
setExceptionalCompletion(rex); |
942 |
> |
} |
943 |
> |
} |
944 |
> |
if (completed) |
945 |
> |
setCompletion(NORMAL); |
946 |
> |
else if (status >= 0 && nanos > 0) |
947 |
> |
w.pool.timedAwaitJoin(this, nanos); |
948 |
> |
} |
949 |
> |
} |
950 |
> |
else { |
951 |
> |
long millis = unit.toMillis(timeout); |
952 |
> |
if (millis > 0) |
953 |
> |
externalInterruptibleAwaitDone(millis); |
954 |
> |
} |
955 |
> |
int s = status; |
956 |
> |
if (s != NORMAL) { |
957 |
> |
Throwable ex; |
958 |
> |
if (s == CANCELLED) |
959 |
> |
throw new CancellationException(); |
960 |
> |
if (s != EXCEPTIONAL) |
961 |
> |
throw new TimeoutException(); |
962 |
> |
if ((ex = getThrowableException()) != null) |
963 |
> |
throw new ExecutionException(ex); |
964 |
> |
} |
965 |
> |
return getRawResult(); |
966 |
> |
} |
967 |
> |
|
968 |
> |
/** |
969 |
> |
* Joins this task, without returning its result or throwing its |
970 |
> |
* exception. This method may be useful when processing |
971 |
> |
* collections of tasks when some have been cancelled or otherwise |
972 |
> |
* known to have aborted. |
973 |
> |
*/ |
974 |
> |
public final void quietlyJoin() { |
975 |
> |
doJoin(); |
976 |
> |
} |
977 |
> |
|
978 |
> |
/** |
979 |
> |
* Commences performing this task and awaits its completion if |
980 |
> |
* necessary, without returning its result or throwing its |
981 |
> |
* exception. |
982 |
> |
*/ |
983 |
> |
public final void quietlyInvoke() { |
984 |
> |
doInvoke(); |
985 |
> |
} |
986 |
> |
|
987 |
> |
/** |
988 |
> |
* Possibly executes tasks until the pool hosting the current task |
989 |
> |
* {@link ForkJoinPool#isQuiescent is quiescent}. This method may |
990 |
> |
* be of use in designs in which many tasks are forked, but none |
991 |
> |
* are explicitly joined, instead executing them until all are |
992 |
> |
* processed. |
993 |
> |
* |
994 |
> |
* <p>This method may be invoked only from within {@code |
995 |
> |
* ForkJoinPool} computations (as may be determined using method |
996 |
> |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
997 |
> |
* result in exceptions or errors, possibly including {@code |
998 |
> |
* ClassCastException}. |
999 |
> |
*/ |
1000 |
> |
public static void helpQuiesce() { |
1001 |
> |
((ForkJoinWorkerThread) Thread.currentThread()) |
1002 |
> |
.helpQuiescePool(); |
1003 |
|
} |
1004 |
|
|
1005 |
|
/** |
1006 |
|
* Resets the internal bookkeeping state of this task, allowing a |
1007 |
< |
* subsequent <tt>fork</tt>. This method allows repeated reuse of |
1007 |
> |
* subsequent {@code fork}. This method allows repeated reuse of |
1008 |
|
* this task, but only if reuse occurs when this task has either |
1009 |
|
* never been forked, or has been forked, then completed and all |
1010 |
|
* outstanding joins of this task have also completed. Effects |
1011 |
< |
* under any other usage conditions are not guaranteed, and are |
1012 |
< |
* almost surely wrong. This method may be useful when executing |
1011 |
> |
* under any other usage conditions are not guaranteed. |
1012 |
> |
* This method may be useful when executing |
1013 |
|
* pre-constructed trees of subtasks in loops. |
1014 |
+ |
* |
1015 |
+ |
* <p>Upon completion of this method, {@code isDone()} reports |
1016 |
+ |
* {@code false}, and {@code getException()} reports {@code |
1017 |
+ |
* null}. However, the value returned by {@code getRawResult} is |
1018 |
+ |
* unaffected. To clear this value, you can invoke {@code |
1019 |
+ |
* setRawResult(null)}. |
1020 |
|
*/ |
1021 |
|
public void reinitialize() { |
1022 |
< |
if ((status & COMPLETION_MASK) == EXCEPTIONAL) |
1023 |
< |
exceptionMap.remove(this); |
1024 |
< |
status = 0; |
1025 |
< |
} |
690 |
< |
|
691 |
< |
/** |
692 |
< |
* Tries to unschedule this task for execution. This method will |
693 |
< |
* typically succeed if this task is the next task that would be |
694 |
< |
* executed by the current thread, and will typically fail (return |
695 |
< |
* false) otherwise. This method may be useful when arranging |
696 |
< |
* faster local processing of tasks that could have been, but were |
697 |
< |
* not, stolen. |
698 |
< |
* @return true if unforked |
699 |
< |
*/ |
700 |
< |
public boolean tryUnfork() { |
701 |
< |
return ((ForkJoinWorkerThread)(Thread.currentThread())).unpushTask(this); |
1022 |
> |
if (status == EXCEPTIONAL) |
1023 |
> |
clearExceptionalCompletion(); |
1024 |
> |
else |
1025 |
> |
status = 0; |
1026 |
|
} |
1027 |
|
|
1028 |
|
/** |
1029 |
< |
* Forks both tasks, returning when <tt>isDone</tt> holds for both |
1030 |
< |
* of them or an exception is encountered. This method may be |
1031 |
< |
* invoked only from within other ForkJoinTask |
1032 |
< |
* computations. Attempts to invoke in other contexts result in |
1033 |
< |
* exceptions or errors including ClassCastException. |
710 |
< |
* @param t1 one task |
711 |
< |
* @param t2 the other task |
712 |
< |
* @throws NullPointerException if t1 or t2 are null |
713 |
< |
* @throws RuntimeException or Error if either task did so. |
1029 |
> |
* Returns the pool hosting the current task execution, or null |
1030 |
> |
* if this task is executing outside of any ForkJoinPool. |
1031 |
> |
* |
1032 |
> |
* @see #inForkJoinPool |
1033 |
> |
* @return the pool, or {@code null} if none |
1034 |
|
*/ |
1035 |
< |
public static void invokeAll(ForkJoinTask<?>t1, ForkJoinTask<?> t2) { |
1036 |
< |
t2.fork(); |
1037 |
< |
t1.invoke(); |
1038 |
< |
t2.join(); |
1035 |
> |
public static ForkJoinPool getPool() { |
1036 |
> |
Thread t = Thread.currentThread(); |
1037 |
> |
return (t instanceof ForkJoinWorkerThread) ? |
1038 |
> |
((ForkJoinWorkerThread) t).pool : null; |
1039 |
|
} |
1040 |
|
|
1041 |
|
/** |
1042 |
< |
* Forks the given tasks, returning when <tt>isDone</tt> holds for |
1043 |
< |
* all of them. If any task encounters an exception, others may be |
1044 |
< |
* cancelled. This method may be invoked only from within other |
1045 |
< |
* ForkJoinTask computations. Attempts to invoke in other contexts |
1046 |
< |
* result in exceptions or errors including ClassCastException. |
1047 |
< |
* @param tasks the array of tasks |
728 |
< |
* @throws NullPointerException if tasks or any element are null. |
729 |
< |
* @throws RuntimeException or Error if any task did so. |
1042 |
> |
* Returns {@code true} if the current thread is a {@link |
1043 |
> |
* ForkJoinWorkerThread} executing as a ForkJoinPool computation. |
1044 |
> |
* |
1045 |
> |
* @return {@code true} if the current thread is a {@link |
1046 |
> |
* ForkJoinWorkerThread} executing as a ForkJoinPool computation, |
1047 |
> |
* or {@code false} otherwise |
1048 |
|
*/ |
1049 |
< |
public static void invokeAll(ForkJoinTask<?>... tasks) { |
1050 |
< |
Throwable ex = null; |
733 |
< |
int last = tasks.length - 1; |
734 |
< |
for (int i = last; i >= 0; --i) { |
735 |
< |
ForkJoinTask<?> t = tasks[i]; |
736 |
< |
if (t == null) { |
737 |
< |
if (ex == null) |
738 |
< |
ex = new NullPointerException(); |
739 |
< |
} |
740 |
< |
else if (i != 0) |
741 |
< |
t.fork(); |
742 |
< |
else { |
743 |
< |
t.quietlyInvoke(); |
744 |
< |
if (ex == null) |
745 |
< |
ex = t.getException(); |
746 |
< |
} |
747 |
< |
} |
748 |
< |
for (int i = 1; i <= last; ++i) { |
749 |
< |
ForkJoinTask<?> t = tasks[i]; |
750 |
< |
if (t != null) { |
751 |
< |
if (ex != null) |
752 |
< |
t.cancel(false); |
753 |
< |
else { |
754 |
< |
t.quietlyJoin(); |
755 |
< |
if (ex == null) |
756 |
< |
ex = t.getException(); |
757 |
< |
} |
758 |
< |
} |
759 |
< |
} |
760 |
< |
if (ex != null) |
761 |
< |
rethrowException(ex); |
1049 |
> |
public static boolean inForkJoinPool() { |
1050 |
> |
return Thread.currentThread() instanceof ForkJoinWorkerThread; |
1051 |
|
} |
1052 |
|
|
1053 |
|
/** |
1054 |
< |
* Forks all tasks in the collection, returning when |
1055 |
< |
* <tt>isDone</tt> holds for all of them. If any task encounters |
1056 |
< |
* an exception, others may be cancelled. This method may be |
1057 |
< |
* invoked only from within other ForkJoinTask |
1058 |
< |
* computations. Attempts to invoke in other contexts result in |
1059 |
< |
* exceptions or errors including ClassCastException. |
1060 |
< |
* @param tasks the collection of tasks |
1061 |
< |
* @throws NullPointerException if tasks or any element are null. |
1062 |
< |
* @throws RuntimeException or Error if any task did so. |
1054 |
> |
* Tries to unschedule this task for execution. This method will |
1055 |
> |
* typically succeed if this task is the most recently forked task |
1056 |
> |
* by the current thread, and has not commenced executing in |
1057 |
> |
* another thread. This method may be useful when arranging |
1058 |
> |
* alternative local processing of tasks that could have been, but |
1059 |
> |
* were not, stolen. |
1060 |
> |
* |
1061 |
> |
* <p>This method may be invoked only from within {@code |
1062 |
> |
* ForkJoinPool} computations (as may be determined using method |
1063 |
> |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
1064 |
> |
* result in exceptions or errors, possibly including {@code |
1065 |
> |
* ClassCastException}. |
1066 |
> |
* |
1067 |
> |
* @return {@code true} if unforked |
1068 |
|
*/ |
1069 |
< |
public static void invokeAll(Collection<? extends ForkJoinTask<?>> tasks) { |
1070 |
< |
if (!(tasks instanceof List)) { |
1071 |
< |
invokeAll(tasks.toArray(new ForkJoinTask[tasks.size()])); |
778 |
< |
return; |
779 |
< |
} |
780 |
< |
List<? extends ForkJoinTask<?>> ts = |
781 |
< |
(List<? extends ForkJoinTask<?>>)tasks; |
782 |
< |
Throwable ex = null; |
783 |
< |
int last = ts.size() - 1; |
784 |
< |
for (int i = last; i >= 0; --i) { |
785 |
< |
ForkJoinTask<?> t = ts.get(i); |
786 |
< |
if (t == null) { |
787 |
< |
if (ex == null) |
788 |
< |
ex = new NullPointerException(); |
789 |
< |
} |
790 |
< |
else if (i != 0) |
791 |
< |
t.fork(); |
792 |
< |
else { |
793 |
< |
t.quietlyInvoke(); |
794 |
< |
if (ex == null) |
795 |
< |
ex = t.getException(); |
796 |
< |
} |
797 |
< |
} |
798 |
< |
for (int i = 1; i <= last; ++i) { |
799 |
< |
ForkJoinTask<?> t = ts.get(i); |
800 |
< |
if (t != null) { |
801 |
< |
if (ex != null) |
802 |
< |
t.cancel(false); |
803 |
< |
else { |
804 |
< |
t.quietlyJoin(); |
805 |
< |
if (ex == null) |
806 |
< |
ex = t.getException(); |
807 |
< |
} |
808 |
< |
} |
809 |
< |
} |
810 |
< |
if (ex != null) |
811 |
< |
rethrowException(ex); |
1069 |
> |
public boolean tryUnfork() { |
1070 |
> |
return ((ForkJoinWorkerThread) Thread.currentThread()) |
1071 |
> |
.unpushTask(this); |
1072 |
|
} |
1073 |
|
|
1074 |
|
/** |
1075 |
< |
* Possibly executes tasks until the pool hosting the current task |
1076 |
< |
* {@link ForkJoinPool#isQuiescent}. This method may be of use in |
1077 |
< |
* designs in which many tasks are forked, but none are explicitly |
1078 |
< |
* joined, instead executing them until all are processed. |
1075 |
> |
* Returns an estimate of the number of tasks that have been |
1076 |
> |
* forked by the current worker thread but not yet executed. This |
1077 |
> |
* value may be useful for heuristic decisions about whether to |
1078 |
> |
* fork other tasks. |
1079 |
> |
* |
1080 |
> |
* <p>This method may be invoked only from within {@code |
1081 |
> |
* ForkJoinPool} computations (as may be determined using method |
1082 |
> |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
1083 |
> |
* result in exceptions or errors, possibly including {@code |
1084 |
> |
* ClassCastException}. |
1085 |
> |
* |
1086 |
> |
* @return the number of tasks |
1087 |
|
*/ |
1088 |
< |
public static void helpQuiesce() { |
1089 |
< |
((ForkJoinWorkerThread)(Thread.currentThread())). |
1090 |
< |
helpQuiescePool(); |
1088 |
> |
public static int getQueuedTaskCount() { |
1089 |
> |
return ((ForkJoinWorkerThread) Thread.currentThread()) |
1090 |
> |
.getQueueSize(); |
1091 |
|
} |
1092 |
|
|
1093 |
|
/** |
1094 |
< |
* Returns a estimate of how many more locally queued tasks are |
1094 |
> |
* Returns an estimate of how many more locally queued tasks are |
1095 |
|
* held by the current worker thread than there are other worker |
1096 |
< |
* threads that might want to steal them. This value may be |
1097 |
< |
* useful for heuristic decisions about whether to fork other |
1098 |
< |
* tasks. In many usages of ForkJoinTasks, at steady state, each |
1099 |
< |
* worker should aim to maintain a small constant surplus (for |
1100 |
< |
* example, 3) of tasks, and to process computations locally if |
1101 |
< |
* this threshold is exceeded. |
1096 |
> |
* threads that might steal them. This value may be useful for |
1097 |
> |
* heuristic decisions about whether to fork other tasks. In many |
1098 |
> |
* usages of ForkJoinTasks, at steady state, each worker should |
1099 |
> |
* aim to maintain a small constant surplus (for example, 3) of |
1100 |
> |
* tasks, and to process computations locally if this threshold is |
1101 |
> |
* exceeded. |
1102 |
> |
* |
1103 |
> |
* <p>This method may be invoked only from within {@code |
1104 |
> |
* ForkJoinPool} computations (as may be determined using method |
1105 |
> |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
1106 |
> |
* result in exceptions or errors, possibly including {@code |
1107 |
> |
* ClassCastException}. |
1108 |
> |
* |
1109 |
|
* @return the surplus number of tasks, which may be negative |
1110 |
|
*/ |
1111 |
< |
public static int surplus() { |
1112 |
< |
return ((ForkJoinWorkerThread)(Thread.currentThread())) |
1111 |
> |
public static int getSurplusQueuedTaskCount() { |
1112 |
> |
return ((ForkJoinWorkerThread) Thread.currentThread()) |
1113 |
|
.getEstimatedSurplusTaskCount(); |
1114 |
|
} |
1115 |
|
|
1116 |
< |
// Extension kit |
1116 |
> |
// Extension methods |
1117 |
|
|
1118 |
|
/** |
1119 |
< |
* Returns the result that would be returned by <tt>join</tt>, or |
1120 |
< |
* null if this task is not known to have been completed. This |
1121 |
< |
* method is designed to aid debugging, as well as to support |
1122 |
< |
* extensions. Its use in any other context is discouraged. |
1119 |
> |
* Returns the result that would be returned by {@link #join}, even |
1120 |
> |
* if this task completed abnormally, or {@code null} if this task |
1121 |
> |
* is not known to have been completed. This method is designed |
1122 |
> |
* to aid debugging, as well as to support extensions. Its use in |
1123 |
> |
* any other context is discouraged. |
1124 |
|
* |
1125 |
< |
* @return the result, or null if not completed. |
1125 |
> |
* @return the result, or {@code null} if not completed |
1126 |
|
*/ |
1127 |
|
public abstract V getRawResult(); |
1128 |
|
|
1141 |
|
* called otherwise. The return value controls whether this task |
1142 |
|
* is considered to be done normally. It may return false in |
1143 |
|
* asynchronous actions that require explicit invocations of |
1144 |
< |
* <tt>complete</tt> to become joinable. It may throw exceptions |
1145 |
< |
* to indicate abnormal exit. |
1146 |
< |
* @return true if completed normally |
1147 |
< |
* @throws Error or RuntimeException if encountered during computation |
1144 |
> |
* {@link #complete} to become joinable. It may also throw an |
1145 |
> |
* (unchecked) exception to indicate abnormal exit. |
1146 |
> |
* |
1147 |
> |
* @return {@code true} if completed normally |
1148 |
|
*/ |
1149 |
|
protected abstract boolean exec(); |
1150 |
|
|
1151 |
+ |
/** |
1152 |
+ |
* Returns, but does not unschedule or execute, a task queued by |
1153 |
+ |
* the current thread but not yet executed, if one is immediately |
1154 |
+ |
* available. There is no guarantee that this task will actually |
1155 |
+ |
* be polled or executed next. Conversely, this method may return |
1156 |
+ |
* null even if a task exists but cannot be accessed without |
1157 |
+ |
* contention with other threads. This method is designed |
1158 |
+ |
* primarily to support extensions, and is unlikely to be useful |
1159 |
+ |
* otherwise. |
1160 |
+ |
* |
1161 |
+ |
* <p>This method may be invoked only from within {@code |
1162 |
+ |
* ForkJoinPool} computations (as may be determined using method |
1163 |
+ |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
1164 |
+ |
* result in exceptions or errors, possibly including {@code |
1165 |
+ |
* ClassCastException}. |
1166 |
+ |
* |
1167 |
+ |
* @return the next task, or {@code null} if none are available |
1168 |
+ |
*/ |
1169 |
+ |
protected static ForkJoinTask<?> peekNextLocalTask() { |
1170 |
+ |
return ((ForkJoinWorkerThread) Thread.currentThread()) |
1171 |
+ |
.peekTask(); |
1172 |
+ |
} |
1173 |
+ |
|
1174 |
+ |
/** |
1175 |
+ |
* Unschedules and returns, without executing, the next task |
1176 |
+ |
* queued by the current thread but not yet executed. This method |
1177 |
+ |
* is designed primarily to support extensions, and is unlikely to |
1178 |
+ |
* be useful otherwise. |
1179 |
+ |
* |
1180 |
+ |
* <p>This method may be invoked only from within {@code |
1181 |
+ |
* ForkJoinPool} computations (as may be determined using method |
1182 |
+ |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
1183 |
+ |
* result in exceptions or errors, possibly including {@code |
1184 |
+ |
* ClassCastException}. |
1185 |
+ |
* |
1186 |
+ |
* @return the next task, or {@code null} if none are available |
1187 |
+ |
*/ |
1188 |
+ |
protected static ForkJoinTask<?> pollNextLocalTask() { |
1189 |
+ |
return ((ForkJoinWorkerThread) Thread.currentThread()) |
1190 |
+ |
.pollLocalTask(); |
1191 |
+ |
} |
1192 |
+ |
|
1193 |
+ |
/** |
1194 |
+ |
* Unschedules and returns, without executing, the next task |
1195 |
+ |
* queued by the current thread but not yet executed, if one is |
1196 |
+ |
* available, or if not available, a task that was forked by some |
1197 |
+ |
* other thread, if available. Availability may be transient, so a |
1198 |
+ |
* {@code null} result does not necessarily imply quiescence |
1199 |
+ |
* of the pool this task is operating in. This method is designed |
1200 |
+ |
* primarily to support extensions, and is unlikely to be useful |
1201 |
+ |
* otherwise. |
1202 |
+ |
* |
1203 |
+ |
* <p>This method may be invoked only from within {@code |
1204 |
+ |
* ForkJoinPool} computations (as may be determined using method |
1205 |
+ |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
1206 |
+ |
* result in exceptions or errors, possibly including {@code |
1207 |
+ |
* ClassCastException}. |
1208 |
+ |
* |
1209 |
+ |
* @return a task, or {@code null} if none are available |
1210 |
+ |
*/ |
1211 |
+ |
protected static ForkJoinTask<?> pollTask() { |
1212 |
+ |
return ((ForkJoinWorkerThread) Thread.currentThread()) |
1213 |
+ |
.pollTask(); |
1214 |
+ |
} |
1215 |
+ |
|
1216 |
+ |
/** |
1217 |
+ |
* Adaptor for Runnables. This implements RunnableFuture |
1218 |
+ |
* to be compliant with AbstractExecutorService constraints |
1219 |
+ |
* when used in ForkJoinPool. |
1220 |
+ |
*/ |
1221 |
+ |
static final class AdaptedRunnable<T> extends ForkJoinTask<T> |
1222 |
+ |
implements RunnableFuture<T> { |
1223 |
+ |
final Runnable runnable; |
1224 |
+ |
final T resultOnCompletion; |
1225 |
+ |
T result; |
1226 |
+ |
AdaptedRunnable(Runnable runnable, T result) { |
1227 |
+ |
if (runnable == null) throw new NullPointerException(); |
1228 |
+ |
this.runnable = runnable; |
1229 |
+ |
this.resultOnCompletion = result; |
1230 |
+ |
} |
1231 |
+ |
public T getRawResult() { return result; } |
1232 |
+ |
public void setRawResult(T v) { result = v; } |
1233 |
+ |
public boolean exec() { |
1234 |
+ |
runnable.run(); |
1235 |
+ |
result = resultOnCompletion; |
1236 |
+ |
return true; |
1237 |
+ |
} |
1238 |
+ |
public void run() { invoke(); } |
1239 |
+ |
private static final long serialVersionUID = 5232453952276885070L; |
1240 |
+ |
} |
1241 |
+ |
|
1242 |
+ |
/** |
1243 |
+ |
* Adaptor for Callables |
1244 |
+ |
*/ |
1245 |
+ |
static final class AdaptedCallable<T> extends ForkJoinTask<T> |
1246 |
+ |
implements RunnableFuture<T> { |
1247 |
+ |
final Callable<? extends T> callable; |
1248 |
+ |
T result; |
1249 |
+ |
AdaptedCallable(Callable<? extends T> callable) { |
1250 |
+ |
if (callable == null) throw new NullPointerException(); |
1251 |
+ |
this.callable = callable; |
1252 |
+ |
} |
1253 |
+ |
public T getRawResult() { return result; } |
1254 |
+ |
public void setRawResult(T v) { result = v; } |
1255 |
+ |
public boolean exec() { |
1256 |
+ |
try { |
1257 |
+ |
result = callable.call(); |
1258 |
+ |
return true; |
1259 |
+ |
} catch (Error err) { |
1260 |
+ |
throw err; |
1261 |
+ |
} catch (RuntimeException rex) { |
1262 |
+ |
throw rex; |
1263 |
+ |
} catch (Exception ex) { |
1264 |
+ |
throw new RuntimeException(ex); |
1265 |
+ |
} |
1266 |
+ |
} |
1267 |
+ |
public void run() { invoke(); } |
1268 |
+ |
private static final long serialVersionUID = 2838392045355241008L; |
1269 |
+ |
} |
1270 |
+ |
|
1271 |
+ |
/** |
1272 |
+ |
* Returns a new {@code ForkJoinTask} that performs the {@code run} |
1273 |
+ |
* method of the given {@code Runnable} as its action, and returns |
1274 |
+ |
* a null result upon {@link #join}. |
1275 |
+ |
* |
1276 |
+ |
* @param runnable the runnable action |
1277 |
+ |
* @return the task |
1278 |
+ |
*/ |
1279 |
+ |
public static ForkJoinTask<?> adapt(Runnable runnable) { |
1280 |
+ |
return new AdaptedRunnable<Void>(runnable, null); |
1281 |
+ |
} |
1282 |
+ |
|
1283 |
+ |
/** |
1284 |
+ |
* Returns a new {@code ForkJoinTask} that performs the {@code run} |
1285 |
+ |
* method of the given {@code Runnable} as its action, and returns |
1286 |
+ |
* the given result upon {@link #join}. |
1287 |
+ |
* |
1288 |
+ |
* @param runnable the runnable action |
1289 |
+ |
* @param result the result upon completion |
1290 |
+ |
* @return the task |
1291 |
+ |
*/ |
1292 |
+ |
public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) { |
1293 |
+ |
return new AdaptedRunnable<T>(runnable, result); |
1294 |
+ |
} |
1295 |
+ |
|
1296 |
+ |
/** |
1297 |
+ |
* Returns a new {@code ForkJoinTask} that performs the {@code call} |
1298 |
+ |
* method of the given {@code Callable} as its action, and returns |
1299 |
+ |
* its result upon {@link #join}, translating any checked exceptions |
1300 |
+ |
* encountered into {@code RuntimeException}. |
1301 |
+ |
* |
1302 |
+ |
* @param callable the callable action |
1303 |
+ |
* @return the task |
1304 |
+ |
*/ |
1305 |
+ |
public static <T> ForkJoinTask<T> adapt(Callable<? extends T> callable) { |
1306 |
+ |
return new AdaptedCallable<T>(callable); |
1307 |
+ |
} |
1308 |
+ |
|
1309 |
|
// Serialization support |
1310 |
|
|
1311 |
|
private static final long serialVersionUID = -7721805057305804111L; |
1312 |
|
|
1313 |
|
/** |
1314 |
< |
* Save the state to a stream. |
1314 |
> |
* Saves the state to a stream (that is, serializes it). |
1315 |
|
* |
1316 |
|
* @serialData the current run status and the exception thrown |
1317 |
< |
* during execution, or null if none. |
1317 |
> |
* during execution, or {@code null} if none |
1318 |
|
* @param s the stream |
1319 |
|
*/ |
1320 |
|
private void writeObject(java.io.ObjectOutputStream s) |
1324 |
|
} |
1325 |
|
|
1326 |
|
/** |
1327 |
< |
* Reconstitute the instance from a stream. |
1327 |
> |
* Reconstitutes the instance from a stream (that is, deserializes it). |
1328 |
> |
* |
1329 |
|
* @param s the stream |
1330 |
|
*/ |
1331 |
|
private void readObject(java.io.ObjectInputStream s) |
1332 |
|
throws java.io.IOException, ClassNotFoundException { |
1333 |
|
s.defaultReadObject(); |
899 |
– |
// status &= ~INTERNAL_SIGNAL_MASK; // todo: define policy |
1334 |
|
Object ex = s.readObject(); |
1335 |
|
if (ex != null) |
1336 |
< |
setDoneExceptionally((Throwable)ex); |
1336 |
> |
setExceptionalCompletion((Throwable)ex); |
1337 |
|
} |
1338 |
|
|
1339 |
< |
// Temporary Unsafe mechanics for preliminary release |
1340 |
< |
|
1341 |
< |
static final Unsafe _unsafe; |
908 |
< |
static final long statusOffset; |
909 |
< |
|
1339 |
> |
// Unsafe mechanics |
1340 |
> |
private static final sun.misc.Unsafe UNSAFE; |
1341 |
> |
private static final long statusOffset; |
1342 |
|
static { |
1343 |
+ |
exceptionTableLock = new ReentrantLock(); |
1344 |
+ |
exceptionTableRefQueue = new ReferenceQueue<Object>(); |
1345 |
+ |
exceptionTable = new ExceptionNode[EXCEPTION_MAP_CAPACITY]; |
1346 |
|
try { |
1347 |
< |
if (ForkJoinTask.class.getClassLoader() != null) { |
1348 |
< |
Field f = Unsafe.class.getDeclaredField("theUnsafe"); |
914 |
< |
f.setAccessible(true); |
915 |
< |
_unsafe = (Unsafe)f.get(null); |
916 |
< |
} |
917 |
< |
else |
918 |
< |
_unsafe = Unsafe.getUnsafe(); |
919 |
< |
statusOffset = _unsafe.objectFieldOffset |
1347 |
> |
UNSAFE = getUnsafe(); |
1348 |
> |
statusOffset = UNSAFE.objectFieldOffset |
1349 |
|
(ForkJoinTask.class.getDeclaredField("status")); |
1350 |
< |
} catch (Exception ex) { throw new Error(ex); } |
1350 |
> |
} catch (Exception e) { |
1351 |
> |
throw new Error(e); |
1352 |
> |
} |
1353 |
|
} |
1354 |
|
|
1355 |
+ |
/** |
1356 |
+ |
* Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package. |
1357 |
+ |
* Replace with a simple call to Unsafe.getUnsafe when integrating |
1358 |
+ |
* into a jdk. |
1359 |
+ |
* |
1360 |
+ |
* @return a sun.misc.Unsafe |
1361 |
+ |
*/ |
1362 |
+ |
private static sun.misc.Unsafe getUnsafe() { |
1363 |
+ |
try { |
1364 |
+ |
return sun.misc.Unsafe.getUnsafe(); |
1365 |
+ |
} catch (SecurityException se) { |
1366 |
+ |
try { |
1367 |
+ |
return java.security.AccessController.doPrivileged |
1368 |
+ |
(new java.security |
1369 |
+ |
.PrivilegedExceptionAction<sun.misc.Unsafe>() { |
1370 |
+ |
public sun.misc.Unsafe run() throws Exception { |
1371 |
+ |
java.lang.reflect.Field f = sun.misc |
1372 |
+ |
.Unsafe.class.getDeclaredField("theUnsafe"); |
1373 |
+ |
f.setAccessible(true); |
1374 |
+ |
return (sun.misc.Unsafe) f.get(null); |
1375 |
+ |
}}); |
1376 |
+ |
} catch (java.security.PrivilegedActionException e) { |
1377 |
+ |
throw new RuntimeException("Could not initialize intrinsics", |
1378 |
+ |
e.getCause()); |
1379 |
+ |
} |
1380 |
+ |
} |
1381 |
+ |
} |
1382 |
|
} |