1 |
|
/* |
2 |
|
* Written by Doug Lea with assistance from members of JCP JSR-166 |
3 |
|
* Expert Group and released to the public domain, as explained at |
4 |
< |
* http://creativecommons.org/licenses/publicdomain |
4 |
> |
* http://creativecommons.org/publicdomain/zero/1.0/ |
5 |
|
*/ |
6 |
|
|
7 |
|
package jsr166y; |
8 |
|
|
9 |
– |
import java.util.concurrent.*; |
10 |
– |
|
9 |
|
import java.io.Serializable; |
10 |
|
import java.util.Collection; |
13 |
– |
import java.util.Collections; |
11 |
|
import java.util.List; |
12 |
|
import java.util.RandomAccess; |
13 |
< |
import java.util.Map; |
14 |
< |
import java.util.WeakHashMap; |
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}. |
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}. However, this class also provides a number of other |
39 |
< |
* methods that can come into play in advanced usages, as well as |
40 |
< |
* extension mechanics that allow support of new forms of fork/join |
41 |
< |
* processing. |
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 |
65 |
|
* rethrown to callers attempting to join them. These exceptions may |
66 |
|
* additionally include {@link RejectedExecutionException} stemming |
67 |
|
* from internal resource exhaustion, such as failure to allocate |
68 |
< |
* internal task queues. |
68 |
> |
* internal task queues. Rethrown exceptions behave in the same way as |
69 |
> |
* regular exceptions, but, when possible, contain stack traces (as |
70 |
> |
* displayed for example using {@code ex.printStackTrace()}) of both |
71 |
> |
* the thread that initiated the computation as well as the thread |
72 |
> |
* actually encountering the exception; minimally only the latter. |
73 |
|
* |
74 |
|
* <p>The primary method for awaiting completion and extracting |
75 |
|
* results of a task is {@link #join}, but there are several variants: |
76 |
|
* The {@link Future#get} methods support interruptible and/or timed |
77 |
|
* waits for completion and report results using {@code Future} |
78 |
< |
* conventions. Method {@link #helpJoin} enables callers to actively |
68 |
< |
* execute other tasks while awaiting joins, which is sometimes more |
69 |
< |
* efficient but only applies when all subtasks are known to be |
70 |
< |
* strictly tree-structured. Method {@link #invoke} is semantically |
78 |
> |
* conventions. Method {@link #invoke} is semantically |
79 |
|
* equivalent to {@code fork(); join()} but always attempts to begin |
80 |
|
* execution in the current thread. The "<em>quiet</em>" forms of |
81 |
|
* these methods do not extract results or report exceptions. These |
111 |
|
* ForkJoinTasks (as may be determined using method {@link |
112 |
|
* #inForkJoinPool}). Attempts to invoke them in other contexts |
113 |
|
* result in exceptions or errors, possibly including |
114 |
< |
* ClassCastException. |
114 |
> |
* {@code ClassCastException}. |
115 |
> |
* |
116 |
> |
* <p>Method {@link #join} and its variants are appropriate for use |
117 |
> |
* only when completion dependencies are acyclic; that is, the |
118 |
> |
* parallel computation can be described as a directed acyclic graph |
119 |
> |
* (DAG). Otherwise, executions may encounter a form of deadlock as |
120 |
> |
* tasks cyclically wait for each other. However, this framework |
121 |
> |
* supports other methods and techniques (for example the use of |
122 |
> |
* {@link Phaser}, {@link #helpQuiesce}, and {@link #complete}) that |
123 |
> |
* may be of use in constructing custom subclasses for problems that |
124 |
> |
* are not statically structured as DAGs. |
125 |
|
* |
126 |
|
* <p>Most base support methods are {@code final}, to prevent |
127 |
|
* overriding of implementations that are intrinsically tied to the |
137 |
|
* computation. Large tasks should be split into smaller subtasks, |
138 |
|
* usually via recursive decomposition. As a very rough rule of thumb, |
139 |
|
* a task should perform more than 100 and less than 10000 basic |
140 |
< |
* computational steps. If tasks are too big, then parallelism cannot |
141 |
< |
* improve throughput. If too small, then memory and internal task |
142 |
< |
* maintenance overhead may overwhelm processing. |
140 |
> |
* computational steps, and should avoid indefinite looping. If tasks |
141 |
> |
* are too big, then parallelism cannot improve throughput. If too |
142 |
> |
* small, then memory and internal task maintenance overhead may |
143 |
> |
* overwhelm processing. |
144 |
|
* |
145 |
|
* <p>This class provides {@code adapt} methods for {@link Runnable} |
146 |
|
* and {@link Callable}, that may be of use when mixing execution of |
147 |
< |
* {@code ForkJoinTasks} with other kinds of tasks. When all tasks |
148 |
< |
* are of this form, consider using a pool in |
130 |
< |
* {@linkplain ForkJoinPool#setAsyncMode async mode}. |
147 |
> |
* {@code ForkJoinTasks} with other kinds of tasks. When all tasks are |
148 |
> |
* of this form, consider using a pool constructed in <em>asyncMode</em>. |
149 |
|
* |
150 |
|
* <p>ForkJoinTasks are {@code Serializable}, which enables them to be |
151 |
|
* used in extensions such as remote execution frameworks. It is |
161 |
|
* See the internal documentation of class ForkJoinPool for a |
162 |
|
* general implementation overview. ForkJoinTasks are mainly |
163 |
|
* responsible for maintaining their "status" field amidst relays |
164 |
< |
* to methods in ForkJoinWorkerThread and ForkJoinPool. The |
165 |
< |
* methods of this class are more-or-less layered into (1) basic |
166 |
< |
* status maintenance (2) execution and awaiting completion (3) |
167 |
< |
* user-level methods that additionally report results. This is |
168 |
< |
* sometimes hard to see because this file orders exported methods |
169 |
< |
* in a way that flows well in javadocs. |
164 |
> |
* to methods in ForkJoinWorkerThread and ForkJoinPool. |
165 |
> |
* |
166 |
> |
* The methods of this class are more-or-less layered into |
167 |
> |
* (1) basic status maintenance |
168 |
> |
* (2) execution and awaiting completion |
169 |
> |
* (3) user-level methods that additionally report results. |
170 |
> |
* This is sometimes hard to see because this file orders exported |
171 |
> |
* methods in a way that flows well in javadocs. |
172 |
|
*/ |
173 |
|
|
174 |
< |
/** |
175 |
< |
* Run control status bits packed into a single int to minimize |
176 |
< |
* footprint and to ensure atomicity (via CAS). Status is |
177 |
< |
* initially zero, and takes on nonnegative values until |
178 |
< |
* completed, upon which status holds COMPLETED. CANCELLED, or |
179 |
< |
* EXCEPTIONAL, which use the top 3 bits. Tasks undergoing |
180 |
< |
* blocking waits by other threads have the SIGNAL bit set. |
181 |
< |
* |
182 |
< |
* Completion of a stolen task with SIGNAL set awakens any waiters |
163 |
< |
* via notifyAll. Even though suboptimal for some purposes, we use |
174 |
> |
/* |
175 |
> |
* The status field holds run control status bits packed into a |
176 |
> |
* single int to minimize footprint and to ensure atomicity (via |
177 |
> |
* CAS). Status is initially zero, and takes on nonnegative |
178 |
> |
* values until completed, upon which status holds value |
179 |
> |
* NORMAL, CANCELLED, or EXCEPTIONAL. Tasks undergoing blocking |
180 |
> |
* waits by other threads have the SIGNAL bit set. Completion of |
181 |
> |
* a stolen task with SIGNAL set awakens any waiters via |
182 |
> |
* notifyAll. Even though suboptimal for some purposes, we use |
183 |
|
* basic builtin wait/notify to take advantage of "monitor |
184 |
|
* inflation" in JVMs that we would otherwise need to emulate to |
185 |
|
* avoid adding further per-task bookkeeping overhead. We want |
186 |
|
* these monitors to be "fat", i.e., not use biasing or thin-lock |
187 |
|
* techniques, so use some odd coding idioms that tend to avoid |
188 |
|
* them. |
170 |
– |
* |
171 |
– |
* Note that bits 1-28 are currently unused. Also value |
172 |
– |
* 0x80000000 is available as spare completion value. |
173 |
– |
*/ |
174 |
– |
volatile int status; // accessed directly by pool and workers |
175 |
– |
|
176 |
– |
private static final int COMPLETION_MASK = 0xe0000000; |
177 |
– |
private static final int NORMAL = 0xe0000000; // == mask |
178 |
– |
private static final int CANCELLED = 0xc0000000; |
179 |
– |
private static final int EXCEPTIONAL = 0xa0000000; |
180 |
– |
private static final int SIGNAL = 0x00000001; |
181 |
– |
|
182 |
– |
/** |
183 |
– |
* Table of exceptions thrown by tasks, to enable reporting by |
184 |
– |
* callers. Because exceptions are rare, we don't directly keep |
185 |
– |
* them with task objects, but instead use a weak ref table. Note |
186 |
– |
* that cancellation exceptions don't appear in the table, but are |
187 |
– |
* instead recorded as status values. |
188 |
– |
* TODO: Use ConcurrentReferenceHashMap |
189 |
|
*/ |
190 |
– |
static final Map<ForkJoinTask<?>, Throwable> exceptionMap = |
191 |
– |
Collections.synchronizedMap |
192 |
– |
(new WeakHashMap<ForkJoinTask<?>, Throwable>()); |
190 |
|
|
191 |
< |
// Maintaining completion status |
191 |
> |
/** The run status of this task */ |
192 |
> |
volatile int status; // accessed directly by pool and workers |
193 |
> |
private static final int NORMAL = -1; |
194 |
> |
private static final int CANCELLED = -2; |
195 |
> |
private static final int EXCEPTIONAL = -3; |
196 |
> |
private static final int SIGNAL = 1; |
197 |
|
|
198 |
|
/** |
199 |
|
* Marks completion and wakes up threads waiting to join this task, |
200 |
|
* also clearing signal request bits. |
201 |
|
* |
202 |
|
* @param completion one of NORMAL, CANCELLED, EXCEPTIONAL |
203 |
< |
* @return status on exit |
203 |
> |
* @return completion status on exit |
204 |
|
*/ |
205 |
|
private int setCompletion(int completion) { |
206 |
< |
int s; |
207 |
< |
while ((s = status) >= 0) { |
206 |
> |
for (int s;;) { |
207 |
> |
if ((s = status) < 0) |
208 |
> |
return s; |
209 |
|
if (UNSAFE.compareAndSwapInt(this, statusOffset, s, completion)) { |
210 |
< |
if ((s & SIGNAL) != 0) |
210 |
> |
if (s != 0) |
211 |
|
synchronized (this) { notifyAll(); } |
212 |
|
return completion; |
213 |
|
} |
214 |
|
} |
212 |
– |
return s; |
215 |
|
} |
216 |
|
|
217 |
|
/** |
218 |
< |
* Record exception and set exceptional completion |
219 |
< |
* @return status on exit |
218 |
> |
* Tries to block a worker thread until completed or timed out. |
219 |
> |
* Uses Object.wait time argument conventions. |
220 |
> |
* May fail on contention or interrupt. |
221 |
> |
* |
222 |
> |
* @param millis if > 0, wait time. |
223 |
|
*/ |
224 |
< |
private int setExceptionalCompletion(Throwable rex) { |
225 |
< |
exceptionMap.put(this, rex); |
226 |
< |
return setCompletion(EXCEPTIONAL); |
224 |
> |
final void tryAwaitDone(long millis) { |
225 |
> |
int s; |
226 |
> |
try { |
227 |
> |
if (((s = status) > 0 || |
228 |
> |
(s == 0 && |
229 |
> |
UNSAFE.compareAndSwapInt(this, statusOffset, 0, SIGNAL))) && |
230 |
> |
status > 0) { |
231 |
> |
synchronized (this) { |
232 |
> |
if (status > 0) |
233 |
> |
wait(millis); |
234 |
> |
} |
235 |
> |
} |
236 |
> |
} catch (InterruptedException ie) { |
237 |
> |
// caller must check termination |
238 |
> |
} |
239 |
|
} |
240 |
|
|
241 |
|
/** |
242 |
< |
* Blocks a worker thread until completion. Called only by pool. |
242 |
> |
* Blocks a non-worker-thread until completion. |
243 |
> |
* @return status upon completion |
244 |
|
*/ |
245 |
< |
final void internalAwaitDone() { |
245 |
> |
private int externalAwaitDone() { |
246 |
|
int s; |
247 |
< |
while ((s = status) >= 0) { |
248 |
< |
synchronized(this) { |
249 |
< |
if (UNSAFE.compareAndSwapInt(this, statusOffset, s, s|SIGNAL)){ |
250 |
< |
do { |
247 |
> |
if ((s = status) >= 0) { |
248 |
> |
boolean interrupted = false; |
249 |
> |
synchronized (this) { |
250 |
> |
while ((s = status) >= 0) { |
251 |
> |
if (s == 0) |
252 |
> |
UNSAFE.compareAndSwapInt(this, statusOffset, |
253 |
> |
0, SIGNAL); |
254 |
> |
else { |
255 |
|
try { |
256 |
|
wait(); |
257 |
|
} catch (InterruptedException ie) { |
258 |
< |
cancelIfTerminating(); |
258 |
> |
interrupted = true; |
259 |
|
} |
260 |
< |
} while (status >= 0); |
239 |
< |
break; |
260 |
> |
} |
261 |
|
} |
262 |
|
} |
263 |
+ |
if (interrupted) |
264 |
+ |
Thread.currentThread().interrupt(); |
265 |
|
} |
266 |
+ |
return s; |
267 |
|
} |
268 |
|
|
269 |
|
/** |
270 |
< |
* Blocks a non-worker-thread until completion. |
247 |
< |
* @return status on exit |
270 |
> |
* Blocks a non-worker-thread until completion or interruption or timeout. |
271 |
|
*/ |
272 |
< |
private int externalAwaitDone() { |
272 |
> |
private int externalInterruptibleAwaitDone(long millis) |
273 |
> |
throws InterruptedException { |
274 |
|
int s; |
275 |
< |
while ((s = status) >= 0) { |
276 |
< |
synchronized(this) { |
277 |
< |
if (UNSAFE.compareAndSwapInt(this, statusOffset, s, s|SIGNAL)){ |
278 |
< |
boolean interrupted = false; |
279 |
< |
do { |
280 |
< |
try { |
281 |
< |
wait(); |
282 |
< |
} catch (InterruptedException ie) { |
283 |
< |
interrupted = true; |
284 |
< |
} |
285 |
< |
} while ((s = status) >= 0); |
286 |
< |
if (interrupted) |
287 |
< |
Thread.currentThread().interrupt(); |
264 |
< |
break; |
275 |
> |
if (Thread.interrupted()) |
276 |
> |
throw new InterruptedException(); |
277 |
> |
if ((s = status) >= 0) { |
278 |
> |
synchronized (this) { |
279 |
> |
while ((s = status) >= 0) { |
280 |
> |
if (s == 0) |
281 |
> |
UNSAFE.compareAndSwapInt(this, statusOffset, |
282 |
> |
0, SIGNAL); |
283 |
> |
else { |
284 |
> |
wait(millis); |
285 |
> |
if (millis > 0L) |
286 |
> |
break; |
287 |
> |
} |
288 |
|
} |
289 |
|
} |
290 |
|
} |
292 |
|
} |
293 |
|
|
294 |
|
/** |
295 |
< |
* Unless done, calls exec and records status if completed, but |
296 |
< |
* doesn't wait for completion otherwise. |
295 |
> |
* Primary execution method for stolen tasks. Unless done, calls |
296 |
> |
* exec and records status if completed, but doesn't wait for |
297 |
> |
* completion otherwise. |
298 |
|
*/ |
299 |
< |
final void tryExec() { |
300 |
< |
try { |
301 |
< |
if (status < 0 || !exec()) |
299 |
> |
final void doExec() { |
300 |
> |
if (status >= 0) { |
301 |
> |
boolean completed; |
302 |
> |
try { |
303 |
> |
completed = exec(); |
304 |
> |
} catch (Throwable rex) { |
305 |
> |
setExceptionalCompletion(rex); |
306 |
|
return; |
307 |
< |
} catch (Throwable rex) { |
308 |
< |
setExceptionalCompletion(rex); |
309 |
< |
return; |
307 |
> |
} |
308 |
> |
if (completed) |
309 |
> |
setCompletion(NORMAL); // must be outside try block |
310 |
|
} |
283 |
– |
setCompletion(NORMAL); // must be outside try block |
311 |
|
} |
312 |
|
|
313 |
|
/** |
314 |
< |
* If not done and this task is next in worker queue, runs it, |
315 |
< |
* else waits for it. |
289 |
< |
* @return status on exit |
314 |
> |
* Primary mechanics for join, get, quietlyJoin. |
315 |
> |
* @return status upon completion |
316 |
|
*/ |
317 |
< |
private int waitingJoin() { |
318 |
< |
int s = status; |
319 |
< |
if (s < 0) |
320 |
< |
return s; |
321 |
< |
Thread t = Thread.currentThread(); |
322 |
< |
if (t instanceof ForkJoinWorkerThread) { |
297 |
< |
ForkJoinWorkerThread w = (ForkJoinWorkerThread) t; |
298 |
< |
if (w.unpushTask(this)) { |
299 |
< |
boolean completed; |
317 |
> |
private int doJoin() { |
318 |
> |
Thread t; ForkJoinWorkerThread w; int s; boolean completed; |
319 |
> |
if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) { |
320 |
> |
if ((s = status) < 0) |
321 |
> |
return s; |
322 |
> |
if ((w = (ForkJoinWorkerThread)t).unpushTask(this)) { |
323 |
|
try { |
324 |
|
completed = exec(); |
325 |
|
} catch (Throwable rex) { |
328 |
|
if (completed) |
329 |
|
return setCompletion(NORMAL); |
330 |
|
} |
331 |
< |
return w.pool.awaitJoin(this); |
331 |
> |
return w.joinTask(this); |
332 |
|
} |
333 |
|
else |
334 |
|
return externalAwaitDone(); |
335 |
|
} |
336 |
|
|
337 |
|
/** |
338 |
< |
* Unless done, calls exec and records status if completed, or |
339 |
< |
* waits for completion otherwise. |
317 |
< |
* @return status on exit |
338 |
> |
* Primary mechanics for invoke, quietlyInvoke. |
339 |
> |
* @return status upon completion |
340 |
|
*/ |
341 |
< |
private int waitingInvoke() { |
342 |
< |
int s = status; |
343 |
< |
if (s < 0) |
341 |
> |
private int doInvoke() { |
342 |
> |
int s; boolean completed; |
343 |
> |
if ((s = status) < 0) |
344 |
|
return s; |
323 |
– |
boolean completed; |
345 |
|
try { |
346 |
|
completed = exec(); |
347 |
|
} catch (Throwable rex) { |
349 |
|
} |
350 |
|
if (completed) |
351 |
|
return setCompletion(NORMAL); |
352 |
< |
return waitingJoin(); |
352 |
> |
else |
353 |
> |
return doJoin(); |
354 |
> |
} |
355 |
> |
|
356 |
> |
// Exception table support |
357 |
> |
|
358 |
> |
/** |
359 |
> |
* Table of exceptions thrown by tasks, to enable reporting by |
360 |
> |
* callers. Because exceptions are rare, we don't directly keep |
361 |
> |
* them with task objects, but instead use a weak ref table. Note |
362 |
> |
* that cancellation exceptions don't appear in the table, but are |
363 |
> |
* instead recorded as status values. |
364 |
> |
* |
365 |
> |
* Note: These statics are initialized below in static block. |
366 |
> |
*/ |
367 |
> |
private static final ExceptionNode[] exceptionTable; |
368 |
> |
private static final ReentrantLock exceptionTableLock; |
369 |
> |
private static final ReferenceQueue<Object> exceptionTableRefQueue; |
370 |
> |
|
371 |
> |
/** |
372 |
> |
* Fixed capacity for exceptionTable. |
373 |
> |
*/ |
374 |
> |
private static final int EXCEPTION_MAP_CAPACITY = 32; |
375 |
> |
|
376 |
> |
/** |
377 |
> |
* Key-value nodes for exception table. The chained hash table |
378 |
> |
* uses identity comparisons, full locking, and weak references |
379 |
> |
* for keys. The table has a fixed capacity because it only |
380 |
> |
* maintains task exceptions long enough for joiners to access |
381 |
> |
* them, so should never become very large for sustained |
382 |
> |
* periods. However, since we do not know when the last joiner |
383 |
> |
* completes, we must use weak references and expunge them. We do |
384 |
> |
* so on each operation (hence full locking). Also, some thread in |
385 |
> |
* any ForkJoinPool will call helpExpungeStaleExceptions when its |
386 |
> |
* pool becomes isQuiescent. |
387 |
> |
*/ |
388 |
> |
static final class ExceptionNode extends WeakReference<ForkJoinTask<?>>{ |
389 |
> |
final Throwable ex; |
390 |
> |
ExceptionNode next; |
391 |
> |
final long thrower; // use id not ref to avoid weak cycles |
392 |
> |
ExceptionNode(ForkJoinTask<?> task, Throwable ex, ExceptionNode next) { |
393 |
> |
super(task, exceptionTableRefQueue); |
394 |
> |
this.ex = ex; |
395 |
> |
this.next = next; |
396 |
> |
this.thrower = Thread.currentThread().getId(); |
397 |
> |
} |
398 |
|
} |
399 |
|
|
400 |
|
/** |
401 |
< |
* If this task is next in worker queue, runs it, else processes other |
402 |
< |
* tasks until complete. |
401 |
> |
* Records exception and sets exceptional completion. |
402 |
> |
* |
403 |
|
* @return status on exit |
404 |
|
*/ |
405 |
< |
private int busyJoin() { |
406 |
< |
int s = status; |
407 |
< |
if (s < 0) |
408 |
< |
return s; |
409 |
< |
ForkJoinWorkerThread w = (ForkJoinWorkerThread) Thread.currentThread(); |
410 |
< |
if (w.unpushTask(this)) { |
411 |
< |
boolean completed; |
412 |
< |
try { |
413 |
< |
completed = exec(); |
414 |
< |
} catch (Throwable rex) { |
415 |
< |
return setExceptionalCompletion(rex); |
405 |
> |
private int setExceptionalCompletion(Throwable ex) { |
406 |
> |
int h = System.identityHashCode(this); |
407 |
> |
final ReentrantLock lock = exceptionTableLock; |
408 |
> |
lock.lock(); |
409 |
> |
try { |
410 |
> |
expungeStaleExceptions(); |
411 |
> |
ExceptionNode[] t = exceptionTable; |
412 |
> |
int i = h & (t.length - 1); |
413 |
> |
for (ExceptionNode e = t[i]; ; e = e.next) { |
414 |
> |
if (e == null) { |
415 |
> |
t[i] = new ExceptionNode(this, ex, t[i]); |
416 |
> |
break; |
417 |
> |
} |
418 |
> |
if (e.get() == this) // already present |
419 |
> |
break; |
420 |
|
} |
421 |
< |
if (completed) |
422 |
< |
return setCompletion(NORMAL); |
421 |
> |
} finally { |
422 |
> |
lock.unlock(); |
423 |
|
} |
424 |
< |
return w.execWhileJoining(this); |
424 |
> |
return setCompletion(EXCEPTIONAL); |
425 |
|
} |
426 |
|
|
427 |
|
/** |
428 |
< |
* Returns result or throws exception associated with given status. |
359 |
< |
* @param s the status |
428 |
> |
* Removes exception node and clears status |
429 |
|
*/ |
430 |
< |
private V reportResult(int s) { |
430 |
> |
private void clearExceptionalCompletion() { |
431 |
> |
int h = System.identityHashCode(this); |
432 |
> |
final ReentrantLock lock = exceptionTableLock; |
433 |
> |
lock.lock(); |
434 |
> |
try { |
435 |
> |
ExceptionNode[] t = exceptionTable; |
436 |
> |
int i = h & (t.length - 1); |
437 |
> |
ExceptionNode e = t[i]; |
438 |
> |
ExceptionNode pred = null; |
439 |
> |
while (e != null) { |
440 |
> |
ExceptionNode next = e.next; |
441 |
> |
if (e.get() == this) { |
442 |
> |
if (pred == null) |
443 |
> |
t[i] = next; |
444 |
> |
else |
445 |
> |
pred.next = next; |
446 |
> |
break; |
447 |
> |
} |
448 |
> |
pred = e; |
449 |
> |
e = next; |
450 |
> |
} |
451 |
> |
expungeStaleExceptions(); |
452 |
> |
status = 0; |
453 |
> |
} finally { |
454 |
> |
lock.unlock(); |
455 |
> |
} |
456 |
> |
} |
457 |
> |
|
458 |
> |
/** |
459 |
> |
* Returns a rethrowable exception for the given task, if |
460 |
> |
* available. To provide accurate stack traces, if the exception |
461 |
> |
* was not thrown by the current thread, we try to create a new |
462 |
> |
* exception of the same type as the one thrown, but with the |
463 |
> |
* recorded exception as its cause. If there is no such |
464 |
> |
* constructor, we instead try to use a no-arg constructor, |
465 |
> |
* followed by initCause, to the same effect. If none of these |
466 |
> |
* apply, or any fail due to other exceptions, we return the |
467 |
> |
* recorded exception, which is still correct, although it may |
468 |
> |
* contain a misleading stack trace. |
469 |
> |
* |
470 |
> |
* @return the exception, or null if none |
471 |
> |
*/ |
472 |
> |
private Throwable getThrowableException() { |
473 |
> |
if (status != EXCEPTIONAL) |
474 |
> |
return null; |
475 |
> |
int h = System.identityHashCode(this); |
476 |
> |
ExceptionNode e; |
477 |
> |
final ReentrantLock lock = exceptionTableLock; |
478 |
> |
lock.lock(); |
479 |
> |
try { |
480 |
> |
expungeStaleExceptions(); |
481 |
> |
ExceptionNode[] t = exceptionTable; |
482 |
> |
e = t[h & (t.length - 1)]; |
483 |
> |
while (e != null && e.get() != this) |
484 |
> |
e = e.next; |
485 |
> |
} finally { |
486 |
> |
lock.unlock(); |
487 |
> |
} |
488 |
|
Throwable ex; |
489 |
< |
if (s < NORMAL && (ex = getException()) != null) |
489 |
> |
if (e == null || (ex = e.ex) == null) |
490 |
> |
return null; |
491 |
> |
if (e.thrower != Thread.currentThread().getId()) { |
492 |
> |
Class<? extends Throwable> ec = ex.getClass(); |
493 |
> |
try { |
494 |
> |
Constructor<?> noArgCtor = null; |
495 |
> |
Constructor<?>[] cs = ec.getConstructors();// public ctors only |
496 |
> |
for (int i = 0; i < cs.length; ++i) { |
497 |
> |
Constructor<?> c = cs[i]; |
498 |
> |
Class<?>[] ps = c.getParameterTypes(); |
499 |
> |
if (ps.length == 0) |
500 |
> |
noArgCtor = c; |
501 |
> |
else if (ps.length == 1 && ps[0] == Throwable.class) |
502 |
> |
return (Throwable)(c.newInstance(ex)); |
503 |
> |
} |
504 |
> |
if (noArgCtor != null) { |
505 |
> |
Throwable wx = (Throwable)(noArgCtor.newInstance()); |
506 |
> |
wx.initCause(ex); |
507 |
> |
return wx; |
508 |
> |
} |
509 |
> |
} catch (Exception ignore) { |
510 |
> |
} |
511 |
> |
} |
512 |
> |
return ex; |
513 |
> |
} |
514 |
> |
|
515 |
> |
/** |
516 |
> |
* Poll stale refs and remove them. Call only while holding lock. |
517 |
> |
*/ |
518 |
> |
private static void expungeStaleExceptions() { |
519 |
> |
for (Object x; (x = exceptionTableRefQueue.poll()) != null;) { |
520 |
> |
if (x instanceof ExceptionNode) { |
521 |
> |
ForkJoinTask<?> key = ((ExceptionNode)x).get(); |
522 |
> |
ExceptionNode[] t = exceptionTable; |
523 |
> |
int i = System.identityHashCode(key) & (t.length - 1); |
524 |
> |
ExceptionNode e = t[i]; |
525 |
> |
ExceptionNode pred = null; |
526 |
> |
while (e != null) { |
527 |
> |
ExceptionNode next = e.next; |
528 |
> |
if (e == x) { |
529 |
> |
if (pred == null) |
530 |
> |
t[i] = next; |
531 |
> |
else |
532 |
> |
pred.next = next; |
533 |
> |
break; |
534 |
> |
} |
535 |
> |
pred = e; |
536 |
> |
e = next; |
537 |
> |
} |
538 |
> |
} |
539 |
> |
} |
540 |
> |
} |
541 |
> |
|
542 |
> |
/** |
543 |
> |
* If lock is available, poll stale refs and remove them. |
544 |
> |
* Called from ForkJoinPool when pools become quiescent. |
545 |
> |
*/ |
546 |
> |
static final void helpExpungeStaleExceptions() { |
547 |
> |
final ReentrantLock lock = exceptionTableLock; |
548 |
> |
if (lock.tryLock()) { |
549 |
> |
try { |
550 |
> |
expungeStaleExceptions(); |
551 |
> |
} finally { |
552 |
> |
lock.unlock(); |
553 |
> |
} |
554 |
> |
} |
555 |
> |
} |
556 |
> |
|
557 |
> |
/** |
558 |
> |
* Report the result of invoke or join; called only upon |
559 |
> |
* non-normal return of internal versions. |
560 |
> |
*/ |
561 |
> |
private V reportResult() { |
562 |
> |
int s; Throwable ex; |
563 |
> |
if ((s = status) == CANCELLED) |
564 |
> |
throw new CancellationException(); |
565 |
> |
if (s == EXCEPTIONAL && (ex = getThrowableException()) != null) |
566 |
|
UNSAFE.throwException(ex); |
567 |
|
return getRawResult(); |
568 |
|
} |
580 |
|
* #isDone} returning {@code true}. |
581 |
|
* |
582 |
|
* <p>This method may be invoked only from within {@code |
583 |
< |
* ForkJoinTask} computations (as may be determined using method |
583 |
> |
* ForkJoinPool} computations (as may be determined using method |
584 |
|
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
585 |
|
* result in exceptions or errors, possibly including {@code |
586 |
|
* ClassCastException}. |
594 |
|
} |
595 |
|
|
596 |
|
/** |
597 |
< |
* Returns the result of the computation when it {@link #isDone is done}. |
598 |
< |
* This method differs from {@link #get()} in that |
597 |
> |
* Returns the result of the computation when it {@link #isDone is |
598 |
> |
* done}. This method differs from {@link #get()} in that |
599 |
|
* abnormal completion results in {@code RuntimeException} or |
600 |
< |
* {@code Error}, not {@code ExecutionException}. |
600 |
> |
* {@code Error}, not {@code ExecutionException}, and that |
601 |
> |
* interrupts of the calling thread do <em>not</em> cause the |
602 |
> |
* method to abruptly return by throwing {@code |
603 |
> |
* InterruptedException}. |
604 |
|
* |
605 |
|
* @return the computed result |
606 |
|
*/ |
607 |
|
public final V join() { |
608 |
< |
return reportResult(waitingJoin()); |
608 |
> |
if (doJoin() != NORMAL) |
609 |
> |
return reportResult(); |
610 |
> |
else |
611 |
> |
return getRawResult(); |
612 |
|
} |
613 |
|
|
614 |
|
/** |
615 |
|
* Commences performing this task, awaits its completion if |
616 |
< |
* necessary, and return its result, or throws an (unchecked) |
617 |
< |
* exception if the underlying computation did so. |
616 |
> |
* necessary, and returns its result, or throws an (unchecked) |
617 |
> |
* {@code RuntimeException} or {@code Error} if the underlying |
618 |
> |
* computation did so. |
619 |
|
* |
620 |
|
* @return the computed result |
621 |
|
*/ |
622 |
|
public final V invoke() { |
623 |
< |
return reportResult(waitingInvoke()); |
623 |
> |
if (doInvoke() != NORMAL) |
624 |
> |
return reportResult(); |
625 |
> |
else |
626 |
> |
return getRawResult(); |
627 |
|
} |
628 |
|
|
629 |
|
/** |
630 |
|
* Forks the given tasks, returning when {@code isDone} holds for |
631 |
|
* each task or an (unchecked) exception is encountered, in which |
632 |
< |
* case the exception is rethrown. If either task encounters an |
633 |
< |
* exception, the other one may be, but is not guaranteed to be, |
634 |
< |
* cancelled. If both tasks throw an exception, then this method |
635 |
< |
* throws one of them. The individual status of each task may be |
636 |
< |
* checked using {@link #getException()} and related methods. |
632 |
> |
* case the exception is rethrown. If more than one task |
633 |
> |
* encounters an exception, then this method throws any one of |
634 |
> |
* these exceptions. If any task encounters an exception, the |
635 |
> |
* other may be cancelled. However, the execution status of |
636 |
> |
* individual tasks is not guaranteed upon exceptional return. The |
637 |
> |
* status of each task may be obtained using {@link |
638 |
> |
* #getException()} and related methods to check if they have been |
639 |
> |
* cancelled, completed normally or exceptionally, or left |
640 |
> |
* unprocessed. |
641 |
|
* |
642 |
|
* <p>This method may be invoked only from within {@code |
643 |
< |
* ForkJoinTask} computations (as may be determined using method |
643 |
> |
* ForkJoinPool} computations (as may be determined using method |
644 |
|
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
645 |
|
* result in exceptions or errors, possibly including {@code |
646 |
|
* ClassCastException}. |
658 |
|
/** |
659 |
|
* Forks the given tasks, returning when {@code isDone} holds for |
660 |
|
* each task or an (unchecked) exception is encountered, in which |
661 |
< |
* case the exception is rethrown. If any task encounters an |
662 |
< |
* exception, others may be, but are not guaranteed to be, |
663 |
< |
* cancelled. If more than one task encounters an exception, then |
664 |
< |
* this method throws any one of these exceptions. The individual |
665 |
< |
* status of each task may be checked using {@link #getException()} |
666 |
< |
* and related methods. |
661 |
> |
* case the exception is rethrown. If more than one task |
662 |
> |
* encounters an exception, then this method throws any one of |
663 |
> |
* these exceptions. If any task encounters an exception, others |
664 |
> |
* may be cancelled. However, the execution status of individual |
665 |
> |
* tasks is not guaranteed upon exceptional return. The status of |
666 |
> |
* each task may be obtained using {@link #getException()} and |
667 |
> |
* related methods to check if they have been cancelled, completed |
668 |
> |
* normally or exceptionally, or left unprocessed. |
669 |
|
* |
670 |
|
* <p>This method may be invoked only from within {@code |
671 |
< |
* ForkJoinTask} computations (as may be determined using method |
671 |
> |
* ForkJoinPool} computations (as may be determined using method |
672 |
|
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
673 |
|
* result in exceptions or errors, possibly including {@code |
674 |
|
* ClassCastException}. |
687 |
|
} |
688 |
|
else if (i != 0) |
689 |
|
t.fork(); |
690 |
< |
else if (t.waitingInvoke() < NORMAL && ex == null) |
690 |
> |
else if (t.doInvoke() < NORMAL && ex == null) |
691 |
|
ex = t.getException(); |
692 |
|
} |
693 |
|
for (int i = 1; i <= last; ++i) { |
695 |
|
if (t != null) { |
696 |
|
if (ex != null) |
697 |
|
t.cancel(false); |
698 |
< |
else if (t.waitingJoin() < NORMAL && ex == null) |
698 |
> |
else if (t.doJoin() < NORMAL) |
699 |
|
ex = t.getException(); |
700 |
|
} |
701 |
|
} |
706 |
|
/** |
707 |
|
* Forks all tasks in the specified collection, returning when |
708 |
|
* {@code isDone} holds for each task or an (unchecked) exception |
709 |
< |
* is encountered. If any task encounters an exception, others |
710 |
< |
* may be, but are not guaranteed to be, cancelled. If more than |
711 |
< |
* one task encounters an exception, then this method throws any |
712 |
< |
* one of these exceptions. The individual status of each task |
713 |
< |
* may be checked using {@link #getException()} and related |
714 |
< |
* methods. The behavior of this operation is undefined if the |
715 |
< |
* specified collection is modified while the operation is in |
716 |
< |
* progress. |
709 |
> |
* is encountered, in which case the exception is rethrown. If |
710 |
> |
* more than one task encounters an exception, then this method |
711 |
> |
* throws any one of these exceptions. If any task encounters an |
712 |
> |
* exception, others may be cancelled. However, the execution |
713 |
> |
* status of individual tasks is not guaranteed upon exceptional |
714 |
> |
* return. The status of each task may be obtained using {@link |
715 |
> |
* #getException()} and related methods to check if they have been |
716 |
> |
* cancelled, completed normally or exceptionally, or left |
717 |
> |
* unprocessed. |
718 |
|
* |
719 |
|
* <p>This method may be invoked only from within {@code |
720 |
< |
* ForkJoinTask} computations (as may be determined using method |
720 |
> |
* ForkJoinPool} computations (as may be determined using method |
721 |
|
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
722 |
|
* result in exceptions or errors, possibly including {@code |
723 |
|
* ClassCastException}. |
744 |
|
} |
745 |
|
else if (i != 0) |
746 |
|
t.fork(); |
747 |
< |
else if (t.waitingInvoke() < NORMAL && ex == null) |
747 |
> |
else if (t.doInvoke() < NORMAL && ex == null) |
748 |
|
ex = t.getException(); |
749 |
|
} |
750 |
|
for (int i = 1; i <= last; ++i) { |
752 |
|
if (t != null) { |
753 |
|
if (ex != null) |
754 |
|
t.cancel(false); |
755 |
< |
else if (t.waitingJoin() < NORMAL && ex == null) |
755 |
> |
else if (t.doJoin() < NORMAL) |
756 |
|
ex = t.getException(); |
757 |
|
} |
758 |
|
} |
763 |
|
|
764 |
|
/** |
765 |
|
* Attempts to cancel execution of this task. This attempt will |
766 |
< |
* fail if the task has already completed, has already been |
767 |
< |
* cancelled, or could not be cancelled for some other reason. If |
768 |
< |
* successful, and this task has not started when cancel is |
769 |
< |
* called, execution of this task is suppressed, {@link |
770 |
< |
* #isCancelled} will report true, and {@link #join} will result |
771 |
< |
* in a {@code CancellationException} being thrown. |
766 |
> |
* fail if the task has already completed or could not be |
767 |
> |
* cancelled for some other reason. If successful, and this task |
768 |
> |
* has not started when {@code cancel} is called, execution of |
769 |
> |
* this task is suppressed. After this method returns |
770 |
> |
* successfully, unless there is an intervening call to {@link |
771 |
> |
* #reinitialize}, subsequent calls to {@link #isCancelled}, |
772 |
> |
* {@link #isDone}, and {@code cancel} will return {@code true} |
773 |
> |
* and calls to {@link #join} and related methods will result in |
774 |
> |
* {@code CancellationException}. |
775 |
|
* |
776 |
|
* <p>This method may be overridden in subclasses, but if so, must |
777 |
< |
* still ensure that these minimal properties hold. In particular, |
778 |
< |
* the {@code cancel} method itself must not throw exceptions. |
777 |
> |
* still ensure that these properties hold. In particular, the |
778 |
> |
* {@code cancel} method itself must not throw exceptions. |
779 |
|
* |
780 |
|
* <p>This method is designed to be invoked by <em>other</em> |
781 |
|
* tasks. To terminate the current task, you can just return or |
782 |
|
* throw an unchecked exception from its computation method, or |
783 |
|
* invoke {@link #completeExceptionally}. |
784 |
|
* |
785 |
< |
* @param mayInterruptIfRunning this value is ignored in the |
786 |
< |
* default implementation because tasks are not |
787 |
< |
* cancelled via interruption |
785 |
> |
* @param mayInterruptIfRunning this value has no effect in the |
786 |
> |
* default implementation because interrupts are not used to |
787 |
> |
* control cancellation. |
788 |
|
* |
789 |
|
* @return {@code true} if this task is now cancelled |
790 |
|
*/ |
791 |
|
public boolean cancel(boolean mayInterruptIfRunning) { |
792 |
< |
setCompletion(CANCELLED); |
571 |
< |
return (status & COMPLETION_MASK) == CANCELLED; |
792 |
> |
return setCompletion(CANCELLED) == CANCELLED; |
793 |
|
} |
794 |
|
|
795 |
|
/** |
796 |
< |
* Cancels, ignoring any exceptions it throws. Used during worker |
797 |
< |
* and pool shutdown. |
796 |
> |
* Cancels, ignoring any exceptions thrown by cancel. Used during |
797 |
> |
* worker and pool shutdown. Cancel is spec'ed not to throw any |
798 |
> |
* exceptions, but if it does anyway, we have no recourse during |
799 |
> |
* shutdown, so guard against this case. |
800 |
|
*/ |
801 |
|
final void cancelIgnoringExceptions() { |
802 |
|
try { |
805 |
|
} |
806 |
|
} |
807 |
|
|
585 |
– |
/** |
586 |
– |
* Cancels ignoring exceptions if worker is terminating |
587 |
– |
*/ |
588 |
– |
private void cancelIfTerminating() { |
589 |
– |
Thread t = Thread.currentThread(); |
590 |
– |
if ((t instanceof ForkJoinWorkerThread) && |
591 |
– |
((ForkJoinWorkerThread) t).isTerminating()) { |
592 |
– |
try { |
593 |
– |
cancel(false); |
594 |
– |
} catch (Throwable ignore) { |
595 |
– |
} |
596 |
– |
} |
597 |
– |
} |
598 |
– |
|
808 |
|
public final boolean isDone() { |
809 |
|
return status < 0; |
810 |
|
} |
811 |
|
|
812 |
|
public final boolean isCancelled() { |
813 |
< |
return (status & COMPLETION_MASK) == CANCELLED; |
813 |
> |
return status == CANCELLED; |
814 |
|
} |
815 |
|
|
816 |
|
/** |
819 |
|
* @return {@code true} if this task threw an exception or was cancelled |
820 |
|
*/ |
821 |
|
public final boolean isCompletedAbnormally() { |
822 |
< |
return (status & COMPLETION_MASK) < NORMAL; |
822 |
> |
return status < NORMAL; |
823 |
|
} |
824 |
|
|
825 |
|
/** |
830 |
|
* exception and was not cancelled |
831 |
|
*/ |
832 |
|
public final boolean isCompletedNormally() { |
833 |
< |
return (status & COMPLETION_MASK) == NORMAL; |
833 |
> |
return status == NORMAL; |
834 |
|
} |
835 |
|
|
836 |
|
/** |
841 |
|
* @return the exception, or {@code null} if none |
842 |
|
*/ |
843 |
|
public final Throwable getException() { |
844 |
< |
int s = status & COMPLETION_MASK; |
844 |
> |
int s = status; |
845 |
|
return ((s >= NORMAL) ? null : |
846 |
|
(s == CANCELLED) ? new CancellationException() : |
847 |
< |
exceptionMap.get(this)); |
847 |
> |
getThrowableException()); |
848 |
|
} |
849 |
|
|
850 |
|
/** |
869 |
|
|
870 |
|
/** |
871 |
|
* Completes this task, and if not already aborted or cancelled, |
872 |
< |
* returning a {@code null} result upon {@code join} and related |
873 |
< |
* operations. This method may be used to provide results for |
874 |
< |
* asynchronous tasks, or to provide alternative handling for |
875 |
< |
* tasks that would not otherwise complete normally. Its use in |
876 |
< |
* other situations is discouraged. This method is |
877 |
< |
* overridable, but overridden versions must invoke {@code super} |
878 |
< |
* implementation to maintain guarantees. |
872 |
> |
* returning the given value as the result of subsequent |
873 |
> |
* invocations of {@code join} and related operations. This method |
874 |
> |
* may be used to provide results for asynchronous tasks, or to |
875 |
> |
* provide alternative handling for tasks that would not otherwise |
876 |
> |
* complete normally. Its use in other situations is |
877 |
> |
* discouraged. This method is overridable, but overridden |
878 |
> |
* versions must invoke {@code super} implementation to maintain |
879 |
> |
* guarantees. |
880 |
|
* |
881 |
|
* @param value the result value for this task |
882 |
|
*/ |
890 |
|
setCompletion(NORMAL); |
891 |
|
} |
892 |
|
|
893 |
+ |
/** |
894 |
+ |
* Waits if necessary for the computation to complete, and then |
895 |
+ |
* retrieves its result. |
896 |
+ |
* |
897 |
+ |
* @return the computed result |
898 |
+ |
* @throws CancellationException if the computation was cancelled |
899 |
+ |
* @throws ExecutionException if the computation threw an |
900 |
+ |
* exception |
901 |
+ |
* @throws InterruptedException if the current thread is not a |
902 |
+ |
* member of a ForkJoinPool and was interrupted while waiting |
903 |
+ |
*/ |
904 |
|
public final V get() throws InterruptedException, ExecutionException { |
905 |
< |
int s = waitingJoin() & COMPLETION_MASK; |
906 |
< |
if (Thread.interrupted()) |
907 |
< |
throw new InterruptedException(); |
908 |
< |
if (s < NORMAL) { |
909 |
< |
Throwable ex; |
910 |
< |
if (s == CANCELLED) |
911 |
< |
throw new CancellationException(); |
691 |
< |
if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null) |
692 |
< |
throw new ExecutionException(ex); |
693 |
< |
} |
905 |
> |
int s = (Thread.currentThread() instanceof ForkJoinWorkerThread) ? |
906 |
> |
doJoin() : externalInterruptibleAwaitDone(0L); |
907 |
> |
Throwable ex; |
908 |
> |
if (s == CANCELLED) |
909 |
> |
throw new CancellationException(); |
910 |
> |
if (s == EXCEPTIONAL && (ex = getThrowableException()) != null) |
911 |
> |
throw new ExecutionException(ex); |
912 |
|
return getRawResult(); |
913 |
|
} |
914 |
|
|
915 |
+ |
/** |
916 |
+ |
* Waits if necessary for at most the given time for the computation |
917 |
+ |
* to complete, and then retrieves its result, if available. |
918 |
+ |
* |
919 |
+ |
* @param timeout the maximum time to wait |
920 |
+ |
* @param unit the time unit of the timeout argument |
921 |
+ |
* @return the computed result |
922 |
+ |
* @throws CancellationException if the computation was cancelled |
923 |
+ |
* @throws ExecutionException if the computation threw an |
924 |
+ |
* exception |
925 |
+ |
* @throws InterruptedException if the current thread is not a |
926 |
+ |
* member of a ForkJoinPool and was interrupted while waiting |
927 |
+ |
* @throws TimeoutException if the wait timed out |
928 |
+ |
*/ |
929 |
|
public final V get(long timeout, TimeUnit unit) |
930 |
|
throws InterruptedException, ExecutionException, TimeoutException { |
931 |
|
Thread t = Thread.currentThread(); |
700 |
– |
ForkJoinPool pool; |
932 |
|
if (t instanceof ForkJoinWorkerThread) { |
933 |
|
ForkJoinWorkerThread w = (ForkJoinWorkerThread) t; |
934 |
< |
if (status >= 0 && w.unpushTask(this)) |
935 |
< |
tryExec(); |
936 |
< |
pool = w.pool; |
937 |
< |
} |
938 |
< |
else |
939 |
< |
pool = null; |
940 |
< |
/* |
941 |
< |
* Timed wait loop intermixes cases for fj (pool != null) and |
711 |
< |
* non FJ threads. For FJ, decrement pool count but don't try |
712 |
< |
* for replacement; increment count on completion. For non-FJ, |
713 |
< |
* deal with interrupts. This is messy, but a little less so |
714 |
< |
* than is splitting the FJ and nonFJ cases. |
715 |
< |
*/ |
716 |
< |
boolean interrupted = false; |
717 |
< |
boolean dec = false; // true if pool count decremented |
718 |
< |
for (;;) { |
719 |
< |
if (Thread.interrupted() && pool == null) { |
720 |
< |
interrupted = true; |
721 |
< |
break; |
722 |
< |
} |
723 |
< |
int s = status; |
724 |
< |
if (s < 0) |
725 |
< |
break; |
726 |
< |
if (UNSAFE.compareAndSwapInt(this, statusOffset, |
727 |
< |
s, s | SIGNAL)) { |
728 |
< |
long startTime = System.nanoTime(); |
729 |
< |
long nanos = unit.toNanos(timeout); |
730 |
< |
long nt; // wait time |
731 |
< |
while (status >= 0 && |
732 |
< |
(nt = nanos - (System.nanoTime() - startTime)) > 0) { |
733 |
< |
if (pool != null && !dec) |
734 |
< |
dec = pool.tryDecrementRunningCount(); |
735 |
< |
else { |
736 |
< |
long ms = nt / 1000000; |
737 |
< |
int ns = (int) (nt % 1000000); |
738 |
< |
try { |
739 |
< |
synchronized(this) { |
740 |
< |
if (status >= 0) |
741 |
< |
wait(ms, ns); |
742 |
< |
} |
743 |
< |
} catch (InterruptedException ie) { |
744 |
< |
if (pool != null) |
745 |
< |
cancelIfTerminating(); |
746 |
< |
else { |
747 |
< |
interrupted = true; |
748 |
< |
break; |
749 |
< |
} |
750 |
< |
} |
934 |
> |
long nanos = unit.toNanos(timeout); |
935 |
> |
if (status >= 0) { |
936 |
> |
boolean completed = false; |
937 |
> |
if (w.unpushTask(this)) { |
938 |
> |
try { |
939 |
> |
completed = exec(); |
940 |
> |
} catch (Throwable rex) { |
941 |
> |
setExceptionalCompletion(rex); |
942 |
|
} |
943 |
|
} |
944 |
< |
break; |
944 |
> |
if (completed) |
945 |
> |
setCompletion(NORMAL); |
946 |
> |
else if (status >= 0 && nanos > 0) |
947 |
> |
w.pool.timedAwaitJoin(this, nanos); |
948 |
|
} |
949 |
|
} |
950 |
< |
if (pool != null && dec) |
951 |
< |
pool.updateRunningCount(1); |
952 |
< |
if (interrupted) |
953 |
< |
throw new InterruptedException(); |
954 |
< |
int es = status & COMPLETION_MASK; |
955 |
< |
if (es != NORMAL) { |
950 |
> |
else { |
951 |
> |
long millis = unit.toMillis(timeout); |
952 |
> |
if (millis > 0) |
953 |
> |
externalInterruptibleAwaitDone(millis); |
954 |
> |
} |
955 |
> |
int s = status; |
956 |
> |
if (s != NORMAL) { |
957 |
|
Throwable ex; |
958 |
< |
if (es == CANCELLED) |
958 |
> |
if (s == CANCELLED) |
959 |
|
throw new CancellationException(); |
960 |
< |
if (es == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null) |
960 |
> |
if (s != EXCEPTIONAL) |
961 |
> |
throw new TimeoutException(); |
962 |
> |
if ((ex = getThrowableException()) != null) |
963 |
|
throw new ExecutionException(ex); |
767 |
– |
throw new TimeoutException(); |
964 |
|
} |
965 |
|
return getRawResult(); |
966 |
|
} |
967 |
|
|
968 |
|
/** |
969 |
< |
* Possibly executes other tasks until this task {@link #isDone is |
774 |
< |
* done}, then returns the result of the computation. This method |
775 |
< |
* may be more efficient than {@code join}, but is only applicable |
776 |
< |
* when there are no potential dependencies between continuation |
777 |
< |
* of the current task and that of any other task that might be |
778 |
< |
* executed while helping. (This usually holds for pure |
779 |
< |
* divide-and-conquer tasks). |
780 |
< |
* |
781 |
< |
* <p>This method may be invoked only from within {@code |
782 |
< |
* ForkJoinTask} computations (as may be determined using method |
783 |
< |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
784 |
< |
* result in exceptions or errors, possibly including {@code |
785 |
< |
* ClassCastException}. |
786 |
< |
* |
787 |
< |
* @return the computed result |
788 |
< |
*/ |
789 |
< |
public final V helpJoin() { |
790 |
< |
return reportResult(busyJoin()); |
791 |
< |
} |
792 |
< |
|
793 |
< |
/** |
794 |
< |
* Possibly executes other tasks until this task {@link #isDone is |
795 |
< |
* done}. This method may be useful when processing collections |
796 |
< |
* of tasks when some have been cancelled or otherwise known to |
797 |
< |
* have aborted. |
798 |
< |
* |
799 |
< |
* <p>This method may be invoked only from within {@code |
800 |
< |
* ForkJoinTask} computations (as may be determined using method |
801 |
< |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
802 |
< |
* result in exceptions or errors, possibly including {@code |
803 |
< |
* ClassCastException}. |
804 |
< |
*/ |
805 |
< |
public final void quietlyHelpJoin() { |
806 |
< |
busyJoin(); |
807 |
< |
} |
808 |
< |
|
809 |
< |
/** |
810 |
< |
* Joins this task, without returning its result or throwing an |
969 |
> |
* Joins this task, without returning its result or throwing its |
970 |
|
* exception. This method may be useful when processing |
971 |
|
* collections of tasks when some have been cancelled or otherwise |
972 |
|
* known to have aborted. |
973 |
|
*/ |
974 |
|
public final void quietlyJoin() { |
975 |
< |
waitingJoin(); |
975 |
> |
doJoin(); |
976 |
|
} |
977 |
|
|
978 |
|
/** |
979 |
|
* Commences performing this task and awaits its completion if |
980 |
< |
* necessary, without returning its result or throwing an |
981 |
< |
* exception. This method may be useful when processing |
823 |
< |
* collections of tasks when some have been cancelled or otherwise |
824 |
< |
* known to have aborted. |
980 |
> |
* necessary, without returning its result or throwing its |
981 |
> |
* exception. |
982 |
|
*/ |
983 |
|
public final void quietlyInvoke() { |
984 |
< |
waitingInvoke(); |
984 |
> |
doInvoke(); |
985 |
|
} |
986 |
|
|
987 |
|
/** |
992 |
|
* processed. |
993 |
|
* |
994 |
|
* <p>This method may be invoked only from within {@code |
995 |
< |
* ForkJoinTask} computations (as may be determined using method |
995 |
> |
* ForkJoinPool} computations (as may be determined using method |
996 |
|
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
997 |
|
* result in exceptions or errors, possibly including {@code |
998 |
|
* ClassCastException}. |
1011 |
|
* under any other usage conditions are not guaranteed. |
1012 |
|
* This method may be useful when executing |
1013 |
|
* pre-constructed trees of subtasks in loops. |
1014 |
+ |
* |
1015 |
+ |
* <p>Upon completion of this method, {@code isDone()} reports |
1016 |
+ |
* {@code false}, and {@code getException()} reports {@code |
1017 |
+ |
* null}. However, the value returned by {@code getRawResult} is |
1018 |
+ |
* unaffected. To clear this value, you can invoke {@code |
1019 |
+ |
* setRawResult(null)}. |
1020 |
|
*/ |
1021 |
|
public void reinitialize() { |
1022 |
< |
if ((status & COMPLETION_MASK) == EXCEPTIONAL) |
1023 |
< |
exceptionMap.remove(this); |
1024 |
< |
status = 0; |
1022 |
> |
if (status == EXCEPTIONAL) |
1023 |
> |
clearExceptionalCompletion(); |
1024 |
> |
else |
1025 |
> |
status = 0; |
1026 |
|
} |
1027 |
|
|
1028 |
|
/** |
1039 |
|
} |
1040 |
|
|
1041 |
|
/** |
1042 |
< |
* Returns {@code true} if the current thread is executing as a |
1043 |
< |
* ForkJoinPool computation. |
1042 |
> |
* Returns {@code true} if the current thread is a {@link |
1043 |
> |
* ForkJoinWorkerThread} executing as a ForkJoinPool computation. |
1044 |
|
* |
1045 |
< |
* @return {@code true} if the current thread is executing as a |
1046 |
< |
* ForkJoinPool computation, or false otherwise |
1045 |
> |
* @return {@code true} if the current thread is a {@link |
1046 |
> |
* ForkJoinWorkerThread} executing as a ForkJoinPool computation, |
1047 |
> |
* or {@code false} otherwise |
1048 |
|
*/ |
1049 |
|
public static boolean inForkJoinPool() { |
1050 |
|
return Thread.currentThread() instanceof ForkJoinWorkerThread; |
1059 |
|
* were not, stolen. |
1060 |
|
* |
1061 |
|
* <p>This method may be invoked only from within {@code |
1062 |
< |
* ForkJoinTask} computations (as may be determined using method |
1062 |
> |
* ForkJoinPool} computations (as may be determined using method |
1063 |
|
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
1064 |
|
* result in exceptions or errors, possibly including {@code |
1065 |
|
* ClassCastException}. |
1078 |
|
* fork other tasks. |
1079 |
|
* |
1080 |
|
* <p>This method may be invoked only from within {@code |
1081 |
< |
* ForkJoinTask} computations (as may be determined using method |
1081 |
> |
* ForkJoinPool} computations (as may be determined using method |
1082 |
|
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
1083 |
|
* result in exceptions or errors, possibly including {@code |
1084 |
|
* ClassCastException}. |
1101 |
|
* exceeded. |
1102 |
|
* |
1103 |
|
* <p>This method may be invoked only from within {@code |
1104 |
< |
* ForkJoinTask} computations (as may be determined using method |
1104 |
> |
* ForkJoinPool} computations (as may be determined using method |
1105 |
|
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
1106 |
|
* result in exceptions or errors, possibly including {@code |
1107 |
|
* ClassCastException}. |
1159 |
|
* otherwise. |
1160 |
|
* |
1161 |
|
* <p>This method may be invoked only from within {@code |
1162 |
< |
* ForkJoinTask} computations (as may be determined using method |
1162 |
> |
* ForkJoinPool} computations (as may be determined using method |
1163 |
|
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
1164 |
|
* result in exceptions or errors, possibly including {@code |
1165 |
|
* ClassCastException}. |
1178 |
|
* be useful otherwise. |
1179 |
|
* |
1180 |
|
* <p>This method may be invoked only from within {@code |
1181 |
< |
* ForkJoinTask} computations (as may be determined using method |
1181 |
> |
* ForkJoinPool} computations (as may be determined using method |
1182 |
|
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
1183 |
|
* result in exceptions or errors, possibly including {@code |
1184 |
|
* ClassCastException}. |
1201 |
|
* otherwise. |
1202 |
|
* |
1203 |
|
* <p>This method may be invoked only from within {@code |
1204 |
< |
* ForkJoinTask} computations (as may be determined using method |
1204 |
> |
* ForkJoinPool} computations (as may be determined using method |
1205 |
|
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
1206 |
|
* result in exceptions or errors, possibly including {@code |
1207 |
|
* ClassCastException}. |
1311 |
|
private static final long serialVersionUID = -7721805057305804111L; |
1312 |
|
|
1313 |
|
/** |
1314 |
< |
* Saves the state to a stream. |
1314 |
> |
* Saves the state to a stream (that is, serializes it). |
1315 |
|
* |
1316 |
|
* @serialData the current run status and the exception thrown |
1317 |
|
* during execution, or {@code null} if none |
1324 |
|
} |
1325 |
|
|
1326 |
|
/** |
1327 |
< |
* Reconstitutes the instance from a stream. |
1327 |
> |
* Reconstitutes the instance from a stream (that is, deserializes it). |
1328 |
|
* |
1329 |
|
* @param s the stream |
1330 |
|
*/ |
1331 |
|
private void readObject(java.io.ObjectInputStream s) |
1332 |
|
throws java.io.IOException, ClassNotFoundException { |
1333 |
|
s.defaultReadObject(); |
1169 |
– |
status |= SIGNAL; // conservatively set external signal |
1334 |
|
Object ex = s.readObject(); |
1335 |
|
if (ex != null) |
1336 |
< |
setExceptionalCompletion((Throwable) ex); |
1336 |
> |
setExceptionalCompletion((Throwable)ex); |
1337 |
|
} |
1338 |
|
|
1339 |
|
// Unsafe mechanics |
1340 |
< |
|
1341 |
< |
private static final sun.misc.Unsafe UNSAFE = getUnsafe(); |
1342 |
< |
private static final long statusOffset = |
1343 |
< |
objectFieldOffset("status", ForkJoinTask.class); |
1344 |
< |
|
1345 |
< |
private static long objectFieldOffset(String field, Class<?> klazz) { |
1340 |
> |
private static final sun.misc.Unsafe UNSAFE; |
1341 |
> |
private static final long statusOffset; |
1342 |
> |
static { |
1343 |
> |
exceptionTableLock = new ReentrantLock(); |
1344 |
> |
exceptionTableRefQueue = new ReferenceQueue<Object>(); |
1345 |
> |
exceptionTable = new ExceptionNode[EXCEPTION_MAP_CAPACITY]; |
1346 |
|
try { |
1347 |
< |
return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field)); |
1348 |
< |
} catch (NoSuchFieldException e) { |
1349 |
< |
// Convert Exception to corresponding Error |
1350 |
< |
NoSuchFieldError error = new NoSuchFieldError(field); |
1351 |
< |
error.initCause(e); |
1188 |
< |
throw error; |
1347 |
> |
UNSAFE = getUnsafe(); |
1348 |
> |
statusOffset = UNSAFE.objectFieldOffset |
1349 |
> |
(ForkJoinTask.class.getDeclaredField("status")); |
1350 |
> |
} catch (Exception e) { |
1351 |
> |
throw new Error(e); |
1352 |
|
} |
1353 |
|
} |
1354 |
|
|