22 |
|
* <p> A "main" ForkJoinTask begins execution when submitted to a |
23 |
|
* {@link ForkJoinPool}. Once started, it will usually in turn start |
24 |
|
* other subtasks. As indicated by the name of this class, many |
25 |
< |
* programs using ForkJoinTasks employ only methods <code>fork</code> |
26 |
< |
* and <code>join</code>, or derivatives such as |
27 |
< |
* <code>invokeAll</code>. However, this class also provides a number |
25 |
> |
* programs using ForkJoinTasks employ only methods {@code fork} |
26 |
> |
* and {@code join}, or derivatives such as |
27 |
> |
* {@code invokeAll}. However, this class also provides a number |
28 |
|
* of other methods that can come into play in advanced usages, as |
29 |
|
* well as extension mechanics that allow support of new forms of |
30 |
|
* fork/join processing. |
36 |
|
* operating on purely isolated objects. The primary coordination |
37 |
|
* mechanisms are {@link #fork}, that arranges asynchronous execution, |
38 |
|
* and {@link #join}, that doesn't proceed until the task's result has |
39 |
< |
* been computed. Computations should avoid <code>synchronized</code> |
39 |
> |
* been computed. Computations should avoid {@code synchronized} |
40 |
|
* methods or blocks, and should minimize other blocking |
41 |
|
* synchronization apart from joining other tasks or using |
42 |
|
* synchronizers such as Phasers that are advertised to cooperate with |
48 |
|
* performance, and the potential to indefinitely stall if the number |
49 |
|
* of threads not waiting for IO or other external synchronization |
50 |
|
* becomes exhausted. This usage restriction is in part enforced by |
51 |
< |
* not permitting checked exceptions such as <code>IOExceptions</code> |
51 |
> |
* not permitting checked exceptions such as {@code IOExceptions} |
52 |
|
* to be thrown. However, computations may still encounter unchecked |
53 |
|
* exceptions, that are rethrown to callers attempting join |
54 |
|
* them. These exceptions may additionally include |
58 |
|
* <p>The primary method for awaiting completion and extracting |
59 |
|
* results of a task is {@link #join}, but there are several variants: |
60 |
|
* The {@link Future#get} methods support interruptible and/or timed |
61 |
< |
* waits for completion and report results using <code>Future</code> |
61 |
> |
* waits for completion and report results using {@code Future} |
62 |
|
* conventions. Method {@link #helpJoin} enables callers to actively |
63 |
|
* execute other tasks while awaiting joins, which is sometimes more |
64 |
|
* efficient but only applies when all subtasks are known to be |
65 |
|
* strictly tree-structured. Method {@link #invoke} is semantically |
66 |
< |
* equivalent to <code>fork(); join()</code> but always attempts to |
66 |
> |
* equivalent to {@code fork(); join()} but always attempts to |
67 |
|
* begin execution in the current thread. The "<em>quiet</em>" forms |
68 |
|
* of these methods do not extract results or report exceptions. These |
69 |
|
* may be useful when a set of tasks are being executed, and you need |
70 |
|
* to delay processing of results or exceptions until all complete. |
71 |
< |
* Method <code>invokeAll</code> (available in multiple versions) |
71 |
> |
* Method {@code invokeAll} (available in multiple versions) |
72 |
|
* performs the most common form of parallel invocation: forking a set |
73 |
|
* of tasks and joining them all. |
74 |
|
* |
76 |
|
* Instead, you subclass one of the abstract classes that support a |
77 |
|
* particular style of fork/join processing. Normally, a concrete |
78 |
|
* ForkJoinTask subclass declares fields comprising its parameters, |
79 |
< |
* established in a constructor, and then defines a <code>compute</code> |
79 |
> |
* established in a constructor, and then defines a {@code compute} |
80 |
|
* method that somehow uses the control methods supplied by this base |
81 |
< |
* class. While these methods have <code>public</code> access (to allow |
81 |
> |
* class. While these methods have {@code public} access (to allow |
82 |
|
* instances of different task subclasses to call each others |
83 |
|
* methods), some of them may only be called from within other |
84 |
< |
* ForkJoinTasks. Attempts to invoke them in other contexts result in |
85 |
< |
* exceptions or errors possibly including ClassCastException. |
84 |
> |
* ForkJoinTasks (as may be determined using method {@link |
85 |
> |
* #inForkJoinPool}). Attempts to invoke them in other contexts |
86 |
> |
* result in exceptions or errors, possibly including |
87 |
> |
* ClassCastException. |
88 |
|
* |
89 |
< |
* <p>Most base support methods are <code>final</code> because their |
89 |
> |
* <p>Most base support methods are {@code final} because their |
90 |
|
* implementations are intrinsically tied to the underlying |
91 |
|
* lightweight task scheduling framework, and so cannot be overridden. |
92 |
|
* Developers creating new basic styles of fork/join processing should |
93 |
< |
* minimally implement <code>protected</code> methods |
94 |
< |
* <code>exec</code>, <code>setRawResult</code>, and |
95 |
< |
* <code>getRawResult</code>, while also introducing an abstract |
93 |
> |
* minimally implement {@code protected} methods |
94 |
> |
* {@code exec}, {@code setRawResult}, and |
95 |
> |
* {@code getRawResult}, while also introducing an abstract |
96 |
|
* computational method that can be implemented in its subclasses, |
97 |
< |
* possibly relying on other <code>protected</code> methods provided |
97 |
> |
* possibly relying on other {@code protected} methods provided |
98 |
|
* by this class. |
99 |
|
* |
100 |
|
* <p>ForkJoinTasks should perform relatively small amounts of |
101 |
< |
* computations, othewise splitting into smaller tasks. As a very |
101 |
> |
* computations, otherwise splitting into smaller tasks. As a very |
102 |
|
* rough rule of thumb, a task should perform more than 100 and less |
103 |
|
* than 10000 basic computational steps. If tasks are too big, then |
104 |
< |
* parellelism cannot improve throughput. If too small, then memory |
104 |
> |
* parallelism cannot improve throughput. If too small, then memory |
105 |
|
* and internal task maintenance overhead may overwhelm processing. |
106 |
|
* |
107 |
< |
* <p>ForkJoinTasks are <code>Serializable</code>, which enables them |
107 |
> |
* <p>ForkJoinTasks are {@code Serializable}, which enables them |
108 |
|
* to be used in extensions such as remote execution frameworks. It is |
109 |
|
* in general sensible to serialize tasks only before or after, but |
110 |
|
* not during execution. Serialization is not relied on during |
111 |
|
* execution itself. |
112 |
+ |
* |
113 |
+ |
* @since 1.7 |
114 |
+ |
* @author Doug Lea |
115 |
|
*/ |
116 |
|
public abstract class ForkJoinTask<V> implements Future<V>, Serializable { |
117 |
|
|
133 |
|
* currently unused. Also value 0x80000000 is available as spare |
134 |
|
* completion value. |
135 |
|
*/ |
136 |
< |
volatile int status; // accessed directy by pool and workers |
136 |
> |
volatile int status; // accessed directly by pool and workers |
137 |
|
|
138 |
|
static final int COMPLETION_MASK = 0xe0000000; |
139 |
|
static final int NORMAL = 0xe0000000; // == mask |
146 |
|
/** |
147 |
|
* Table of exceptions thrown by tasks, to enable reporting by |
148 |
|
* callers. Because exceptions are rare, we don't directly keep |
149 |
< |
* them with task objects, but instead us a weak ref table. Note |
149 |
> |
* them with task objects, but instead use a weak ref table. Note |
150 |
|
* that cancellation exceptions don't appear in the table, but are |
151 |
|
* instead recorded as status values. |
152 |
< |
* Todo: Use ConcurrentReferenceHashMap |
152 |
> |
* TODO: Use ConcurrentReferenceHashMap |
153 |
|
*/ |
154 |
|
static final Map<ForkJoinTask<?>, Throwable> exceptionMap = |
155 |
|
Collections.synchronizedMap |
158 |
|
// within-package utilities |
159 |
|
|
160 |
|
/** |
161 |
< |
* Get current worker thread, or null if not a worker thread |
161 |
> |
* Gets current worker thread, or null if not a worker thread. |
162 |
|
*/ |
163 |
|
static ForkJoinWorkerThread getWorker() { |
164 |
|
Thread t = Thread.currentThread(); |
165 |
< |
return ((t instanceof ForkJoinWorkerThread)? |
166 |
< |
(ForkJoinWorkerThread)t : null); |
165 |
> |
return ((t instanceof ForkJoinWorkerThread) ? |
166 |
> |
(ForkJoinWorkerThread) t : null); |
167 |
|
} |
168 |
|
|
169 |
|
final boolean casStatus(int cmp, int val) { |
170 |
< |
return _unsafe.compareAndSwapInt(this, statusOffset, cmp, val); |
170 |
> |
return UNSAFE.compareAndSwapInt(this, statusOffset, cmp, val); |
171 |
|
} |
172 |
|
|
173 |
|
/** |
175 |
|
*/ |
176 |
|
static void rethrowException(Throwable ex) { |
177 |
|
if (ex != null) |
178 |
< |
_unsafe.throwException(ex); |
178 |
> |
UNSAFE.throwException(ex); |
179 |
|
} |
180 |
|
|
181 |
|
// Setting completion status |
182 |
|
|
183 |
|
/** |
184 |
< |
* Mark completion and wake up threads waiting to join this task. |
184 |
> |
* Marks completion and wakes up threads waiting to join this task. |
185 |
> |
* |
186 |
|
* @param completion one of NORMAL, CANCELLED, EXCEPTIONAL |
187 |
|
*/ |
188 |
|
final void setCompletion(int completion) { |
189 |
|
ForkJoinPool pool = getPool(); |
190 |
|
if (pool != null) { |
191 |
|
int s; // Clear signal bits while setting completion status |
192 |
< |
do;while ((s = status) >= 0 && !casStatus(s, completion)); |
192 |
> |
do {} while ((s = status) >= 0 && !casStatus(s, completion)); |
193 |
|
|
194 |
|
if ((s & SIGNAL_MASK) != 0) { |
195 |
|
if ((s &= INTERNAL_SIGNAL_MASK) != 0) |
196 |
|
pool.updateRunningCount(s); |
197 |
< |
synchronized(this) { notifyAll(); } |
197 |
> |
synchronized (this) { notifyAll(); } |
198 |
|
} |
199 |
|
} |
200 |
|
else |
207 |
|
*/ |
208 |
|
private void externallySetCompletion(int completion) { |
209 |
|
int s; |
210 |
< |
do;while ((s = status) >= 0 && |
211 |
< |
!casStatus(s, (s & SIGNAL_MASK) | completion)); |
212 |
< |
synchronized(this) { notifyAll(); } |
210 |
> |
do {} while ((s = status) >= 0 && |
211 |
> |
!casStatus(s, (s & SIGNAL_MASK) | completion)); |
212 |
> |
synchronized (this) { notifyAll(); } |
213 |
|
} |
214 |
|
|
215 |
|
/** |
216 |
< |
* Sets status to indicate normal completion |
216 |
> |
* Sets status to indicate normal completion. |
217 |
|
*/ |
218 |
|
final void setNormalCompletion() { |
219 |
|
// Try typical fast case -- single CAS, no signal, not already done. |
220 |
|
// Manually expand casStatus to improve chances of inlining it |
221 |
< |
if (!_unsafe.compareAndSwapInt(this, statusOffset, 0, NORMAL)) |
221 |
> |
if (!UNSAFE.compareAndSwapInt(this, statusOffset, 0, NORMAL)) |
222 |
|
setCompletion(NORMAL); |
223 |
|
} |
224 |
|
|
225 |
|
// internal waiting and notification |
226 |
|
|
227 |
|
/** |
228 |
< |
* Performs the actual monitor wait for awaitDone |
228 |
> |
* Performs the actual monitor wait for awaitDone. |
229 |
|
*/ |
230 |
|
private void doAwaitDone() { |
231 |
|
// Minimize lock bias and in/de-flation effects by maximizing |
232 |
|
// chances of waiting inside sync |
233 |
|
try { |
234 |
|
while (status >= 0) |
235 |
< |
synchronized(this) { if (status >= 0) wait(); } |
235 |
> |
synchronized (this) { if (status >= 0) wait(); } |
236 |
|
} catch (InterruptedException ie) { |
237 |
|
onInterruptedWait(); |
238 |
|
} |
239 |
|
} |
240 |
|
|
241 |
|
/** |
242 |
< |
* Performs the actual monitor wait for awaitDone |
242 |
> |
* Performs the actual timed monitor wait for awaitDone. |
243 |
|
*/ |
244 |
|
private void doAwaitDone(long startTime, long nanos) { |
245 |
< |
synchronized(this) { |
245 |
> |
synchronized (this) { |
246 |
|
try { |
247 |
|
while (status >= 0) { |
248 |
|
long nt = nanos - System.nanoTime() - startTime; |
249 |
|
if (nt <= 0) |
250 |
|
break; |
251 |
< |
wait(nt / 1000000, (int)(nt % 1000000)); |
251 |
> |
wait(nt / 1000000, (int) (nt % 1000000)); |
252 |
|
} |
253 |
|
} catch (InterruptedException ie) { |
254 |
|
onInterruptedWait(); |
261 |
|
/** |
262 |
|
* Sets status to indicate there is joiner, then waits for join, |
263 |
|
* surrounded with pool notifications. |
264 |
+ |
* |
265 |
|
* @return status upon exit |
266 |
|
*/ |
267 |
< |
private int awaitDone(ForkJoinWorkerThread w, boolean maintainParallelism) { |
268 |
< |
ForkJoinPool pool = w == null? null : w.pool; |
267 |
> |
private int awaitDone(ForkJoinWorkerThread w, |
268 |
> |
boolean maintainParallelism) { |
269 |
> |
ForkJoinPool pool = (w == null) ? null : w.pool; |
270 |
|
int s; |
271 |
|
while ((s = status) >= 0) { |
272 |
< |
if (casStatus(s, pool == null? s|EXTERNAL_SIGNAL : s+1)) { |
272 |
> |
if (casStatus(s, (pool == null) ? s|EXTERNAL_SIGNAL : s+1)) { |
273 |
|
if (pool == null || !pool.preJoin(this, maintainParallelism)) |
274 |
|
doAwaitDone(); |
275 |
|
if (((s = status) & INTERNAL_SIGNAL_MASK) != 0) |
282 |
|
|
283 |
|
/** |
284 |
|
* Timed version of awaitDone |
285 |
+ |
* |
286 |
|
* @return status upon exit |
287 |
|
*/ |
288 |
|
private int awaitDone(ForkJoinWorkerThread w, long nanos) { |
289 |
< |
ForkJoinPool pool = w == null? null : w.pool; |
289 |
> |
ForkJoinPool pool = (w == null) ? null : w.pool; |
290 |
|
int s; |
291 |
|
while ((s = status) >= 0) { |
292 |
< |
if (casStatus(s, pool == null? s|EXTERNAL_SIGNAL : s+1)) { |
292 |
> |
if (casStatus(s, (pool == null) ? s|EXTERNAL_SIGNAL : s+1)) { |
293 |
|
long startTime = System.nanoTime(); |
294 |
|
if (pool == null || !pool.preJoin(this, false)) |
295 |
|
doAwaitDone(startTime, nanos); |
306 |
|
} |
307 |
|
|
308 |
|
/** |
309 |
< |
* Notify pool that thread is unblocked. Called by signalled |
309 |
> |
* Notifies pool that thread is unblocked. Called by signalled |
310 |
|
* threads when woken by non-FJ threads (which is atypical). |
311 |
|
*/ |
312 |
|
private void adjustPoolCountsOnUnblock(ForkJoinPool pool) { |
313 |
|
int s; |
314 |
< |
do;while ((s = status) < 0 && !casStatus(s, s & COMPLETION_MASK)); |
314 |
> |
do {} while ((s = status) < 0 && !casStatus(s, s & COMPLETION_MASK)); |
315 |
|
if (pool != null && (s &= INTERNAL_SIGNAL_MASK) != 0) |
316 |
|
pool.updateRunningCount(s); |
317 |
|
} |
318 |
|
|
319 |
|
/** |
320 |
< |
* Notify pool to adjust counts on cancelled or timed out wait |
320 |
> |
* Notifies pool to adjust counts on cancelled or timed out wait. |
321 |
|
*/ |
322 |
|
private void adjustPoolCountsOnCancelledWait(ForkJoinPool pool) { |
323 |
|
if (pool != null) { |
332 |
|
} |
333 |
|
|
334 |
|
/** |
335 |
< |
* Handle interruptions during waits. |
335 |
> |
* Handles interruptions during waits. |
336 |
|
*/ |
337 |
|
private void onInterruptedWait() { |
338 |
|
ForkJoinWorkerThread w = getWorker(); |
351 |
|
} |
352 |
|
|
353 |
|
/** |
354 |
< |
* Throws the exception associated with status s; |
354 |
> |
* Throws the exception associated with status s. |
355 |
> |
* |
356 |
|
* @throws the exception |
357 |
|
*/ |
358 |
|
private void reportException(int s) { |
365 |
|
} |
366 |
|
|
367 |
|
/** |
368 |
< |
* Returns result or throws exception using j.u.c.Future conventions |
369 |
< |
* Only call when isDone known to be true. |
368 |
> |
* Returns result or throws exception using j.u.c.Future conventions. |
369 |
> |
* Only call when {@code isDone} known to be true. |
370 |
|
*/ |
371 |
|
private V reportFutureResult() |
372 |
|
throws ExecutionException, InterruptedException { |
385 |
|
|
386 |
|
/** |
387 |
|
* Returns result or throws exception using j.u.c.Future conventions |
388 |
< |
* with timeouts |
388 |
> |
* with timeouts. |
389 |
|
*/ |
390 |
|
private V reportTimedFutureResult() |
391 |
|
throws InterruptedException, ExecutionException, TimeoutException { |
406 |
|
|
407 |
|
/** |
408 |
|
* Calls exec, recording completion, and rethrowing exception if |
409 |
< |
* encountered. Caller should normally check status before calling |
409 |
> |
* encountered. Caller should normally check status before calling. |
410 |
> |
* |
411 |
|
* @return true if completed normally |
412 |
|
*/ |
413 |
|
private boolean tryExec() { |
425 |
|
|
426 |
|
/** |
427 |
|
* Main execution method used by worker threads. Invokes |
428 |
< |
* base computation unless already complete |
428 |
> |
* base computation unless already complete. |
429 |
|
*/ |
430 |
|
final void quietlyExec() { |
431 |
|
if (status >= 0) { |
432 |
|
try { |
433 |
|
if (!exec()) |
434 |
|
return; |
435 |
< |
} catch(Throwable rex) { |
435 |
> |
} catch (Throwable rex) { |
436 |
|
setDoneExceptionally(rex); |
437 |
|
return; |
438 |
|
} |
441 |
|
} |
442 |
|
|
443 |
|
/** |
444 |
< |
* Calls exec, recording but not rethrowing exception |
445 |
< |
* Caller should normally check status before calling |
444 |
> |
* Calls exec(), recording but not rethrowing exception. |
445 |
> |
* Caller should normally check status before calling. |
446 |
> |
* |
447 |
|
* @return true if completed normally |
448 |
|
*/ |
449 |
|
private boolean tryQuietlyInvoke() { |
459 |
|
} |
460 |
|
|
461 |
|
/** |
462 |
< |
* Cancel, ignoring any exceptions it throws |
462 |
> |
* Cancels, ignoring any exceptions it throws. |
463 |
|
*/ |
464 |
|
final void cancelIgnoringExceptions() { |
465 |
|
try { |
466 |
|
cancel(false); |
467 |
< |
} catch(Throwable ignore) { |
467 |
> |
} catch (Throwable ignore) { |
468 |
|
} |
469 |
|
} |
470 |
|
|
476 |
|
ForkJoinTask<?> t; |
477 |
|
while ((s = status) >= 0 && (t = w.scanWhileJoining(this)) != null) |
478 |
|
t.quietlyExec(); |
479 |
< |
return (s >= 0)? awaitDone(w, false) : s; // block if no work |
479 |
> |
return (s >= 0) ? awaitDone(w, false) : s; // block if no work |
480 |
|
} |
481 |
|
|
482 |
|
// public methods |
486 |
|
* necessarily enforced, it is a usage error to fork a task more |
487 |
|
* than once unless it has completed and been reinitialized. This |
488 |
|
* method may be invoked only from within ForkJoinTask |
489 |
< |
* computations. Attempts to invoke in other contexts result in |
490 |
< |
* exceptions or errors possibly including ClassCastException. |
489 |
> |
* computations (as may be determined using method {@link |
490 |
> |
* #inForkJoinPool}). Attempts to invoke in other contexts result |
491 |
> |
* in exceptions or errors, possibly including ClassCastException. |
492 |
|
*/ |
493 |
|
public final void fork() { |
494 |
< |
((ForkJoinWorkerThread)(Thread.currentThread())).pushTask(this); |
494 |
> |
((ForkJoinWorkerThread) Thread.currentThread()) |
495 |
> |
.pushTask(this); |
496 |
|
} |
497 |
|
|
498 |
|
/** |
499 |
|
* Returns the result of the computation when it is ready. |
500 |
< |
* This method differs from <code>get</code> in that abnormal |
500 |
> |
* This method differs from {@code get} in that abnormal |
501 |
|
* completion results in RuntimeExceptions or Errors, not |
502 |
|
* ExecutionExceptions. |
503 |
|
* |
513 |
|
/** |
514 |
|
* Commences performing this task, awaits its completion if |
515 |
|
* necessary, and return its result. |
516 |
+ |
* |
517 |
|
* @throws Throwable (a RuntimeException, Error, or unchecked |
518 |
< |
* exception) if the underlying computation did so. |
518 |
> |
* exception) if the underlying computation did so |
519 |
|
* @return the computed result |
520 |
|
*/ |
521 |
|
public final V invoke() { |
526 |
|
} |
527 |
|
|
528 |
|
/** |
529 |
< |
* Forks both tasks, returning when <code>isDone</code> holds for |
529 |
> |
* Forks both tasks, returning when {@code isDone} holds for |
530 |
|
* both of them or an exception is encountered. This method may be |
531 |
< |
* invoked only from within ForkJoinTask computations. Attempts to |
532 |
< |
* invoke in other contexts result in exceptions or errors |
531 |
> |
* invoked only from within ForkJoinTask computations (as may be |
532 |
> |
* determined using method {@link #inForkJoinPool}). Attempts to |
533 |
> |
* invoke in other contexts result in exceptions or errors, |
534 |
|
* possibly including ClassCastException. |
535 |
+ |
* |
536 |
|
* @param t1 one task |
537 |
|
* @param t2 the other task |
538 |
|
* @throws NullPointerException if t1 or t2 are null |
539 |
< |
* @throws RuntimeException or Error if either task did so. |
539 |
> |
* @throws RuntimeException or Error if either task did so |
540 |
|
*/ |
541 |
|
public static void invokeAll(ForkJoinTask<?>t1, ForkJoinTask<?> t2) { |
542 |
|
t2.fork(); |
545 |
|
} |
546 |
|
|
547 |
|
/** |
548 |
< |
* Forks the given tasks, returning when <code>isDone</code> holds |
548 |
> |
* Forks the given tasks, returning when {@code isDone} holds |
549 |
|
* for all of them. If any task encounters an exception, others |
550 |
|
* may be cancelled. This method may be invoked only from within |
551 |
< |
* ForkJoinTask computations. Attempts to invoke in other contexts |
552 |
< |
* result in exceptions or errors possibly including ClassCastException. |
551 |
> |
* ForkJoinTask computations (as may be determined using method |
552 |
> |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
553 |
> |
* result in exceptions or errors, possibly including |
554 |
> |
* ClassCastException. |
555 |
> |
* |
556 |
|
* @param tasks the array of tasks |
557 |
< |
* @throws NullPointerException if tasks or any element are null. |
558 |
< |
* @throws RuntimeException or Error if any task did so. |
557 |
> |
* @throws NullPointerException if tasks or any element are null |
558 |
> |
* @throws RuntimeException or Error if any task did so |
559 |
|
*/ |
560 |
|
public static void invokeAll(ForkJoinTask<?>... tasks) { |
561 |
|
Throwable ex = null; |
592 |
|
|
593 |
|
/** |
594 |
|
* Forks all tasks in the collection, returning when |
595 |
< |
* <code>isDone</code> holds for all of them. If any task |
595 |
> |
* {@code isDone} holds for all of them. If any task |
596 |
|
* encounters an exception, others may be cancelled. This method |
597 |
< |
* may be invoked only from within ForkJoinTask |
598 |
< |
* computations. Attempts to invoke in other contexts resul!t in |
599 |
< |
* exceptions or errors possibly including ClassCastException. |
597 |
> |
* may be invoked only from within ForkJoinTask computations (as |
598 |
> |
* may be determined using method {@link |
599 |
> |
* #inForkJoinPool}). Attempts to invoke in other contexts result |
600 |
> |
* in exceptions or errors, possibly including ClassCastException. |
601 |
> |
* |
602 |
|
* @param tasks the collection of tasks |
603 |
< |
* @throws NullPointerException if tasks or any element are null. |
604 |
< |
* @throws RuntimeException or Error if any task did so. |
603 |
> |
* @throws NullPointerException if tasks or any element are null |
604 |
> |
* @throws RuntimeException or Error if any task did so |
605 |
|
*/ |
606 |
|
public static void invokeAll(Collection<? extends ForkJoinTask<?>> tasks) { |
607 |
< |
if (!(tasks instanceof List)) { |
608 |
< |
invokeAll(tasks.toArray(new ForkJoinTask[tasks.size()])); |
607 |
> |
if (!(tasks instanceof List<?>)) { |
608 |
> |
invokeAll(tasks.toArray(new ForkJoinTask<?>[tasks.size()])); |
609 |
|
return; |
610 |
|
} |
611 |
+ |
@SuppressWarnings("unchecked") |
612 |
|
List<? extends ForkJoinTask<?>> ts = |
613 |
< |
(List<? extends ForkJoinTask<?>>)tasks; |
613 |
> |
(List<? extends ForkJoinTask<?>>) tasks; |
614 |
|
Throwable ex = null; |
615 |
|
int last = ts.size() - 1; |
616 |
|
for (int i = last; i >= 0; --i) { |
646 |
|
/** |
647 |
|
* Returns true if the computation performed by this task has |
648 |
|
* completed (or has been cancelled). |
649 |
+ |
* |
650 |
|
* @return true if this computation has completed |
651 |
|
*/ |
652 |
|
public final boolean isDone() { |
655 |
|
|
656 |
|
/** |
657 |
|
* Returns true if this task was cancelled. |
658 |
+ |
* |
659 |
|
* @return true if this task was cancelled |
660 |
|
*/ |
661 |
|
public final boolean isCancelled() { |
664 |
|
|
665 |
|
/** |
666 |
|
* Asserts that the results of this task's computation will not be |
667 |
< |
* used. If a cancellation occurs before atempting to execute this |
668 |
< |
* task, then execution will be suppressed, <code>isCancelled</code> |
669 |
< |
* will report true, and <code>join</code> will result in a |
670 |
< |
* <code>CancellationException</code> being thrown. Otherwise, when |
667 |
> |
* used. If a cancellation occurs before attempting to execute this |
668 |
> |
* task, then execution will be suppressed, {@code isCancelled} |
669 |
> |
* will report true, and {@code join} will result in a |
670 |
> |
* {@code CancellationException} being thrown. Otherwise, when |
671 |
|
* cancellation races with completion, there are no guarantees |
672 |
< |
* about whether <code>isCancelled</code> will report true, whether |
673 |
< |
* <code>join</code> will return normally or via an exception, or |
672 |
> |
* about whether {@code isCancelled} will report true, whether |
673 |
> |
* {@code join} will return normally or via an exception, or |
674 |
|
* whether these behaviors will remain consistent upon repeated |
675 |
|
* invocation. |
676 |
|
* |
681 |
|
* <p> This method is designed to be invoked by <em>other</em> |
682 |
|
* tasks. To terminate the current task, you can just return or |
683 |
|
* throw an unchecked exception from its computation method, or |
684 |
< |
* invoke <code>completeExceptionally</code>. |
684 |
> |
* invoke {@code completeExceptionally}. |
685 |
|
* |
686 |
|
* @param mayInterruptIfRunning this value is ignored in the |
687 |
|
* default implementation because tasks are not in general |
688 |
< |
* cancelled via interruption. |
688 |
> |
* cancelled via interruption |
689 |
|
* |
690 |
|
* @return true if this task is now cancelled |
691 |
|
*/ |
695 |
|
} |
696 |
|
|
697 |
|
/** |
698 |
< |
* Returns true if this task threw an exception or was cancelled |
698 |
> |
* Returns true if this task threw an exception or was cancelled. |
699 |
> |
* |
700 |
|
* @return true if this task threw an exception or was cancelled |
701 |
|
*/ |
702 |
|
public final boolean isCompletedAbnormally() { |
707 |
|
* Returns the exception thrown by the base computation, or a |
708 |
|
* CancellationException if cancelled, or null if none or if the |
709 |
|
* method has not yet completed. |
710 |
+ |
* |
711 |
|
* @return the exception, or null if none |
712 |
|
*/ |
713 |
|
public final Throwable getException() { |
722 |
|
/** |
723 |
|
* Completes this task abnormally, and if not already aborted or |
724 |
|
* cancelled, causes it to throw the given exception upon |
725 |
< |
* <code>join</code> and related operations. This method may be used |
725 |
> |
* {@code join} and related operations. This method may be used |
726 |
|
* to induce exceptions in asynchronous tasks, or to force |
727 |
|
* completion of tasks that would not otherwise complete. Its use |
728 |
|
* in other situations is likely to be wrong. This method is |
729 |
< |
* overridable, but overridden versions must invoke <code>super</code> |
729 |
> |
* overridable, but overridden versions must invoke {@code super} |
730 |
|
* implementation to maintain guarantees. |
731 |
|
* |
732 |
|
* @param ex the exception to throw. If this exception is |
735 |
|
*/ |
736 |
|
public void completeExceptionally(Throwable ex) { |
737 |
|
setDoneExceptionally((ex instanceof RuntimeException) || |
738 |
< |
(ex instanceof Error)? ex : |
738 |
> |
(ex instanceof Error) ? ex : |
739 |
|
new RuntimeException(ex)); |
740 |
|
} |
741 |
|
|
742 |
|
/** |
743 |
|
* Completes this task, and if not already aborted or cancelled, |
744 |
< |
* returning a <code>null</code> result upon <code>join</code> and related |
744 |
> |
* returning a {@code null} result upon {@code join} and related |
745 |
|
* operations. This method may be used to provide results for |
746 |
|
* asynchronous tasks, or to provide alternative handling for |
747 |
|
* tasks that would not otherwise complete normally. Its use in |
748 |
|
* other situations is likely to be wrong. This method is |
749 |
< |
* overridable, but overridden versions must invoke <code>super</code> |
749 |
> |
* overridable, but overridden versions must invoke {@code super} |
750 |
|
* implementation to maintain guarantees. |
751 |
|
* |
752 |
< |
* @param value the result value for this task. |
752 |
> |
* @param value the result value for this task |
753 |
|
*/ |
754 |
|
public void complete(V value) { |
755 |
|
try { |
756 |
|
setRawResult(value); |
757 |
< |
} catch(Throwable rex) { |
757 |
> |
} catch (Throwable rex) { |
758 |
|
setDoneExceptionally(rex); |
759 |
|
return; |
760 |
|
} |
779 |
|
/** |
780 |
|
* Possibly executes other tasks until this task is ready, then |
781 |
|
* returns the result of the computation. This method may be more |
782 |
< |
* efficient than <code>join</code>, but is only applicable when |
783 |
< |
* there are no potemtial dependencies between continuation of the |
782 |
> |
* efficient than {@code join}, but is only applicable when |
783 |
> |
* there are no potential dependencies between continuation of the |
784 |
|
* current task and that of any other task that might be executed |
785 |
|
* while helping. (This usually holds for pure divide-and-conquer |
786 |
|
* tasks). This method may be invoked only from within |
787 |
< |
* ForkJoinTask computations. Attempts to invoke in other contexts |
788 |
< |
* resul!t in exceptions or errors possibly including ClassCastException. |
787 |
> |
* ForkJoinTask computations (as may be determined using method |
788 |
> |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
789 |
> |
* result in exceptions or errors, possibly including |
790 |
> |
* ClassCastException. |
791 |
> |
* |
792 |
|
* @return the computed result |
793 |
|
*/ |
794 |
|
public final V helpJoin() { |
795 |
< |
ForkJoinWorkerThread w = (ForkJoinWorkerThread)(Thread.currentThread()); |
795 |
> |
ForkJoinWorkerThread w = (ForkJoinWorkerThread) Thread.currentThread(); |
796 |
|
if (status < 0 || !w.unpushTask(this) || !tryExec()) |
797 |
|
reportException(busyJoin(w)); |
798 |
|
return getRawResult(); |
801 |
|
/** |
802 |
|
* Possibly executes other tasks until this task is ready. This |
803 |
|
* method may be invoked only from within ForkJoinTask |
804 |
< |
* computations. Attempts to invoke in other contexts resul!t in |
805 |
< |
* exceptions or errors possibly including ClassCastException. |
804 |
> |
* computations (as may be determined using method {@link |
805 |
> |
* #inForkJoinPool}). Attempts to invoke in other contexts result |
806 |
> |
* in exceptions or errors, possibly including ClassCastException. |
807 |
|
*/ |
808 |
|
public final void quietlyHelpJoin() { |
809 |
|
if (status >= 0) { |
810 |
|
ForkJoinWorkerThread w = |
811 |
< |
(ForkJoinWorkerThread)(Thread.currentThread()); |
811 |
> |
(ForkJoinWorkerThread) Thread.currentThread(); |
812 |
|
if (!w.unpushTask(this) || !tryQuietlyInvoke()) |
813 |
|
busyJoin(w); |
814 |
|
} |
847 |
|
* joined, instead executing them until all are processed. |
848 |
|
*/ |
849 |
|
public static void helpQuiesce() { |
850 |
< |
((ForkJoinWorkerThread)(Thread.currentThread())). |
851 |
< |
helpQuiescePool(); |
850 |
> |
((ForkJoinWorkerThread) Thread.currentThread()) |
851 |
> |
.helpQuiescePool(); |
852 |
|
} |
853 |
|
|
854 |
|
/** |
855 |
|
* Resets the internal bookkeeping state of this task, allowing a |
856 |
< |
* subsequent <code>fork</code>. This method allows repeated reuse of |
856 |
> |
* subsequent {@code fork}. This method allows repeated reuse of |
857 |
|
* this task, but only if reuse occurs when this task has either |
858 |
|
* never been forked, or has been forked, then completed and all |
859 |
|
* outstanding joins of this task have also completed. Effects |
869 |
|
|
870 |
|
/** |
871 |
|
* Returns the pool hosting the current task execution, or null |
872 |
< |
* if this task is executing outside of any pool. |
873 |
< |
* @return the pool, or null if none. |
872 |
> |
* if this task is executing outside of any ForkJoinPool. |
873 |
> |
* |
874 |
> |
* @return the pool, or null if none |
875 |
|
*/ |
876 |
|
public static ForkJoinPool getPool() { |
877 |
|
Thread t = Thread.currentThread(); |
878 |
< |
return ((t instanceof ForkJoinWorkerThread)? |
879 |
< |
((ForkJoinWorkerThread)t).pool : null); |
878 |
> |
return (t instanceof ForkJoinWorkerThread) ? |
879 |
> |
((ForkJoinWorkerThread) t).pool : null; |
880 |
> |
} |
881 |
> |
|
882 |
> |
/** |
883 |
> |
* Returns {@code true} if the current thread is executing as a |
884 |
> |
* ForkJoinPool computation. |
885 |
> |
* |
886 |
> |
* @return {@code true} if the current thread is executing as a |
887 |
> |
* ForkJoinPool computation, or false otherwise |
888 |
> |
*/ |
889 |
> |
public static boolean inForkJoinPool() { |
890 |
> |
return Thread.currentThread() instanceof ForkJoinWorkerThread; |
891 |
|
} |
892 |
|
|
893 |
|
/** |
897 |
|
* another thread. This method may be useful when arranging |
898 |
|
* alternative local processing of tasks that could have been, but |
899 |
|
* were not, stolen. This method may be invoked only from within |
900 |
< |
* ForkJoinTask computations. Attempts to invoke in other contexts |
901 |
< |
* result in exceptions or errors possibly including ClassCastException. |
900 |
> |
* ForkJoinTask computations (as may be determined using method |
901 |
> |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
902 |
> |
* result in exceptions or errors, possibly including |
903 |
> |
* ClassCastException. |
904 |
> |
* |
905 |
|
* @return true if unforked |
906 |
|
*/ |
907 |
|
public boolean tryUnfork() { |
908 |
< |
return ((ForkJoinWorkerThread)(Thread.currentThread())).unpushTask(this); |
908 |
> |
return ((ForkJoinWorkerThread) Thread.currentThread()) |
909 |
> |
.unpushTask(this); |
910 |
|
} |
911 |
|
|
912 |
|
/** |
914 |
|
* forked by the current worker thread but not yet executed. This |
915 |
|
* value may be useful for heuristic decisions about whether to |
916 |
|
* fork other tasks. |
917 |
+ |
* |
918 |
|
* @return the number of tasks |
919 |
|
*/ |
920 |
|
public static int getQueuedTaskCount() { |
921 |
< |
return ((ForkJoinWorkerThread)(Thread.currentThread())). |
922 |
< |
getQueueSize(); |
921 |
> |
return ((ForkJoinWorkerThread) Thread.currentThread()) |
922 |
> |
.getQueueSize(); |
923 |
|
} |
924 |
|
|
925 |
|
/** |
926 |
< |
* Returns a estimate of how many more locally queued tasks are |
926 |
> |
* Returns an estimate of how many more locally queued tasks are |
927 |
|
* held by the current worker thread than there are other worker |
928 |
|
* threads that might steal them. This value may be useful for |
929 |
|
* heuristic decisions about whether to fork other tasks. In many |
931 |
|
* aim to maintain a small constant surplus (for example, 3) of |
932 |
|
* tasks, and to process computations locally if this threshold is |
933 |
|
* exceeded. |
934 |
+ |
* |
935 |
|
* @return the surplus number of tasks, which may be negative |
936 |
|
*/ |
937 |
|
public static int getSurplusQueuedTaskCount() { |
938 |
< |
return ((ForkJoinWorkerThread)(Thread.currentThread())) |
938 |
> |
return ((ForkJoinWorkerThread) Thread.currentThread()) |
939 |
|
.getEstimatedSurplusTaskCount(); |
940 |
|
} |
941 |
|
|
942 |
|
// Extension methods |
943 |
|
|
944 |
|
/** |
945 |
< |
* Returns the result that would be returned by <code>join</code>, |
945 |
> |
* Returns the result that would be returned by {@code join}, |
946 |
|
* even if this task completed abnormally, or null if this task is |
947 |
|
* not known to have been completed. This method is designed to |
948 |
|
* aid debugging, as well as to support extensions. Its use in any |
949 |
|
* other context is discouraged. |
950 |
|
* |
951 |
< |
* @return the result, or null if not completed. |
951 |
> |
* @return the result, or null if not completed |
952 |
|
*/ |
953 |
|
public abstract V getRawResult(); |
954 |
|
|
967 |
|
* called otherwise. The return value controls whether this task |
968 |
|
* is considered to be done normally. It may return false in |
969 |
|
* asynchronous actions that require explicit invocations of |
970 |
< |
* <code>complete</code> to become joinable. It may throw exceptions |
970 |
> |
* {@code complete} to become joinable. It may throw exceptions |
971 |
|
* to indicate abnormal exit. |
972 |
+ |
* |
973 |
|
* @return true if completed normally |
974 |
|
* @throws Error or RuntimeException if encountered during computation |
975 |
|
*/ |
976 |
|
protected abstract boolean exec(); |
977 |
|
|
978 |
|
/** |
979 |
< |
* Returns, but does not unschedule or execute, the task most |
980 |
< |
* recently forked by the current thread but not yet executed, if |
981 |
< |
* one is available. There is no guarantee that this task will |
982 |
< |
* actually be polled or executed next. |
983 |
< |
* This method is designed primarily to support extensions, |
984 |
< |
* and is unlikely to be useful otherwise. |
985 |
< |
* This method may be invoked only from within |
986 |
< |
* ForkJoinTask computations. Attempts to invoke in other contexts |
987 |
< |
* result in exceptions or errors possibly including ClassCastException. |
979 |
> |
* Returns, but does not unschedule or execute, the task queued by |
980 |
> |
* the current thread but not yet executed, if one is |
981 |
> |
* available. There is no guarantee that this task will actually |
982 |
> |
* be polled or executed next. This method is designed primarily |
983 |
> |
* to support extensions, and is unlikely to be useful otherwise. |
984 |
> |
* This method may be invoked only from within ForkJoinTask |
985 |
> |
* computations (as may be determined using method {@link |
986 |
> |
* #inForkJoinPool}). Attempts to invoke in other contexts result |
987 |
> |
* in exceptions or errors, possibly including ClassCastException. |
988 |
|
* |
989 |
|
* @return the next task, or null if none are available |
990 |
|
*/ |
991 |
|
protected static ForkJoinTask<?> peekNextLocalTask() { |
992 |
< |
return ((ForkJoinWorkerThread)(Thread.currentThread())).peekTask(); |
992 |
> |
return ((ForkJoinWorkerThread) Thread.currentThread()) |
993 |
> |
.peekTask(); |
994 |
|
} |
995 |
|
|
996 |
|
/** |
997 |
< |
* Unschedules and returns, without executing, the task most |
998 |
< |
* recently forked by the current thread but not yet executed. |
999 |
< |
* This method is designed primarily to support extensions, |
1000 |
< |
* and is unlikely to be useful otherwise. |
1001 |
< |
* This method may be invoked only from within |
1002 |
< |
* ForkJoinTask computations. Attempts to invoke in other contexts |
1003 |
< |
* result in exceptions or errors possibly including ClassCastException. |
997 |
> |
* Unschedules and returns, without executing, the next task |
998 |
> |
* queued by the current thread but not yet executed. This method |
999 |
> |
* is designed primarily to support extensions, and is unlikely to |
1000 |
> |
* be useful otherwise. This method may be invoked only from |
1001 |
> |
* within ForkJoinTask computations (as may be determined using |
1002 |
> |
* method {@link #inForkJoinPool}). Attempts to invoke in other |
1003 |
> |
* contexts result in exceptions or errors, possibly including |
1004 |
> |
* ClassCastException. |
1005 |
|
* |
1006 |
|
* @return the next task, or null if none are available |
1007 |
|
*/ |
1008 |
|
protected static ForkJoinTask<?> pollNextLocalTask() { |
1009 |
< |
return ((ForkJoinWorkerThread)(Thread.currentThread())).popTask(); |
1009 |
> |
return ((ForkJoinWorkerThread) Thread.currentThread()) |
1010 |
> |
.pollLocalTask(); |
1011 |
|
} |
1012 |
|
|
1013 |
|
/** |
1014 |
< |
* Unschedules and returns, without executing, the task most |
1015 |
< |
* recently forked by the current thread but not yet executed, if |
1016 |
< |
* one is available, or if not available, a task that was forked |
1017 |
< |
* by some other thread, if available. Availability may be |
1018 |
< |
* transient, so a <code>null</code> result does not necessarily |
1019 |
< |
* imply quiecence of the pool this task is operating in. |
1020 |
< |
* This method is designed primarily to support extensions, |
1021 |
< |
* and is unlikely to be useful otherwise. |
1022 |
< |
* This method may be invoked only from within |
1023 |
< |
* ForkJoinTask computations. Attempts to invoke in other contexts |
1024 |
< |
* result in exceptions or errors possibly including ClassCastException. |
1014 |
> |
* Unschedules and returns, without executing, the next task |
1015 |
> |
* queued by the current thread but not yet executed, if one is |
1016 |
> |
* available, or if not available, a task that was forked by some |
1017 |
> |
* other thread, if available. Availability may be transient, so a |
1018 |
> |
* {@code null} result does not necessarily imply quiescence |
1019 |
> |
* of the pool this task is operating in. This method is designed |
1020 |
> |
* primarily to support extensions, and is unlikely to be useful |
1021 |
> |
* otherwise. This method may be invoked only from within |
1022 |
> |
* ForkJoinTask computations (as may be determined using method |
1023 |
> |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
1024 |
> |
* result in exceptions or errors, possibly including |
1025 |
> |
* ClassCastException. |
1026 |
|
* |
1027 |
|
* @return a task, or null if none are available |
1028 |
|
*/ |
1029 |
|
protected static ForkJoinTask<?> pollTask() { |
1030 |
< |
return ((ForkJoinWorkerThread)(Thread.currentThread())). |
1031 |
< |
pollTask(); |
1030 |
> |
return ((ForkJoinWorkerThread) Thread.currentThread()) |
1031 |
> |
.pollTask(); |
1032 |
|
} |
1033 |
|
|
1034 |
|
// Serialization support |
1039 |
|
* Save the state to a stream. |
1040 |
|
* |
1041 |
|
* @serialData the current run status and the exception thrown |
1042 |
< |
* during execution, or null if none. |
1042 |
> |
* during execution, or null if none |
1043 |
|
* @param s the stream |
1044 |
|
*/ |
1045 |
|
private void writeObject(java.io.ObjectOutputStream s) |
1050 |
|
|
1051 |
|
/** |
1052 |
|
* Reconstitute the instance from a stream. |
1053 |
+ |
* |
1054 |
|
* @param s the stream |
1055 |
|
*/ |
1056 |
|
private void readObject(java.io.ObjectInputStream s) |
1060 |
|
status |= EXTERNAL_SIGNAL; // conservatively set external signal |
1061 |
|
Object ex = s.readObject(); |
1062 |
|
if (ex != null) |
1063 |
< |
setDoneExceptionally((Throwable)ex); |
1063 |
> |
setDoneExceptionally((Throwable) ex); |
1064 |
|
} |
1065 |
|
|
1066 |
|
// Temporary Unsafe mechanics for preliminary release |
1067 |
+ |
private static Unsafe getUnsafe() throws Throwable { |
1068 |
+ |
try { |
1069 |
+ |
return Unsafe.getUnsafe(); |
1070 |
+ |
} catch (SecurityException se) { |
1071 |
+ |
try { |
1072 |
+ |
return java.security.AccessController.doPrivileged |
1073 |
+ |
(new java.security.PrivilegedExceptionAction<Unsafe>() { |
1074 |
+ |
public Unsafe run() throws Exception { |
1075 |
+ |
return getUnsafePrivileged(); |
1076 |
+ |
}}); |
1077 |
+ |
} catch (java.security.PrivilegedActionException e) { |
1078 |
+ |
throw e.getCause(); |
1079 |
+ |
} |
1080 |
+ |
} |
1081 |
+ |
} |
1082 |
+ |
|
1083 |
+ |
private static Unsafe getUnsafePrivileged() |
1084 |
+ |
throws NoSuchFieldException, IllegalAccessException { |
1085 |
+ |
Field f = Unsafe.class.getDeclaredField("theUnsafe"); |
1086 |
+ |
f.setAccessible(true); |
1087 |
+ |
return (Unsafe) f.get(null); |
1088 |
+ |
} |
1089 |
|
|
1090 |
< |
static final Unsafe _unsafe; |
1090 |
> |
private static long fieldOffset(String fieldName) |
1091 |
> |
throws NoSuchFieldException { |
1092 |
> |
return UNSAFE.objectFieldOffset |
1093 |
> |
(ForkJoinTask.class.getDeclaredField(fieldName)); |
1094 |
> |
} |
1095 |
> |
|
1096 |
> |
static final Unsafe UNSAFE; |
1097 |
|
static final long statusOffset; |
1098 |
|
|
1099 |
|
static { |
1100 |
|
try { |
1101 |
< |
if (ForkJoinTask.class.getClassLoader() != null) { |
1102 |
< |
Field f = Unsafe.class.getDeclaredField("theUnsafe"); |
1103 |
< |
f.setAccessible(true); |
1104 |
< |
_unsafe = (Unsafe)f.get(null); |
1105 |
< |
} |
1023 |
< |
else |
1024 |
< |
_unsafe = Unsafe.getUnsafe(); |
1025 |
< |
statusOffset = _unsafe.objectFieldOffset |
1026 |
< |
(ForkJoinTask.class.getDeclaredField("status")); |
1027 |
< |
} catch (Exception ex) { throw new Error(ex); } |
1101 |
> |
UNSAFE = getUnsafe(); |
1102 |
> |
statusOffset = fieldOffset("status"); |
1103 |
> |
} catch (Throwable e) { |
1104 |
> |
throw new RuntimeException("Could not initialize intrinsics", e); |
1105 |
> |
} |
1106 |
|
} |
1107 |
|
|
1108 |
|
} |