5 |
|
*/ |
6 |
|
|
7 |
|
package jsr166y; |
8 |
< |
import java.io.Serializable; |
9 |
< |
import java.util.*; |
8 |
> |
|
9 |
|
import java.util.concurrent.*; |
10 |
< |
import java.util.concurrent.atomic.*; |
11 |
< |
import sun.misc.Unsafe; |
12 |
< |
import java.lang.reflect.*; |
10 |
> |
|
11 |
> |
import java.io.Serializable; |
12 |
> |
import java.util.Collection; |
13 |
> |
import java.util.Collections; |
14 |
> |
import java.util.List; |
15 |
> |
import java.util.Map; |
16 |
> |
import java.util.WeakHashMap; |
17 |
|
|
18 |
|
/** |
19 |
< |
* Abstract base class for tasks that run within a ForkJoinPool. A |
20 |
< |
* ForkJoinTask is a thread-like entity that is much lighter weight |
21 |
< |
* than a normal thread. Huge numbers of tasks and subtasks may be |
22 |
< |
* hosted by a small number of actual threads in a ForkJoinPool, |
23 |
< |
* at the price of some usage limitations. |
19 |
> |
* Abstract base class for tasks that run within a {@link |
20 |
> |
* ForkJoinPool}. A ForkJoinTask is a thread-like entity that is much |
21 |
> |
* lighter weight than a normal thread. Huge numbers of tasks and |
22 |
> |
* subtasks may be hosted by a small number of actual threads in a |
23 |
> |
* ForkJoinPool, at the price of some usage limitations. |
24 |
|
* |
25 |
< |
* <p> ForkJoinTasks are forms of <tt>Futures</tt> supporting a |
26 |
< |
* limited range of use. The "lightness" of ForkJoinTasks is due to a |
27 |
< |
* set of restrictions (that are only partially statically |
28 |
< |
* enforceable) reflecting their intended use as computational tasks |
29 |
< |
* calculating pure functions or operating on purely isolated objects. |
30 |
< |
* The primary coordination mechanisms supported for ForkJoinTasks are |
31 |
< |
* <tt>fork</tt>, that arranges asynchronous execution, and |
32 |
< |
* <tt>join</tt>, that doesn't proceed until the task's result has |
33 |
< |
* been computed. (Cancellation is also supported). The computation |
34 |
< |
* defined in the <tt>compute</tt> method should avoid |
35 |
< |
* <tt>synchronized</tt> methods or blocks, and should minimize |
36 |
< |
* blocking synchronization apart from joining other tasks or using |
25 |
> |
* <p> A "main" ForkJoinTask begins execution when submitted to a |
26 |
> |
* {@link ForkJoinPool}. Once started, it will usually in turn start |
27 |
> |
* other subtasks. As indicated by the name of this class, many |
28 |
> |
* programs using ForkJoinTasks employ only methods {@code fork} |
29 |
> |
* and {@code join}, or derivatives such as |
30 |
> |
* {@code invokeAll}. However, this class also provides a number |
31 |
> |
* of other methods that can come into play in advanced usages, as |
32 |
> |
* well as extension mechanics that allow support of new forms of |
33 |
> |
* fork/join processing. |
34 |
> |
* |
35 |
> |
* <p>A ForkJoinTask is a lightweight form of {@link Future}. The |
36 |
> |
* efficiency of ForkJoinTasks stems from a set of restrictions (that |
37 |
> |
* are only partially statically enforceable) reflecting their |
38 |
> |
* intended use as computational tasks calculating pure functions or |
39 |
> |
* operating on purely isolated objects. The primary coordination |
40 |
> |
* mechanisms are {@link #fork}, that arranges asynchronous execution, |
41 |
> |
* and {@link #join}, that doesn't proceed until the task's result has |
42 |
> |
* been computed. Computations should avoid {@code synchronized} |
43 |
> |
* methods or blocks, and should minimize other blocking |
44 |
> |
* 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 |
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 |
52 |
> |
* of threads not waiting for IO or other external synchronization |
53 |
> |
* becomes exhausted. This usage restriction is in part enforced by |
54 |
> |
* not permitting checked exceptions such as {@code IOExceptions} |
55 |
> |
* to be 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. |
61 |
> |
* <p>The primary method for awaiting completion and extracting |
62 |
> |
* results of a task is {@link #join}, but there are several variants: |
63 |
> |
* The {@link Future#get} methods support interruptible and/or timed |
64 |
> |
* waits for completion and report results using {@code Future} |
65 |
> |
* conventions. Method {@link #helpJoin} enables callers to actively |
66 |
> |
* execute other tasks while awaiting joins, which is sometimes more |
67 |
> |
* efficient but only applies when all subtasks are known to be |
68 |
> |
* strictly tree-structured. Method {@link #invoke} is semantically |
69 |
> |
* equivalent to {@code fork(); join()} but always attempts to |
70 |
> |
* begin execution in the current thread. The "<em>quiet</em>" forms |
71 |
> |
* of these methods do not extract results or report exceptions. These |
72 |
> |
* may be useful when a set of tasks are being executed, and you need |
73 |
> |
* to delay processing of results or exceptions until all complete. |
74 |
> |
* Method {@code invokeAll} (available in multiple versions) |
75 |
> |
* performs the most common form of parallel invocation: forking a set |
76 |
> |
* of tasks and joining them all. |
77 |
> |
* |
78 |
> |
* <p> The ForkJoinTask class is not usually directly subclassed. |
79 |
> |
* Instead, you subclass one of the abstract classes that support a |
80 |
> |
* particular style of fork/join processing. Normally, a concrete |
81 |
> |
* ForkJoinTask subclass declares fields comprising its parameters, |
82 |
> |
* established in a constructor, and then defines a {@code compute} |
83 |
> |
* method that somehow uses the control methods supplied by this base |
84 |
> |
* class. While these methods have {@code public} access (to allow |
85 |
> |
* instances of different task subclasses to call each others |
86 |
> |
* methods), some of them may only be called from within other |
87 |
> |
* ForkJoinTasks (as may be determined using method {@link |
88 |
> |
* #inForkJoinPool}). Attempts to invoke them in other contexts |
89 |
> |
* result in exceptions or errors, possibly including |
90 |
> |
* ClassCastException. |
91 |
|
* |
92 |
< |
* <p>Most base support methods are <tt>final</tt> because their |
92 |
> |
* <p>Most base support methods are {@code final} because their |
93 |
|
* implementations are intrinsically tied to the underlying |
94 |
|
* lightweight task scheduling framework, and so cannot be overridden. |
95 |
|
* Developers creating new basic styles of fork/join processing should |
96 |
< |
* minimally implement protected methods <tt>exec</tt>, |
97 |
< |
* <tt>setRawResult</tt>, and <tt>getRawResult</tt>, while also |
98 |
< |
* introducing an abstract computational method that can be |
99 |
< |
* implemented in its subclasses. To support such extensions, |
100 |
< |
* instances of ForkJoinTasks maintain an atomically updated |
101 |
< |
* <tt>short</tt> representing user-defined control state. Control |
74 |
< |
* state is guaranteed initially to be zero, and to be negative upon |
75 |
< |
* completion, but may otherwise be used for any other control |
76 |
< |
* purposes, such as maintaining join counts. The {@link |
77 |
< |
* ForkJoinWorkerThread} class supports additional inspection and |
78 |
< |
* tuning methods that can be useful when developing extensions. |
96 |
> |
* minimally implement {@code protected} methods |
97 |
> |
* {@code exec}, {@code setRawResult}, and |
98 |
> |
* {@code getRawResult}, while also introducing an abstract |
99 |
> |
* computational method that can be implemented in its subclasses, |
100 |
> |
* possibly relying on other {@code protected} methods provided |
101 |
> |
* by this class. |
102 |
|
* |
103 |
|
* <p>ForkJoinTasks should perform relatively small amounts of |
104 |
< |
* computations, othewise splitting into smaller tasks. As a very |
104 |
> |
* computations, otherwise splitting into smaller tasks. As a very |
105 |
|
* rough rule of thumb, a task should perform more than 100 and less |
106 |
|
* than 10000 basic computational steps. If tasks are too big, then |
107 |
< |
* parellelism cannot improve throughput. If too small, then memory |
107 |
> |
* parallelism cannot improve throughput. If too small, then memory |
108 |
|
* and internal task maintenance overhead may overwhelm processing. |
109 |
|
* |
110 |
< |
* <p>ForkJoinTasks are <tt>Serializable</tt>, which enables them to |
111 |
< |
* be used in extensions such as remote execution frameworks. However, |
112 |
< |
* it is in general safe to serialize tasks only before or after, but |
110 |
> |
* <p>ForkJoinTasks are {@code Serializable}, which enables them |
111 |
> |
* to be used in extensions such as remote execution frameworks. It is |
112 |
> |
* in general sensible to serialize tasks only before or after, but |
113 |
|
* not during execution. Serialization is not relied on during |
114 |
|
* execution itself. |
115 |
+ |
* |
116 |
+ |
* @since 1.7 |
117 |
+ |
* @author Doug Lea |
118 |
|
*/ |
119 |
|
public abstract class ForkJoinTask<V> implements Future<V>, Serializable { |
120 |
+ |
|
121 |
|
/** |
122 |
< |
* Status field holding all run status. We pack this into a single |
123 |
< |
* int both to minimize footprint overhead and to ensure atomicity |
124 |
< |
* (updates are via CAS). |
98 |
< |
* |
99 |
< |
* Status is initially zero, and takes on nonnegative values until |
122 |
> |
* Run control status bits packed into a single int to minimize |
123 |
> |
* footprint and to ensure atomicity (via CAS). Status is |
124 |
> |
* initially zero, and takes on nonnegative values until |
125 |
|
* completed, upon which status holds COMPLETED. CANCELLED, or |
126 |
|
* EXCEPTIONAL, which use the top 3 bits. Tasks undergoing |
127 |
|
* blocking waits by other threads have SIGNAL_MASK bits set -- |
136 |
|
* currently unused. Also value 0x80000000 is available as spare |
137 |
|
* completion value. |
138 |
|
*/ |
139 |
< |
volatile int status; // accessed directy by pool and workers |
139 |
> |
volatile int status; // accessed directly by pool and workers |
140 |
|
|
141 |
|
static final int COMPLETION_MASK = 0xe0000000; |
142 |
|
static final int NORMAL = 0xe0000000; // == mask |
149 |
|
/** |
150 |
|
* Table of exceptions thrown by tasks, to enable reporting by |
151 |
|
* callers. Because exceptions are rare, we don't directly keep |
152 |
< |
* them with task objects, but instead us a weak ref table. Note |
152 |
> |
* them with task objects, but instead use a weak ref table. Note |
153 |
|
* that cancellation exceptions don't appear in the table, but are |
154 |
|
* instead recorded as status values. |
155 |
< |
* Todo: Use ConcurrentReferenceHashMap |
155 |
> |
* TODO: Use ConcurrentReferenceHashMap |
156 |
|
*/ |
157 |
|
static final Map<ForkJoinTask<?>, Throwable> exceptionMap = |
158 |
|
Collections.synchronizedMap |
161 |
|
// within-package utilities |
162 |
|
|
163 |
|
/** |
164 |
< |
* Get current worker thread, or null if not a worker thread |
164 |
> |
* Gets current worker thread, or null if not a worker thread. |
165 |
|
*/ |
166 |
|
static ForkJoinWorkerThread getWorker() { |
167 |
|
Thread t = Thread.currentThread(); |
168 |
< |
return ((t instanceof ForkJoinWorkerThread)? |
169 |
< |
(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); |
168 |
> |
return ((t instanceof ForkJoinWorkerThread) ? |
169 |
> |
(ForkJoinWorkerThread) t : null); |
170 |
|
} |
171 |
|
|
172 |
|
final boolean casStatus(int cmp, int val) { |
173 |
< |
return _unsafe.compareAndSwapInt(this, statusOffset, cmp, val); |
173 |
> |
return UNSAFE.compareAndSwapInt(this, statusOffset, cmp, val); |
174 |
|
} |
175 |
|
|
176 |
|
/** |
178 |
|
*/ |
179 |
|
static void rethrowException(Throwable ex) { |
180 |
|
if (ex != null) |
181 |
< |
_unsafe.throwException(ex); |
181 |
> |
UNSAFE.throwException(ex); |
182 |
|
} |
183 |
|
|
184 |
|
// Setting completion status |
185 |
|
|
186 |
|
/** |
187 |
< |
* Mark completion and wake up threads waiting to join this task. |
187 |
> |
* Marks completion and wakes up threads waiting to join this task. |
188 |
> |
* |
189 |
|
* @param completion one of NORMAL, CANCELLED, EXCEPTIONAL |
190 |
|
*/ |
191 |
|
final void setCompletion(int completion) { |
192 |
< |
ForkJoinPool pool = getWorkerPool(); |
192 |
> |
ForkJoinPool pool = getPool(); |
193 |
|
if (pool != null) { |
194 |
|
int s; // Clear signal bits while setting completion status |
195 |
< |
do;while ((s = status) >= 0 && !casStatus(s, completion)); |
195 |
> |
do {} while ((s = status) >= 0 && !casStatus(s, completion)); |
196 |
|
|
197 |
|
if ((s & SIGNAL_MASK) != 0) { |
198 |
|
if ((s &= INTERNAL_SIGNAL_MASK) != 0) |
199 |
|
pool.updateRunningCount(s); |
200 |
< |
synchronized(this) { notifyAll(); } |
200 |
> |
synchronized (this) { notifyAll(); } |
201 |
|
} |
202 |
|
} |
203 |
|
else |
210 |
|
*/ |
211 |
|
private void externallySetCompletion(int completion) { |
212 |
|
int s; |
213 |
< |
do;while ((s = status) >= 0 && |
214 |
< |
!casStatus(s, (s & SIGNAL_MASK) | completion)); |
215 |
< |
synchronized(this) { notifyAll(); } |
213 |
> |
do {} while ((s = status) >= 0 && |
214 |
> |
!casStatus(s, (s & SIGNAL_MASK) | completion)); |
215 |
> |
synchronized (this) { notifyAll(); } |
216 |
|
} |
217 |
|
|
218 |
|
/** |
219 |
< |
* Sets status to indicate normal completion |
219 |
> |
* Sets status to indicate normal completion. |
220 |
|
*/ |
221 |
|
final void setNormalCompletion() { |
222 |
|
// Try typical fast case -- single CAS, no signal, not already done. |
223 |
|
// Manually expand casStatus to improve chances of inlining it |
224 |
< |
if (!_unsafe.compareAndSwapInt(this, statusOffset, 0, NORMAL)) |
224 |
> |
if (!UNSAFE.compareAndSwapInt(this, statusOffset, 0, NORMAL)) |
225 |
|
setCompletion(NORMAL); |
226 |
|
} |
227 |
|
|
228 |
|
// internal waiting and notification |
229 |
|
|
230 |
|
/** |
231 |
< |
* Performs the actual monitor wait for awaitDone |
231 |
> |
* Performs the actual monitor wait for awaitDone. |
232 |
|
*/ |
233 |
|
private void doAwaitDone() { |
234 |
|
// Minimize lock bias and in/de-flation effects by maximizing |
235 |
|
// chances of waiting inside sync |
236 |
|
try { |
237 |
|
while (status >= 0) |
238 |
< |
synchronized(this) { if (status >= 0) wait(); } |
238 |
> |
synchronized (this) { if (status >= 0) wait(); } |
239 |
|
} catch (InterruptedException ie) { |
240 |
|
onInterruptedWait(); |
241 |
|
} |
242 |
|
} |
243 |
|
|
244 |
|
/** |
245 |
< |
* Performs the actual monitor wait for awaitDone |
245 |
> |
* Performs the actual timed monitor wait for awaitDone. |
246 |
|
*/ |
247 |
|
private void doAwaitDone(long startTime, long nanos) { |
248 |
< |
synchronized(this) { |
248 |
> |
synchronized (this) { |
249 |
|
try { |
250 |
|
while (status >= 0) { |
251 |
|
long nt = nanos - System.nanoTime() - startTime; |
252 |
|
if (nt <= 0) |
253 |
|
break; |
254 |
< |
wait(nt / 1000000, (int)(nt % 1000000)); |
254 |
> |
wait(nt / 1000000, (int) (nt % 1000000)); |
255 |
|
} |
256 |
|
} catch (InterruptedException ie) { |
257 |
|
onInterruptedWait(); |
264 |
|
/** |
265 |
|
* Sets status to indicate there is joiner, then waits for join, |
266 |
|
* surrounded with pool notifications. |
267 |
+ |
* |
268 |
|
* @return status upon exit |
269 |
|
*/ |
270 |
< |
final int awaitDone(ForkJoinWorkerThread w, boolean maintainParallelism) { |
271 |
< |
ForkJoinPool pool = w == null? null : w.pool; |
270 |
> |
private int awaitDone(ForkJoinWorkerThread w, |
271 |
> |
boolean maintainParallelism) { |
272 |
> |
ForkJoinPool pool = (w == null) ? null : w.pool; |
273 |
|
int s; |
274 |
|
while ((s = status) >= 0) { |
275 |
< |
if (casStatus(s, pool == null? s|EXTERNAL_SIGNAL : s+1)) { |
275 |
> |
if (casStatus(s, (pool == null) ? s|EXTERNAL_SIGNAL : s+1)) { |
276 |
|
if (pool == null || !pool.preJoin(this, maintainParallelism)) |
277 |
|
doAwaitDone(); |
278 |
|
if (((s = status) & INTERNAL_SIGNAL_MASK) != 0) |
285 |
|
|
286 |
|
/** |
287 |
|
* Timed version of awaitDone |
288 |
+ |
* |
289 |
|
* @return status upon exit |
290 |
|
*/ |
291 |
< |
final int awaitDone(ForkJoinWorkerThread w, long nanos) { |
292 |
< |
ForkJoinPool pool = w == null? null : w.pool; |
291 |
> |
private int awaitDone(ForkJoinWorkerThread w, long nanos) { |
292 |
> |
ForkJoinPool pool = (w == null) ? null : w.pool; |
293 |
|
int s; |
294 |
|
while ((s = status) >= 0) { |
295 |
< |
if (casStatus(s, pool == null? s|EXTERNAL_SIGNAL : s+1)) { |
295 |
> |
if (casStatus(s, (pool == null) ? s|EXTERNAL_SIGNAL : s+1)) { |
296 |
|
long startTime = System.nanoTime(); |
297 |
|
if (pool == null || !pool.preJoin(this, false)) |
298 |
|
doAwaitDone(startTime, nanos); |
309 |
|
} |
310 |
|
|
311 |
|
/** |
312 |
< |
* Notify pool that thread is unblocked. Called by signalled |
312 |
> |
* Notifies pool that thread is unblocked. Called by signalled |
313 |
|
* threads when woken by non-FJ threads (which is atypical). |
314 |
|
*/ |
315 |
|
private void adjustPoolCountsOnUnblock(ForkJoinPool pool) { |
316 |
|
int s; |
317 |
< |
do;while ((s = status) < 0 && !casStatus(s, s & COMPLETION_MASK)); |
317 |
> |
do {} while ((s = status) < 0 && !casStatus(s, s & COMPLETION_MASK)); |
318 |
|
if (pool != null && (s &= INTERNAL_SIGNAL_MASK) != 0) |
319 |
|
pool.updateRunningCount(s); |
320 |
|
} |
321 |
|
|
322 |
|
/** |
323 |
< |
* Notify pool to adjust counts on cancelled or timed out wait |
323 |
> |
* Notifies pool to adjust counts on cancelled or timed out wait. |
324 |
|
*/ |
325 |
|
private void adjustPoolCountsOnCancelledWait(ForkJoinPool pool) { |
326 |
|
if (pool != null) { |
334 |
|
} |
335 |
|
} |
336 |
|
|
337 |
+ |
/** |
338 |
+ |
* Handles interruptions during waits. |
339 |
+ |
*/ |
340 |
|
private void onInterruptedWait() { |
341 |
< |
Thread t = Thread.currentThread(); |
342 |
< |
if (t instanceof ForkJoinWorkerThread) { |
343 |
< |
ForkJoinWorkerThread w = (ForkJoinWorkerThread)t; |
344 |
< |
if (w.isTerminating()) |
345 |
< |
cancelIgnoreExceptions(); |
346 |
< |
} |
324 |
< |
else { // re-interrupt |
325 |
< |
try { |
326 |
< |
t.interrupt(); |
327 |
< |
} catch (SecurityException ignore) { |
328 |
< |
} |
329 |
< |
} |
341 |
> |
ForkJoinWorkerThread w = getWorker(); |
342 |
> |
if (w == null) |
343 |
> |
Thread.currentThread().interrupt(); // re-interrupt |
344 |
> |
else if (w.isTerminating()) |
345 |
> |
cancelIgnoringExceptions(); |
346 |
> |
// else if FJworker, ignore interrupt |
347 |
|
} |
348 |
|
|
349 |
|
// Recording and reporting exceptions |
354 |
|
} |
355 |
|
|
356 |
|
/** |
357 |
< |
* Throws the exception associated with status s; |
357 |
> |
* Throws the exception associated with status s. |
358 |
> |
* |
359 |
|
* @throws the exception |
360 |
|
*/ |
361 |
|
private void reportException(int s) { |
368 |
|
} |
369 |
|
|
370 |
|
/** |
371 |
< |
* Returns result or throws exception using j.u.c.Future conventions |
372 |
< |
* Only call when isDone known to be true. |
371 |
> |
* Returns result or throws exception using j.u.c.Future conventions. |
372 |
> |
* Only call when {@code isDone} known to be true. |
373 |
|
*/ |
374 |
|
private V reportFutureResult() |
375 |
|
throws ExecutionException, InterruptedException { |
388 |
|
|
389 |
|
/** |
390 |
|
* Returns result or throws exception using j.u.c.Future conventions |
391 |
< |
* with timeouts |
391 |
> |
* with timeouts. |
392 |
|
*/ |
393 |
|
private V reportTimedFutureResult() |
394 |
|
throws InterruptedException, ExecutionException, TimeoutException { |
409 |
|
|
410 |
|
/** |
411 |
|
* Calls exec, recording completion, and rethrowing exception if |
412 |
< |
* encountered. Caller should normally check status before calling |
412 |
> |
* encountered. Caller should normally check status before calling. |
413 |
> |
* |
414 |
|
* @return true if completed normally |
415 |
|
*/ |
416 |
|
private boolean tryExec() { |
428 |
|
|
429 |
|
/** |
430 |
|
* Main execution method used by worker threads. Invokes |
431 |
< |
* base computation unless already complete |
431 |
> |
* base computation unless already complete. |
432 |
|
*/ |
433 |
|
final void quietlyExec() { |
434 |
|
if (status >= 0) { |
435 |
|
try { |
436 |
|
if (!exec()) |
437 |
|
return; |
438 |
< |
} catch(Throwable rex) { |
438 |
> |
} catch (Throwable rex) { |
439 |
|
setDoneExceptionally(rex); |
440 |
|
return; |
441 |
|
} |
444 |
|
} |
445 |
|
|
446 |
|
/** |
447 |
< |
* Calls exec, recording but not rethrowing exception |
448 |
< |
* Caller should normally check status before calling |
447 |
> |
* Calls exec(), recording but not rethrowing exception. |
448 |
> |
* Caller should normally check status before calling. |
449 |
> |
* |
450 |
|
* @return true if completed normally |
451 |
|
*/ |
452 |
|
private boolean tryQuietlyInvoke() { |
462 |
|
} |
463 |
|
|
464 |
|
/** |
465 |
< |
* Cancel, ignoring any exceptions it throws |
465 |
> |
* Cancels, ignoring any exceptions it throws. |
466 |
|
*/ |
467 |
< |
final void cancelIgnoreExceptions() { |
467 |
> |
final void cancelIgnoringExceptions() { |
468 |
|
try { |
469 |
|
cancel(false); |
470 |
< |
} catch(Throwable ignore) { |
470 |
> |
} catch (Throwable ignore) { |
471 |
|
} |
472 |
|
} |
473 |
|
|
474 |
+ |
/** |
475 |
+ |
* Main implementation of helpJoin |
476 |
+ |
*/ |
477 |
+ |
private int busyJoin(ForkJoinWorkerThread w) { |
478 |
+ |
int s; |
479 |
+ |
ForkJoinTask<?> t; |
480 |
+ |
while ((s = status) >= 0 && (t = w.scanWhileJoining(this)) != null) |
481 |
+ |
t.quietlyExec(); |
482 |
+ |
return (s >= 0) ? awaitDone(w, false) : s; // block if no work |
483 |
+ |
} |
484 |
+ |
|
485 |
|
// public methods |
486 |
|
|
487 |
|
/** |
488 |
|
* Arranges to asynchronously execute this task. While it is not |
489 |
|
* necessarily enforced, it is a usage error to fork a task more |
490 |
|
* than once unless it has completed and been reinitialized. This |
491 |
< |
* method may be invoked only from within other ForkJoinTask |
492 |
< |
* computations. Attempts to invoke in other contexts result in |
493 |
< |
* exceptions or errors including ClassCastException. |
491 |
> |
* method may be invoked only from within ForkJoinTask |
492 |
> |
* computations (as may be determined using method {@link |
493 |
> |
* #inForkJoinPool}). Attempts to invoke in other contexts result |
494 |
> |
* in exceptions or errors, possibly including ClassCastException. |
495 |
> |
* |
496 |
> |
* @return {@code this}, to simplify usage. |
497 |
|
*/ |
498 |
< |
public final void fork() { |
499 |
< |
((ForkJoinWorkerThread)(Thread.currentThread())).pushTask(this); |
498 |
> |
public final ForkJoinTask<V> fork() { |
499 |
> |
((ForkJoinWorkerThread) Thread.currentThread()) |
500 |
> |
.pushTask(this); |
501 |
> |
return this; |
502 |
|
} |
503 |
|
|
504 |
|
/** |
505 |
|
* Returns the result of the computation when it is ready. |
506 |
< |
* This method differs from <tt>get</tt> in that abnormal |
506 |
> |
* This method differs from {@code get} in that abnormal |
507 |
|
* completion results in RuntimeExceptions or Errors, not |
508 |
|
* ExecutionExceptions. |
509 |
|
* |
516 |
|
return getRawResult(); |
517 |
|
} |
518 |
|
|
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(); |
496 |
– |
} |
497 |
– |
|
519 |
|
/** |
520 |
< |
* Possibly executes other tasks until this task is ready, then |
521 |
< |
* returns the result of the computation. This method may be more |
522 |
< |
* efficient than <tt>join</tt>, but is only applicable when there |
502 |
< |
* are no potemtial dependencies between continuation of the |
503 |
< |
* 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). |
506 |
< |
* @return the computed result |
507 |
< |
*/ |
508 |
< |
public final V helpJoin() { |
509 |
< |
ForkJoinWorkerThread w = (ForkJoinWorkerThread)(Thread.currentThread()); |
510 |
< |
if (status < 0 || !w.unpushTask(this) || !tryExec()) |
511 |
< |
reportException(w.helpJoinTask(this)); |
512 |
< |
return getRawResult(); |
513 |
< |
} |
514 |
< |
|
515 |
< |
/** |
516 |
< |
* Performs this task, awaits its completion if necessary, and |
517 |
< |
* return its result. |
520 |
> |
* Commences performing this task, awaits its completion if |
521 |
> |
* necessary, and return its result. |
522 |
> |
* |
523 |
|
* @throws Throwable (a RuntimeException, Error, or unchecked |
524 |
< |
* exception) if the underlying computation did so. |
524 |
> |
* exception) if the underlying computation did so |
525 |
|
* @return the computed result |
526 |
|
*/ |
527 |
|
public final V invoke() { |
532 |
|
} |
533 |
|
|
534 |
|
/** |
535 |
< |
* Joins this task, without returning its result or throwing an |
536 |
< |
* exception. This method may be useful when processing |
537 |
< |
* collections of tasks when some have been cancelled or otherwise |
538 |
< |
* known to have aborted. |
535 |
> |
* Forks both tasks, returning when {@code isDone} holds for |
536 |
> |
* both of them or an exception is encountered. This method may be |
537 |
> |
* invoked only from within ForkJoinTask computations (as may be |
538 |
> |
* determined using method {@link #inForkJoinPool}). Attempts to |
539 |
> |
* invoke in other contexts result in exceptions or errors, |
540 |
> |
* possibly including ClassCastException. |
541 |
> |
* |
542 |
> |
* @param t1 one task |
543 |
> |
* @param t2 the other task |
544 |
> |
* @throws NullPointerException if t1 or t2 are null |
545 |
> |
* @throws RuntimeException or Error if either task did so |
546 |
|
*/ |
547 |
< |
public final void quietlyJoin() { |
548 |
< |
if (status >= 0) { |
549 |
< |
ForkJoinWorkerThread w = getWorker(); |
550 |
< |
if (w == null || !w.unpushTask(this) || !tryQuietlyInvoke()) |
539 |
< |
awaitDone(w, true); |
540 |
< |
} |
547 |
> |
public static void invokeAll(ForkJoinTask<?>t1, ForkJoinTask<?> t2) { |
548 |
> |
t2.fork(); |
549 |
> |
t1.invoke(); |
550 |
> |
t2.join(); |
551 |
|
} |
552 |
|
|
553 |
|
/** |
554 |
< |
* Possibly executes other tasks until this task is ready. |
554 |
> |
* Forks the given tasks, returning when {@code isDone} holds |
555 |
> |
* for all of them. If any task encounters an exception, others |
556 |
> |
* may be cancelled. This method may be invoked only from within |
557 |
> |
* ForkJoinTask computations (as may be determined using method |
558 |
> |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
559 |
> |
* result in exceptions or errors, possibly including |
560 |
> |
* ClassCastException. |
561 |
> |
* |
562 |
> |
* @param tasks the array of tasks |
563 |
> |
* @throws NullPointerException if tasks or any element are null |
564 |
> |
* @throws RuntimeException or Error if any task did so |
565 |
|
*/ |
566 |
< |
public final void quietlyHelpJoin() { |
567 |
< |
if (status >= 0) { |
568 |
< |
ForkJoinWorkerThread w = |
569 |
< |
(ForkJoinWorkerThread)(Thread.currentThread()); |
570 |
< |
if (!w.unpushTask(this) || !tryQuietlyInvoke()) |
571 |
< |
w.helpJoinTask(this); |
566 |
> |
public static void invokeAll(ForkJoinTask<?>... tasks) { |
567 |
> |
Throwable ex = null; |
568 |
> |
int last = tasks.length - 1; |
569 |
> |
for (int i = last; i >= 0; --i) { |
570 |
> |
ForkJoinTask<?> t = tasks[i]; |
571 |
> |
if (t == null) { |
572 |
> |
if (ex == null) |
573 |
> |
ex = new NullPointerException(); |
574 |
> |
} |
575 |
> |
else if (i != 0) |
576 |
> |
t.fork(); |
577 |
> |
else { |
578 |
> |
t.quietlyInvoke(); |
579 |
> |
if (ex == null) |
580 |
> |
ex = t.getException(); |
581 |
> |
} |
582 |
|
} |
583 |
+ |
for (int i = 1; i <= last; ++i) { |
584 |
+ |
ForkJoinTask<?> t = tasks[i]; |
585 |
+ |
if (t != null) { |
586 |
+ |
if (ex != null) |
587 |
+ |
t.cancel(false); |
588 |
+ |
else { |
589 |
+ |
t.quietlyJoin(); |
590 |
+ |
if (ex == null) |
591 |
+ |
ex = t.getException(); |
592 |
+ |
} |
593 |
+ |
} |
594 |
+ |
} |
595 |
+ |
if (ex != null) |
596 |
+ |
rethrowException(ex); |
597 |
|
} |
598 |
|
|
599 |
|
/** |
600 |
< |
* Performs this task and awaits its completion if necessary, |
601 |
< |
* without returning its result or throwing an exception. This |
602 |
< |
* method may be useful when processing collections of tasks when |
603 |
< |
* some have been cancelled or otherwise known to have aborted. |
604 |
< |
*/ |
605 |
< |
public final void quietlyInvoke() { |
606 |
< |
if (status >= 0 && !tryQuietlyInvoke()) |
607 |
< |
quietlyJoin(); |
600 |
> |
* Forks all tasks in the collection, returning when |
601 |
> |
* {@code isDone} holds for all of them. If any task |
602 |
> |
* encounters an exception, others may be cancelled. This method |
603 |
> |
* may be invoked only from within ForkJoinTask computations (as |
604 |
> |
* may be determined using method {@link |
605 |
> |
* #inForkJoinPool}). Attempts to invoke in other contexts result |
606 |
> |
* in exceptions or errors, possibly including ClassCastException. |
607 |
> |
* |
608 |
> |
* @param tasks the collection of tasks |
609 |
> |
* @return the tasks argument, to simplify usage |
610 |
> |
* @throws NullPointerException if tasks or any element are null |
611 |
> |
* @throws RuntimeException or Error if any task did so |
612 |
> |
*/ |
613 |
> |
public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) { |
614 |
> |
if (!(tasks instanceof List<?>)) { |
615 |
> |
invokeAll(tasks.toArray(new ForkJoinTask<?>[tasks.size()])); |
616 |
> |
return tasks; |
617 |
> |
} |
618 |
> |
@SuppressWarnings("unchecked") |
619 |
> |
List<? extends ForkJoinTask<?>> ts = |
620 |
> |
(List<? extends ForkJoinTask<?>>) tasks; |
621 |
> |
Throwable ex = null; |
622 |
> |
int last = ts.size() - 1; |
623 |
> |
for (int i = last; i >= 0; --i) { |
624 |
> |
ForkJoinTask<?> t = ts.get(i); |
625 |
> |
if (t == null) { |
626 |
> |
if (ex == null) |
627 |
> |
ex = new NullPointerException(); |
628 |
> |
} |
629 |
> |
else if (i != 0) |
630 |
> |
t.fork(); |
631 |
> |
else { |
632 |
> |
t.quietlyInvoke(); |
633 |
> |
if (ex == null) |
634 |
> |
ex = t.getException(); |
635 |
> |
} |
636 |
> |
} |
637 |
> |
for (int i = 1; i <= last; ++i) { |
638 |
> |
ForkJoinTask<?> t = ts.get(i); |
639 |
> |
if (t != null) { |
640 |
> |
if (ex != null) |
641 |
> |
t.cancel(false); |
642 |
> |
else { |
643 |
> |
t.quietlyJoin(); |
644 |
> |
if (ex == null) |
645 |
> |
ex = t.getException(); |
646 |
> |
} |
647 |
> |
} |
648 |
> |
} |
649 |
> |
if (ex != null) |
650 |
> |
rethrowException(ex); |
651 |
> |
return tasks; |
652 |
|
} |
653 |
|
|
654 |
|
/** |
655 |
|
* Returns true if the computation performed by this task has |
656 |
|
* completed (or has been cancelled). |
657 |
+ |
* |
658 |
|
* @return true if this computation has completed |
659 |
|
*/ |
660 |
|
public final boolean isDone() { |
663 |
|
|
664 |
|
/** |
665 |
|
* Returns true if this task was cancelled. |
666 |
+ |
* |
667 |
|
* @return true if this task was cancelled |
668 |
|
*/ |
669 |
|
public final boolean isCancelled() { |
671 |
|
} |
672 |
|
|
673 |
|
/** |
584 |
– |
* Returns true if this task threw an exception or was cancelled |
585 |
– |
* @return true if this task threw an exception or was cancelled |
586 |
– |
*/ |
587 |
– |
public final boolean completedAbnormally() { |
588 |
– |
return (status & COMPLETION_MASK) < NORMAL; |
589 |
– |
} |
590 |
– |
|
591 |
– |
/** |
592 |
– |
* Returns the exception thrown by the base computation, or a |
593 |
– |
* CancellationException if cancelled, or null if none or if the |
594 |
– |
* method has not yet completed. |
595 |
– |
* @return the exception, or null if none |
596 |
– |
*/ |
597 |
– |
public final Throwable getException() { |
598 |
– |
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); |
604 |
– |
} |
605 |
– |
|
606 |
– |
/** |
674 |
|
* Asserts that the results of this task's computation will not be |
675 |
< |
* used. If a cancellation occurs before this task is processed, |
676 |
< |
* then its <tt>compute</tt> method will not be executed, |
677 |
< |
* <tt>isCancelled</tt> will report true, and <tt>join</tt> will |
678 |
< |
* result in a CancellationException being thrown. Otherwise, when |
675 |
> |
* used. If a cancellation occurs before attempting to execute this |
676 |
> |
* task, then execution will be suppressed, {@code isCancelled} |
677 |
> |
* will report true, and {@code join} will result in a |
678 |
> |
* {@code CancellationException} being thrown. Otherwise, when |
679 |
|
* cancellation races with completion, there are no guarantees |
680 |
< |
* about whether <tt>isCancelled</tt> will report true, whether |
681 |
< |
* <tt>join</tt> will return normally or via an exception, or |
680 |
> |
* about whether {@code isCancelled} will report true, whether |
681 |
> |
* {@code join} will return normally or via an exception, or |
682 |
|
* whether these behaviors will remain consistent upon repeated |
683 |
|
* invocation. |
684 |
|
* |
689 |
|
* <p> This method is designed to be invoked by <em>other</em> |
690 |
|
* tasks. To terminate the current task, you can just return or |
691 |
|
* throw an unchecked exception from its computation method, or |
692 |
< |
* invoke <tt>completeExceptionally(someException)</tt>. |
692 |
> |
* invoke {@code completeExceptionally}. |
693 |
|
* |
694 |
|
* @param mayInterruptIfRunning this value is ignored in the |
695 |
|
* default implementation because tasks are not in general |
696 |
< |
* cancelled via interruption. |
696 |
> |
* cancelled via interruption |
697 |
|
* |
698 |
|
* @return true if this task is now cancelled |
699 |
|
*/ |
703 |
|
} |
704 |
|
|
705 |
|
/** |
706 |
+ |
* Returns true if this task threw an exception or was cancelled. |
707 |
+ |
* |
708 |
+ |
* @return true if this task threw an exception or was cancelled |
709 |
+ |
*/ |
710 |
+ |
public final boolean isCompletedAbnormally() { |
711 |
+ |
return (status & COMPLETION_MASK) < NORMAL; |
712 |
+ |
} |
713 |
+ |
|
714 |
+ |
/** |
715 |
+ |
* Returns the exception thrown by the base computation, or a |
716 |
+ |
* CancellationException if cancelled, or null if none or if the |
717 |
+ |
* method has not yet completed. |
718 |
+ |
* |
719 |
+ |
* @return the exception, or null if none |
720 |
+ |
*/ |
721 |
+ |
public final Throwable getException() { |
722 |
+ |
int s = status & COMPLETION_MASK; |
723 |
+ |
if (s >= NORMAL) |
724 |
+ |
return null; |
725 |
+ |
if (s == CANCELLED) |
726 |
+ |
return new CancellationException(); |
727 |
+ |
return exceptionMap.get(this); |
728 |
+ |
} |
729 |
+ |
|
730 |
+ |
/** |
731 |
|
* Completes this task abnormally, and if not already aborted or |
732 |
|
* cancelled, causes it to throw the given exception upon |
733 |
< |
* <tt>join</tt> and related operations. This method may be used |
733 |
> |
* {@code join} and related operations. This method may be used |
734 |
|
* to induce exceptions in asynchronous tasks, or to force |
735 |
< |
* completion of tasks that would not otherwise complete. This |
736 |
< |
* method is overridable, but overridden versions must invoke |
737 |
< |
* <tt>super</tt> implementation to maintain guarantees. |
735 |
> |
* completion of tasks that would not otherwise complete. Its use |
736 |
> |
* in other situations is likely to be wrong. This method is |
737 |
> |
* overridable, but overridden versions must invoke {@code super} |
738 |
> |
* implementation to maintain guarantees. |
739 |
> |
* |
740 |
|
* @param ex the exception to throw. If this exception is |
741 |
|
* not a RuntimeException or Error, the actual exception thrown |
742 |
|
* will be a RuntimeException with cause ex. |
743 |
|
*/ |
744 |
|
public void completeExceptionally(Throwable ex) { |
745 |
|
setDoneExceptionally((ex instanceof RuntimeException) || |
746 |
< |
(ex instanceof Error)? ex : |
746 |
> |
(ex instanceof Error) ? ex : |
747 |
|
new RuntimeException(ex)); |
748 |
|
} |
749 |
|
|
750 |
|
/** |
751 |
|
* Completes this task, and if not already aborted or cancelled, |
752 |
< |
* returning a <tt>null</tt> result upon <tt>join</tt> and related |
752 |
> |
* returning a {@code null} result upon {@code join} and related |
753 |
|
* operations. This method may be used to provide results for |
754 |
|
* asynchronous tasks, or to provide alternative handling for |
755 |
< |
* tasks that would not otherwise complete normally. |
755 |
> |
* tasks that would not otherwise complete normally. Its use in |
756 |
> |
* other situations is likely to be wrong. This method is |
757 |
> |
* overridable, but overridden versions must invoke {@code super} |
758 |
> |
* implementation to maintain guarantees. |
759 |
|
* |
760 |
< |
* @param value the result value for this task. |
760 |
> |
* @param value the result value for this task |
761 |
|
*/ |
762 |
|
public void complete(V value) { |
763 |
|
try { |
764 |
|
setRawResult(value); |
765 |
< |
} catch(Throwable rex) { |
765 |
> |
} catch (Throwable rex) { |
766 |
|
setDoneExceptionally(rex); |
767 |
|
return; |
768 |
|
} |
769 |
|
setNormalCompletion(); |
770 |
|
} |
771 |
|
|
772 |
+ |
public final V get() throws InterruptedException, ExecutionException { |
773 |
+ |
ForkJoinWorkerThread w = getWorker(); |
774 |
+ |
if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke()) |
775 |
+ |
awaitDone(w, true); |
776 |
+ |
return reportFutureResult(); |
777 |
+ |
} |
778 |
+ |
|
779 |
+ |
public final V get(long timeout, TimeUnit unit) |
780 |
+ |
throws InterruptedException, ExecutionException, TimeoutException { |
781 |
+ |
ForkJoinWorkerThread w = getWorker(); |
782 |
+ |
if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke()) |
783 |
+ |
awaitDone(w, unit.toNanos(timeout)); |
784 |
+ |
return reportTimedFutureResult(); |
785 |
+ |
} |
786 |
+ |
|
787 |
+ |
/** |
788 |
+ |
* Possibly executes other tasks until this task is ready, then |
789 |
+ |
* returns the result of the computation. This method may be more |
790 |
+ |
* efficient than {@code join}, but is only applicable when |
791 |
+ |
* there are no potential dependencies between continuation of the |
792 |
+ |
* current task and that of any other task that might be executed |
793 |
+ |
* while helping. (This usually holds for pure divide-and-conquer |
794 |
+ |
* tasks). This method may be invoked only from within |
795 |
+ |
* ForkJoinTask computations (as may be determined using method |
796 |
+ |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
797 |
+ |
* result in exceptions or errors, possibly including |
798 |
+ |
* ClassCastException. |
799 |
+ |
* |
800 |
+ |
* @return the computed result |
801 |
+ |
*/ |
802 |
+ |
public final V helpJoin() { |
803 |
+ |
ForkJoinWorkerThread w = (ForkJoinWorkerThread) Thread.currentThread(); |
804 |
+ |
if (status < 0 || !w.unpushTask(this) || !tryExec()) |
805 |
+ |
reportException(busyJoin(w)); |
806 |
+ |
return getRawResult(); |
807 |
+ |
} |
808 |
+ |
|
809 |
+ |
/** |
810 |
+ |
* Possibly executes other tasks until this task is ready. This |
811 |
+ |
* method may be invoked only from within ForkJoinTask |
812 |
+ |
* computations (as may be determined using method {@link |
813 |
+ |
* #inForkJoinPool}). Attempts to invoke in other contexts result |
814 |
+ |
* in exceptions or errors, possibly including ClassCastException. |
815 |
+ |
*/ |
816 |
+ |
public final void quietlyHelpJoin() { |
817 |
+ |
if (status >= 0) { |
818 |
+ |
ForkJoinWorkerThread w = |
819 |
+ |
(ForkJoinWorkerThread) Thread.currentThread(); |
820 |
+ |
if (!w.unpushTask(this) || !tryQuietlyInvoke()) |
821 |
+ |
busyJoin(w); |
822 |
+ |
} |
823 |
+ |
} |
824 |
+ |
|
825 |
+ |
/** |
826 |
+ |
* Joins this task, without returning its result or throwing an |
827 |
+ |
* exception. This method may be useful when processing |
828 |
+ |
* collections of tasks when some have been cancelled or otherwise |
829 |
+ |
* known to have aborted. |
830 |
+ |
*/ |
831 |
+ |
public final void quietlyJoin() { |
832 |
+ |
if (status >= 0) { |
833 |
+ |
ForkJoinWorkerThread w = getWorker(); |
834 |
+ |
if (w == null || !w.unpushTask(this) || !tryQuietlyInvoke()) |
835 |
+ |
awaitDone(w, true); |
836 |
+ |
} |
837 |
+ |
} |
838 |
+ |
|
839 |
+ |
/** |
840 |
+ |
* Commences performing this task and awaits its completion if |
841 |
+ |
* necessary, without returning its result or throwing an |
842 |
+ |
* exception. This method may be useful when processing |
843 |
+ |
* collections of tasks when some have been cancelled or otherwise |
844 |
+ |
* known to have aborted. |
845 |
+ |
*/ |
846 |
+ |
public final void quietlyInvoke() { |
847 |
+ |
if (status >= 0 && !tryQuietlyInvoke()) |
848 |
+ |
quietlyJoin(); |
849 |
+ |
} |
850 |
+ |
|
851 |
+ |
/** |
852 |
+ |
* Possibly executes tasks until the pool hosting the current task |
853 |
+ |
* {@link ForkJoinPool#isQuiescent}. This method may be of use in |
854 |
+ |
* designs in which many tasks are forked, but none are explicitly |
855 |
+ |
* joined, instead executing them until all are processed. |
856 |
+ |
*/ |
857 |
+ |
public static void helpQuiesce() { |
858 |
+ |
((ForkJoinWorkerThread) Thread.currentThread()) |
859 |
+ |
.helpQuiescePool(); |
860 |
+ |
} |
861 |
+ |
|
862 |
|
/** |
863 |
|
* Resets the internal bookkeeping state of this task, allowing a |
864 |
< |
* subsequent <tt>fork</tt>. This method allows repeated reuse of |
864 |
> |
* subsequent {@code fork}. This method allows repeated reuse of |
865 |
|
* this task, but only if reuse occurs when this task has either |
866 |
|
* never been forked, or has been forked, then completed and all |
867 |
|
* outstanding joins of this task have also completed. Effects |
876 |
|
} |
877 |
|
|
878 |
|
/** |
879 |
< |
* Tries to unschedule this task for execution. This method will |
880 |
< |
* typically succeed if this task is the next task that would be |
881 |
< |
* executed by the current thread, and will typically fail (return |
882 |
< |
* 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); |
702 |
< |
} |
703 |
< |
|
704 |
< |
/** |
705 |
< |
* Forks both tasks, returning when <tt>isDone</tt> holds for both |
706 |
< |
* of them or an exception is encountered. This method may be |
707 |
< |
* invoked only from within other ForkJoinTask |
708 |
< |
* computations. Attempts to invoke in other contexts result in |
709 |
< |
* 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. |
879 |
> |
* Returns the pool hosting the current task execution, or null |
880 |
> |
* if this task is executing outside of any ForkJoinPool. |
881 |
> |
* |
882 |
> |
* @return the pool, or null if none |
883 |
|
*/ |
884 |
< |
public static void invokeAll(ForkJoinTask<?>t1, ForkJoinTask<?> t2) { |
885 |
< |
t2.fork(); |
886 |
< |
t1.invoke(); |
887 |
< |
t2.join(); |
884 |
> |
public static ForkJoinPool getPool() { |
885 |
> |
Thread t = Thread.currentThread(); |
886 |
> |
return (t instanceof ForkJoinWorkerThread) ? |
887 |
> |
((ForkJoinWorkerThread) t).pool : null; |
888 |
|
} |
889 |
|
|
890 |
|
/** |
891 |
< |
* Forks the given tasks, returning when <tt>isDone</tt> holds for |
892 |
< |
* all of them. If any task encounters an exception, others may be |
893 |
< |
* cancelled. This method may be invoked only from within other |
894 |
< |
* ForkJoinTask computations. Attempts to invoke in other contexts |
895 |
< |
* result in exceptions or errors including ClassCastException. |
727 |
< |
* @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. |
891 |
> |
* Returns {@code true} if the current thread is executing as a |
892 |
> |
* ForkJoinPool computation. |
893 |
> |
* |
894 |
> |
* @return {@code true} if the current thread is executing as a |
895 |
> |
* ForkJoinPool computation, or false otherwise |
896 |
|
*/ |
897 |
< |
public static void invokeAll(ForkJoinTask<?>... tasks) { |
898 |
< |
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); |
897 |
> |
public static boolean inForkJoinPool() { |
898 |
> |
return Thread.currentThread() instanceof ForkJoinWorkerThread; |
899 |
|
} |
900 |
|
|
901 |
|
/** |
902 |
< |
* Forks all tasks in the collection, returning when |
903 |
< |
* <tt>isDone</tt> holds for all of them. If any task encounters |
904 |
< |
* an exception, others may be cancelled. This method may be |
905 |
< |
* invoked only from within other ForkJoinTask |
906 |
< |
* computations. Attempts to invoke in other contexts result in |
907 |
< |
* exceptions or errors including ClassCastException. |
908 |
< |
* @param tasks the collection of tasks |
909 |
< |
* @throws NullPointerException if tasks or any element are null. |
910 |
< |
* @throws RuntimeException or Error if any task did so. |
902 |
> |
* Tries to unschedule this task for execution. This method will |
903 |
> |
* typically succeed if this task is the most recently forked task |
904 |
> |
* by the current thread, and has not commenced executing in |
905 |
> |
* another thread. This method may be useful when arranging |
906 |
> |
* alternative local processing of tasks that could have been, but |
907 |
> |
* were not, stolen. This method may be invoked only from within |
908 |
> |
* ForkJoinTask computations (as may be determined using method |
909 |
> |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
910 |
> |
* result in exceptions or errors, possibly including |
911 |
> |
* ClassCastException. |
912 |
> |
* |
913 |
> |
* @return true if unforked |
914 |
|
*/ |
915 |
< |
public static void invokeAll(Collection<? extends ForkJoinTask<?>> tasks) { |
916 |
< |
if (!(tasks instanceof List)) { |
917 |
< |
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); |
915 |
> |
public boolean tryUnfork() { |
916 |
> |
return ((ForkJoinWorkerThread) Thread.currentThread()) |
917 |
> |
.unpushTask(this); |
918 |
|
} |
919 |
|
|
920 |
|
/** |
921 |
< |
* Possibly executes tasks until the pool hosting the current task |
922 |
< |
* {@link ForkJoinPool#isQuiescent}. This method may be of use in |
923 |
< |
* designs in which many tasks are forked, but none are explicitly |
924 |
< |
* joined, instead executing them until all are processed. |
921 |
> |
* Returns an estimate of the number of tasks that have been |
922 |
> |
* forked by the current worker thread but not yet executed. This |
923 |
> |
* value may be useful for heuristic decisions about whether to |
924 |
> |
* fork other tasks. |
925 |
> |
* |
926 |
> |
* @return the number of tasks |
927 |
|
*/ |
928 |
< |
public static void helpQuiesce() { |
929 |
< |
((ForkJoinWorkerThread)(Thread.currentThread())). |
930 |
< |
helpQuiescePool(); |
928 |
> |
public static int getQueuedTaskCount() { |
929 |
> |
return ((ForkJoinWorkerThread) Thread.currentThread()) |
930 |
> |
.getQueueSize(); |
931 |
|
} |
932 |
|
|
933 |
|
/** |
934 |
< |
* Returns a estimate of how many more locally queued tasks are |
934 |
> |
* Returns an estimate of how many more locally queued tasks are |
935 |
|
* held by the current worker thread than there are other worker |
936 |
< |
* threads that might want to steal them. This value may be |
937 |
< |
* useful for heuristic decisions about whether to fork other |
938 |
< |
* tasks. In many usages of ForkJoinTasks, at steady state, each |
939 |
< |
* worker should aim to maintain a small constant surplus (for |
940 |
< |
* example, 3) of tasks, and to process computations locally if |
941 |
< |
* this threshold is exceeded. |
936 |
> |
* threads that might steal them. This value may be useful for |
937 |
> |
* heuristic decisions about whether to fork other tasks. In many |
938 |
> |
* usages of ForkJoinTasks, at steady state, each worker should |
939 |
> |
* aim to maintain a small constant surplus (for example, 3) of |
940 |
> |
* tasks, and to process computations locally if this threshold is |
941 |
> |
* exceeded. |
942 |
> |
* |
943 |
|
* @return the surplus number of tasks, which may be negative |
944 |
|
*/ |
945 |
< |
public static int surplus() { |
946 |
< |
return ((ForkJoinWorkerThread)(Thread.currentThread())) |
945 |
> |
public static int getSurplusQueuedTaskCount() { |
946 |
> |
return ((ForkJoinWorkerThread) Thread.currentThread()) |
947 |
|
.getEstimatedSurplusTaskCount(); |
948 |
|
} |
949 |
|
|
950 |
< |
// Extension kit |
950 |
> |
// Extension methods |
951 |
|
|
952 |
|
/** |
953 |
< |
* Returns the result that would be returned by <tt>join</tt>, or |
954 |
< |
* null if this task is not known to have been completed. This |
955 |
< |
* method is designed to aid debugging, as well as to support |
956 |
< |
* extensions. Its use in any other context is discouraged. |
953 |
> |
* Returns the result that would be returned by {@code join}, |
954 |
> |
* even if this task completed abnormally, or null if this task is |
955 |
> |
* not known to have been completed. This method is designed to |
956 |
> |
* aid debugging, as well as to support extensions. Its use in any |
957 |
> |
* other context is discouraged. |
958 |
|
* |
959 |
< |
* @return the result, or null if not completed. |
959 |
> |
* @return the result, or null if not completed |
960 |
|
*/ |
961 |
|
public abstract V getRawResult(); |
962 |
|
|
975 |
|
* called otherwise. The return value controls whether this task |
976 |
|
* is considered to be done normally. It may return false in |
977 |
|
* asynchronous actions that require explicit invocations of |
978 |
< |
* <tt>complete</tt> to become joinable. It may throw exceptions |
978 |
> |
* {@code complete} to become joinable. It may throw exceptions |
979 |
|
* to indicate abnormal exit. |
980 |
+ |
* |
981 |
|
* @return true if completed normally |
982 |
|
* @throws Error or RuntimeException if encountered during computation |
983 |
|
*/ |
984 |
|
protected abstract boolean exec(); |
985 |
|
|
986 |
+ |
/** |
987 |
+ |
* Returns, but does not unschedule or execute, the task queued by |
988 |
+ |
* the current thread but not yet executed, if one is |
989 |
+ |
* available. There is no guarantee that this task will actually |
990 |
+ |
* be polled or executed next. This method is designed primarily |
991 |
+ |
* to support extensions, and is unlikely to be useful otherwise. |
992 |
+ |
* This method may be invoked only from within ForkJoinTask |
993 |
+ |
* computations (as may be determined using method {@link |
994 |
+ |
* #inForkJoinPool}). Attempts to invoke in other contexts result |
995 |
+ |
* in exceptions or errors, possibly including ClassCastException. |
996 |
+ |
* |
997 |
+ |
* @return the next task, or null if none are available |
998 |
+ |
*/ |
999 |
+ |
protected static ForkJoinTask<?> peekNextLocalTask() { |
1000 |
+ |
return ((ForkJoinWorkerThread) Thread.currentThread()) |
1001 |
+ |
.peekTask(); |
1002 |
+ |
} |
1003 |
+ |
|
1004 |
+ |
/** |
1005 |
+ |
* Unschedules and returns, without executing, the next task |
1006 |
+ |
* queued by the current thread but not yet executed. This method |
1007 |
+ |
* is designed primarily to support extensions, and is unlikely to |
1008 |
+ |
* be useful otherwise. This method may be invoked only from |
1009 |
+ |
* within ForkJoinTask computations (as may be determined using |
1010 |
+ |
* method {@link #inForkJoinPool}). Attempts to invoke in other |
1011 |
+ |
* contexts result in exceptions or errors, possibly including |
1012 |
+ |
* ClassCastException. |
1013 |
+ |
* |
1014 |
+ |
* @return the next task, or null if none are available |
1015 |
+ |
*/ |
1016 |
+ |
protected static ForkJoinTask<?> pollNextLocalTask() { |
1017 |
+ |
return ((ForkJoinWorkerThread) Thread.currentThread()) |
1018 |
+ |
.pollLocalTask(); |
1019 |
+ |
} |
1020 |
+ |
|
1021 |
+ |
/** |
1022 |
+ |
* Unschedules and returns, without executing, the next task |
1023 |
+ |
* queued by the current thread but not yet executed, if one is |
1024 |
+ |
* available, or if not available, a task that was forked by some |
1025 |
+ |
* other thread, if available. Availability may be transient, so a |
1026 |
+ |
* {@code null} result does not necessarily imply quiescence |
1027 |
+ |
* of the pool this task is operating in. This method is designed |
1028 |
+ |
* primarily to support extensions, and is unlikely to be useful |
1029 |
+ |
* otherwise. This method may be invoked only from within |
1030 |
+ |
* ForkJoinTask computations (as may be determined using method |
1031 |
+ |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
1032 |
+ |
* result in exceptions or errors, possibly including |
1033 |
+ |
* ClassCastException. |
1034 |
+ |
* |
1035 |
+ |
* @return a task, or null if none are available |
1036 |
+ |
*/ |
1037 |
+ |
protected static ForkJoinTask<?> pollTask() { |
1038 |
+ |
return ((ForkJoinWorkerThread) Thread.currentThread()) |
1039 |
+ |
.pollTask(); |
1040 |
+ |
} |
1041 |
+ |
|
1042 |
+ |
// adaptors |
1043 |
+ |
|
1044 |
+ |
/** |
1045 |
+ |
* Returns a new ForkJoinTask that performs the {@code run} |
1046 |
+ |
* method of the given Runnable as its action, and returns a null |
1047 |
+ |
* result upon {@code join}. |
1048 |
+ |
* |
1049 |
+ |
* @param runnable the runnable action |
1050 |
+ |
* @return the task |
1051 |
+ |
*/ |
1052 |
+ |
public static ForkJoinTask<Void> adapt(Runnable runnable) { |
1053 |
+ |
return new ForkJoinPool.AdaptedRunnable<Void>(runnable, null); |
1054 |
+ |
} |
1055 |
+ |
|
1056 |
+ |
/** |
1057 |
+ |
* Returns a new ForkJoinTask that performs the {@code run} |
1058 |
+ |
* method of the given Runnable as its action, and returns the |
1059 |
+ |
* given result upon {@code join}. |
1060 |
+ |
* |
1061 |
+ |
* @param runnable the runnable action |
1062 |
+ |
* @param result the result upon completion |
1063 |
+ |
* @return the task |
1064 |
+ |
*/ |
1065 |
+ |
public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) { |
1066 |
+ |
return new ForkJoinPool.AdaptedRunnable<T>(runnable, result); |
1067 |
+ |
} |
1068 |
+ |
|
1069 |
+ |
/** |
1070 |
+ |
* Returns a new ForkJoinTask that performs the {@code call} |
1071 |
+ |
* method of the given Callable as its action, and returns its |
1072 |
+ |
* result upon {@code join}, translating any checked |
1073 |
+ |
* exceptions encountered into {@code RuntimeException}. |
1074 |
+ |
* |
1075 |
+ |
* @param callable the callable action |
1076 |
+ |
* @return the task |
1077 |
+ |
*/ |
1078 |
+ |
public static <T> ForkJoinTask<T> adapt(Callable<T> callable) { |
1079 |
+ |
return new ForkJoinPool.AdaptedCallable<T>(callable); |
1080 |
+ |
} |
1081 |
+ |
|
1082 |
|
// Serialization support |
1083 |
|
|
1084 |
|
private static final long serialVersionUID = -7721805057305804111L; |
1087 |
|
* Save the state to a stream. |
1088 |
|
* |
1089 |
|
* @serialData the current run status and the exception thrown |
1090 |
< |
* during execution, or null if none. |
1090 |
> |
* during execution, or null if none |
1091 |
|
* @param s the stream |
1092 |
|
*/ |
1093 |
|
private void writeObject(java.io.ObjectOutputStream s) |
1098 |
|
|
1099 |
|
/** |
1100 |
|
* Reconstitute the instance from a stream. |
1101 |
+ |
* |
1102 |
|
* @param s the stream |
1103 |
|
*/ |
1104 |
|
private void readObject(java.io.ObjectInputStream s) |
1105 |
|
throws java.io.IOException, ClassNotFoundException { |
1106 |
|
s.defaultReadObject(); |
1107 |
< |
// status &= ~INTERNAL_SIGNAL_MASK; // todo: define policy |
1107 |
> |
status &= ~INTERNAL_SIGNAL_MASK; // clear internal signal counts |
1108 |
> |
status |= EXTERNAL_SIGNAL; // conservatively set external signal |
1109 |
|
Object ex = s.readObject(); |
1110 |
|
if (ex != null) |
1111 |
< |
setDoneExceptionally((Throwable)ex); |
1111 |
> |
setDoneExceptionally((Throwable) ex); |
1112 |
|
} |
1113 |
|
|
1114 |
< |
// Temporary Unsafe mechanics for preliminary release |
1114 |
> |
// Unsafe mechanics for jsr166y 3rd party package. |
1115 |
> |
private static sun.misc.Unsafe getUnsafe() { |
1116 |
> |
try { |
1117 |
> |
return sun.misc.Unsafe.getUnsafe(); |
1118 |
> |
} catch (SecurityException se) { |
1119 |
> |
try { |
1120 |
> |
return java.security.AccessController.doPrivileged |
1121 |
> |
(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() { |
1122 |
> |
public sun.misc.Unsafe run() throws Exception { |
1123 |
> |
return getUnsafeByReflection(); |
1124 |
> |
}}); |
1125 |
> |
} catch (java.security.PrivilegedActionException e) { |
1126 |
> |
throw new RuntimeException("Could not initialize intrinsics", |
1127 |
> |
e.getCause()); |
1128 |
> |
} |
1129 |
> |
} |
1130 |
> |
} |
1131 |
|
|
1132 |
< |
static final Unsafe _unsafe; |
1133 |
< |
static final long statusOffset; |
1132 |
> |
private static sun.misc.Unsafe getUnsafeByReflection() |
1133 |
> |
throws NoSuchFieldException, IllegalAccessException { |
1134 |
> |
java.lang.reflect.Field f = |
1135 |
> |
sun.misc.Unsafe.class.getDeclaredField("theUnsafe"); |
1136 |
> |
f.setAccessible(true); |
1137 |
> |
return (sun.misc.Unsafe) f.get(null); |
1138 |
> |
} |
1139 |
|
|
1140 |
< |
static { |
1140 |
> |
private static long fieldOffset(String fieldName, Class<?> klazz) { |
1141 |
|
try { |
1142 |
< |
if (ForkJoinTask.class.getClassLoader() != null) { |
1143 |
< |
Field f = Unsafe.class.getDeclaredField("theUnsafe"); |
1144 |
< |
f.setAccessible(true); |
1145 |
< |
_unsafe = (Unsafe)f.get(null); |
1146 |
< |
} |
1147 |
< |
else |
1148 |
< |
_unsafe = Unsafe.getUnsafe(); |
919 |
< |
statusOffset = _unsafe.objectFieldOffset |
920 |
< |
(ForkJoinTask.class.getDeclaredField("status")); |
921 |
< |
} catch (Exception ex) { throw new Error(ex); } |
1142 |
> |
return UNSAFE.objectFieldOffset(klazz.getDeclaredField(fieldName)); |
1143 |
> |
} catch (NoSuchFieldException e) { |
1144 |
> |
// Convert Exception to Error |
1145 |
> |
NoSuchFieldError error = new NoSuchFieldError(fieldName); |
1146 |
> |
error.initCause(e); |
1147 |
> |
throw error; |
1148 |
> |
} |
1149 |
|
} |
1150 |
|
|
1151 |
+ |
private static final sun.misc.Unsafe UNSAFE = getUnsafe(); |
1152 |
+ |
private static final long statusOffset = |
1153 |
+ |
fieldOffset("status", ForkJoinTask.class); |
1154 |
+ |
|
1155 |
|
} |