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