5 |
|
*/ |
6 |
|
|
7 |
|
package jsr166y; |
8 |
< |
import java.io.Serializable; |
9 |
< |
import java.util.*; |
8 |
> |
|
9 |
|
import java.util.concurrent.*; |
10 |
< |
import java.util.concurrent.atomic.*; |
11 |
< |
import sun.misc.Unsafe; |
12 |
< |
import java.lang.reflect.*; |
10 |
> |
|
11 |
> |
import java.io.Serializable; |
12 |
> |
import java.util.Collection; |
13 |
> |
import java.util.Collections; |
14 |
> |
import java.util.List; |
15 |
> |
import java.util.RandomAccess; |
16 |
> |
import java.util.Map; |
17 |
> |
import java.util.WeakHashMap; |
18 |
|
|
19 |
|
/** |
20 |
< |
* Abstract base class for tasks that run within a ForkJoinPool. A |
21 |
< |
* ForkJoinTask is a thread-like entity that is much lighter weight |
22 |
< |
* than a normal thread. Huge numbers of tasks and subtasks may be |
23 |
< |
* hosted by a small number of actual threads in a ForkJoinPool, |
24 |
< |
* at the price of some usage limitations. |
20 |
> |
* Abstract base class for tasks that run within a {@link ForkJoinPool}. |
21 |
> |
* A {@code ForkJoinTask} is a thread-like entity that is much |
22 |
> |
* lighter weight than a normal thread. Huge numbers of tasks and |
23 |
> |
* subtasks may be hosted by a small number of actual threads in a |
24 |
> |
* ForkJoinPool, at the price of some usage limitations. |
25 |
|
* |
26 |
< |
* <p> ForkJoinTasks are forms of <tt>Futures</tt> supporting a |
27 |
< |
* limited range of use. The "lightness" of ForkJoinTasks is due to a |
28 |
< |
* set of restrictions (that are only partially statically |
29 |
< |
* enforceable) reflecting their intended use as computational tasks |
30 |
< |
* calculating pure functions or operating on purely isolated objects. |
31 |
< |
* The primary coordination mechanisms supported for ForkJoinTasks are |
32 |
< |
* <tt>fork</tt>, that arranges asynchronous execution, and |
33 |
< |
* <tt>join</tt>, that doesn't proceed until the task's result has |
34 |
< |
* been computed. (Cancellation is also supported). The computation |
31 |
< |
* defined in the <tt>compute</tt> method should avoid |
32 |
< |
* <tt>synchronized</tt> methods or blocks, and should minimize |
33 |
< |
* blocking synchronization apart from joining other tasks or using |
34 |
< |
* synchronizers such as Phasers that are advertised to cooperate with |
35 |
< |
* fork/join scheduling. Tasks should also not perform blocking IO, |
36 |
< |
* and should ideally access variables that are completely independent |
37 |
< |
* of those accessed by other running tasks. Minor breaches of these |
38 |
< |
* restrictions, for example using shared output streams, may be |
39 |
< |
* tolerable in practice, but frequent use may result in poor |
40 |
< |
* performance, and the potential to indefinitely stall if the number |
41 |
< |
* of threads not waiting for external synchronization becomes |
42 |
< |
* exhausted. This usage restriction is in part enforced by not |
43 |
< |
* permitting checked exceptions such as IOExceptions to be |
44 |
< |
* thrown. However, computations may still encounter unchecked |
45 |
< |
* exceptions, that are rethrown to callers attempting join |
46 |
< |
* them. These exceptions may additionally include |
47 |
< |
* RejectedExecutionExceptions stemming from internal resource |
48 |
< |
* exhaustion such as failure to allocate internal task queues. |
26 |
> |
* <p>A "main" {@code ForkJoinTask} begins execution when submitted |
27 |
> |
* to a {@link ForkJoinPool}. Once started, it will usually in turn |
28 |
> |
* start other subtasks. As indicated by the name of this class, |
29 |
> |
* many programs using {@code ForkJoinTask} employ only methods |
30 |
> |
* {@link #fork} and {@link #join}, or derivatives such as {@link |
31 |
> |
* #invokeAll}. However, this class also provides a number of other |
32 |
> |
* methods that can come into play in advanced usages, as well as |
33 |
> |
* extension mechanics that allow support of new forms of fork/join |
34 |
> |
* processing. |
35 |
|
* |
36 |
< |
* <p> The <tt>ForkJoinTask</tt> class is not usually directly |
37 |
< |
* subclassed. Instead, you subclass one of the abstract classes that |
38 |
< |
* support different styles of fork/join processing. Normally, a |
39 |
< |
* concrete ForkJoinTask subclass declares fields comprising its |
40 |
< |
* parameters, established in a constructor, and then defines a |
41 |
< |
* <tt>compute</tt> method that somehow uses the control methods |
42 |
< |
* supplied by this base class. While these methods have |
43 |
< |
* <tt>public</tt> access, some of them may only be called from within |
44 |
< |
* other ForkJoinTasks. Attempts to invoke them in other contexts |
45 |
< |
* result in exceptions or errors including ClassCastException. The |
46 |
< |
* only way to invoke a "main" driver task is to submit it to a |
47 |
< |
* ForkJoinPool. Once started, this will usually in turn start other |
48 |
< |
* subtasks. |
36 |
> |
* <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}. |
37 |
> |
* The efficiency of {@code ForkJoinTask}s stems from a set of |
38 |
> |
* restrictions (that are only partially statically enforceable) |
39 |
> |
* reflecting their intended use as computational tasks calculating |
40 |
> |
* pure functions or operating on purely isolated objects. The |
41 |
> |
* primary coordination mechanisms are {@link #fork}, that arranges |
42 |
> |
* asynchronous execution, and {@link #join}, that doesn't proceed |
43 |
> |
* until the task's result has been computed. Computations should |
44 |
> |
* avoid {@code synchronized} methods or blocks, and should minimize |
45 |
> |
* other blocking synchronization apart from joining other tasks or |
46 |
> |
* using synchronizers such as Phasers that are advertised to |
47 |
> |
* cooperate with fork/join scheduling. Tasks should also not perform |
48 |
> |
* blocking IO, and should ideally access variables that are |
49 |
> |
* completely independent of those accessed by other running |
50 |
> |
* tasks. Minor breaches of these restrictions, for example using |
51 |
> |
* shared output streams, may be tolerable in practice, but frequent |
52 |
> |
* use may result in poor performance, and the potential to |
53 |
> |
* indefinitely stall if the number of threads not waiting for IO or |
54 |
> |
* other external synchronization becomes exhausted. This usage |
55 |
> |
* restriction is in part enforced by not permitting checked |
56 |
> |
* exceptions such as {@code IOExceptions} to be thrown. However, |
57 |
> |
* computations may still encounter unchecked exceptions, that are |
58 |
> |
* rethrown to callers attempting to join them. These exceptions may |
59 |
> |
* additionally include RejectedExecutionExceptions stemming from |
60 |
> |
* internal resource exhaustion such as failure to allocate internal |
61 |
> |
* task queues. |
62 |
|
* |
63 |
< |
* <p>Most base support methods are <tt>final</tt> because their |
64 |
< |
* implementations are intrinsically tied to the underlying |
65 |
< |
* lightweight task scheduling framework, and so cannot be overridden. |
66 |
< |
* Developers creating new basic styles of fork/join processing should |
67 |
< |
* minimally implement protected methods <tt>exec</tt>, |
68 |
< |
* <tt>setRawResult</tt>, and <tt>getRawResult</tt>, while also |
69 |
< |
* introducing an abstract computational method that can be |
70 |
< |
* implemented in its subclasses. To support such extensions, |
71 |
< |
* instances of ForkJoinTasks maintain an atomically updated |
72 |
< |
* <tt>short</tt> representing user-defined control state. Control |
73 |
< |
* state is guaranteed initially to be zero, and to be negative upon |
74 |
< |
* completion, but may otherwise be used for any other control |
75 |
< |
* purposes, such as maintaining join counts. The {@link |
76 |
< |
* ForkJoinWorkerThread} class supports additional inspection and |
77 |
< |
* tuning methods that can be useful when developing extensions. |
63 |
> |
* <p>The primary method for awaiting completion and extracting |
64 |
> |
* results of a task is {@link #join}, but there are several variants: |
65 |
> |
* The {@link Future#get} methods support interruptible and/or timed |
66 |
> |
* waits for completion and report results using {@code Future} |
67 |
> |
* 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 |
71 |
> |
* equivalent to {@code fork(); join()} but always attempts to |
72 |
> |
* begin execution in the current thread. The "<em>quiet</em>" forms |
73 |
> |
* of these methods do not extract results or report exceptions. These |
74 |
> |
* may be useful when a set of tasks are being executed, and you need |
75 |
> |
* to delay processing of results or exceptions until all complete. |
76 |
> |
* Method {@code invokeAll} (available in multiple versions) |
77 |
> |
* performs the most common form of parallel invocation: forking a set |
78 |
> |
* of tasks and joining them all. |
79 |
> |
* |
80 |
> |
* <p>The ForkJoinTask class is not usually directly subclassed. |
81 |
> |
* Instead, you subclass one of the abstract classes that support a |
82 |
> |
* particular style of fork/join processing, typically {@link |
83 |
> |
* RecursiveAction} for computations that do not return results, or |
84 |
> |
* {@link RecursiveTask} for those that do. Normally, a concrete |
85 |
> |
* ForkJoinTask subclass declares fields comprising its parameters, |
86 |
> |
* established in a constructor, and then defines a {@code compute} |
87 |
> |
* method that somehow uses the control methods supplied by this base |
88 |
> |
* class. While these methods have {@code public} access (to allow |
89 |
> |
* instances of different task subclasses to call each other's |
90 |
> |
* methods), some of them may only be called from within other |
91 |
> |
* ForkJoinTasks (as may be determined using method {@link |
92 |
> |
* #inForkJoinPool}). Attempts to invoke them in other contexts |
93 |
> |
* result in exceptions or errors, possibly including |
94 |
> |
* ClassCastException. |
95 |
> |
* |
96 |
> |
* <p>Most base support methods are {@code final}, to prevent |
97 |
> |
* overriding of implementations that are intrinsically tied to the |
98 |
> |
* underlying lightweight task scheduling framework. Developers |
99 |
> |
* creating new basic styles of fork/join processing should minimally |
100 |
> |
* implement {@code protected} methods {@link #exec}, {@link |
101 |
> |
* #setRawResult}, and {@link #getRawResult}, while also introducing |
102 |
> |
* an abstract computational method that can be implemented in its |
103 |
> |
* subclasses, possibly relying on other {@code protected} methods |
104 |
> |
* provided by this class. |
105 |
|
* |
106 |
|
* <p>ForkJoinTasks should perform relatively small amounts of |
107 |
< |
* computations, othewise splitting into smaller tasks. As a very |
108 |
< |
* rough rule of thumb, a task should perform more than 100 and less |
109 |
< |
* than 10000 basic computational steps. If tasks are too big, then |
110 |
< |
* parellelism cannot improve throughput. If too small, then memory |
111 |
< |
* and internal task maintenance overhead may overwhelm processing. |
107 |
> |
* computation. Large tasks should be split into smaller subtasks, |
108 |
> |
* usually via recursive decomposition. As a very rough rule of thumb, |
109 |
> |
* a task should perform more than 100 and less than 10000 basic |
110 |
> |
* computational steps. If tasks are too big, then parallelism cannot |
111 |
> |
* improve throughput. If too small, then memory and internal task |
112 |
> |
* maintenance overhead may overwhelm processing. |
113 |
> |
* |
114 |
> |
* <p>This class provides {@code adapt} methods for {@link |
115 |
> |
* java.lang.Runnable} and {@link java.util.concurrent.Callable}, that |
116 |
> |
* may be of use when mixing execution of ForkJoinTasks with other |
117 |
> |
* kinds of tasks. When all tasks are of this form, consider using a |
118 |
> |
* pool in {@link ForkJoinPool#setAsyncMode}. |
119 |
|
* |
120 |
< |
* <p>ForkJoinTasks are <tt>Serializable</tt>, which enables them to |
121 |
< |
* be used in extensions such as remote execution frameworks. However, |
122 |
< |
* it is in general safe to serialize tasks only before or after, but |
123 |
< |
* not during execution. Serialization is not relied on during |
124 |
< |
* execution itself. |
120 |
> |
* <p>ForkJoinTasks are {@code Serializable}, which enables them to be |
121 |
> |
* used in extensions such as remote execution frameworks. It is |
122 |
> |
* sensible to serialize tasks only before or after, but not during, |
123 |
> |
* execution. Serialization is not relied on during execution itself. |
124 |
> |
* |
125 |
> |
* @since 1.7 |
126 |
> |
* @author Doug Lea |
127 |
|
*/ |
128 |
|
public abstract class ForkJoinTask<V> implements Future<V>, Serializable { |
129 |
+ |
|
130 |
|
/** |
131 |
< |
* Status field holding all run status. We pack this into a single |
132 |
< |
* int both to minimize footprint overhead and to ensure atomicity |
133 |
< |
* (updates are via CAS). |
98 |
< |
* |
99 |
< |
* Status is initially zero, and takes on nonnegative values until |
131 |
> |
* Run control status bits packed into a single int to minimize |
132 |
> |
* footprint and to ensure atomicity (via CAS). Status is |
133 |
> |
* initially zero, and takes on nonnegative values until |
134 |
|
* completed, upon which status holds COMPLETED. CANCELLED, or |
135 |
|
* EXCEPTIONAL, which use the top 3 bits. Tasks undergoing |
136 |
|
* blocking waits by other threads have SIGNAL_MASK bits set -- |
145 |
|
* currently unused. Also value 0x80000000 is available as spare |
146 |
|
* completion value. |
147 |
|
*/ |
148 |
< |
volatile int status; // accessed directy by pool and workers |
148 |
> |
volatile int status; // accessed directly by pool and workers |
149 |
|
|
150 |
|
static final int COMPLETION_MASK = 0xe0000000; |
151 |
|
static final int NORMAL = 0xe0000000; // == mask |
158 |
|
/** |
159 |
|
* Table of exceptions thrown by tasks, to enable reporting by |
160 |
|
* callers. Because exceptions are rare, we don't directly keep |
161 |
< |
* them with task objects, but instead us a weak ref table. Note |
161 |
> |
* them with task objects, but instead use a weak ref table. Note |
162 |
|
* that cancellation exceptions don't appear in the table, but are |
163 |
|
* instead recorded as status values. |
164 |
< |
* Todo: Use ConcurrentReferenceHashMap |
164 |
> |
* TODO: Use ConcurrentReferenceHashMap |
165 |
|
*/ |
166 |
|
static final Map<ForkJoinTask<?>, Throwable> exceptionMap = |
167 |
|
Collections.synchronizedMap |
170 |
|
// within-package utilities |
171 |
|
|
172 |
|
/** |
173 |
< |
* Get current worker thread, or null if not a worker thread |
173 |
> |
* Gets current worker thread, or null if not a worker thread. |
174 |
|
*/ |
175 |
|
static ForkJoinWorkerThread getWorker() { |
176 |
|
Thread t = Thread.currentThread(); |
177 |
< |
return ((t instanceof ForkJoinWorkerThread)? |
178 |
< |
(ForkJoinWorkerThread)t : null); |
145 |
< |
} |
146 |
< |
|
147 |
< |
/** |
148 |
< |
* Get pool of current worker thread, or null if not a worker thread |
149 |
< |
*/ |
150 |
< |
static ForkJoinPool getWorkerPool() { |
151 |
< |
Thread t = Thread.currentThread(); |
152 |
< |
return ((t instanceof ForkJoinWorkerThread)? |
153 |
< |
((ForkJoinWorkerThread)t).pool : null); |
177 |
> |
return ((t instanceof ForkJoinWorkerThread) ? |
178 |
> |
(ForkJoinWorkerThread) t : null); |
179 |
|
} |
180 |
|
|
181 |
|
final boolean casStatus(int cmp, int val) { |
182 |
< |
return _unsafe.compareAndSwapInt(this, statusOffset, cmp, val); |
182 |
> |
return UNSAFE.compareAndSwapInt(this, statusOffset, cmp, val); |
183 |
|
} |
184 |
|
|
185 |
|
/** |
187 |
|
*/ |
188 |
|
static void rethrowException(Throwable ex) { |
189 |
|
if (ex != null) |
190 |
< |
_unsafe.throwException(ex); |
190 |
> |
UNSAFE.throwException(ex); |
191 |
|
} |
192 |
|
|
193 |
|
// Setting completion status |
194 |
|
|
195 |
|
/** |
196 |
< |
* Mark completion and wake up threads waiting to join this task. |
196 |
> |
* Marks completion and wakes up threads waiting to join this task. |
197 |
> |
* |
198 |
|
* @param completion one of NORMAL, CANCELLED, EXCEPTIONAL |
199 |
|
*/ |
200 |
|
final void setCompletion(int completion) { |
201 |
< |
ForkJoinPool pool = getWorkerPool(); |
201 |
> |
ForkJoinPool pool = getPool(); |
202 |
|
if (pool != null) { |
203 |
|
int s; // Clear signal bits while setting completion status |
204 |
< |
do;while ((s = status) >= 0 && !casStatus(s, completion)); |
204 |
> |
do {} while ((s = status) >= 0 && !casStatus(s, completion)); |
205 |
|
|
206 |
|
if ((s & SIGNAL_MASK) != 0) { |
207 |
|
if ((s &= INTERNAL_SIGNAL_MASK) != 0) |
208 |
|
pool.updateRunningCount(s); |
209 |
< |
synchronized(this) { notifyAll(); } |
209 |
> |
synchronized (this) { notifyAll(); } |
210 |
|
} |
211 |
|
} |
212 |
|
else |
219 |
|
*/ |
220 |
|
private void externallySetCompletion(int completion) { |
221 |
|
int s; |
222 |
< |
do;while ((s = status) >= 0 && |
223 |
< |
!casStatus(s, (s & SIGNAL_MASK) | completion)); |
224 |
< |
synchronized(this) { notifyAll(); } |
222 |
> |
do {} while ((s = status) >= 0 && |
223 |
> |
!casStatus(s, (s & SIGNAL_MASK) | completion)); |
224 |
> |
synchronized (this) { notifyAll(); } |
225 |
|
} |
226 |
|
|
227 |
|
/** |
228 |
< |
* Sets status to indicate normal completion |
228 |
> |
* Sets status to indicate normal completion. |
229 |
|
*/ |
230 |
|
final void setNormalCompletion() { |
231 |
|
// Try typical fast case -- single CAS, no signal, not already done. |
232 |
|
// Manually expand casStatus to improve chances of inlining it |
233 |
< |
if (!_unsafe.compareAndSwapInt(this, statusOffset, 0, NORMAL)) |
233 |
> |
if (!UNSAFE.compareAndSwapInt(this, statusOffset, 0, NORMAL)) |
234 |
|
setCompletion(NORMAL); |
235 |
|
} |
236 |
|
|
237 |
|
// internal waiting and notification |
238 |
|
|
239 |
|
/** |
240 |
< |
* Performs the actual monitor wait for awaitDone |
240 |
> |
* Performs the actual monitor wait for awaitDone. |
241 |
|
*/ |
242 |
|
private void doAwaitDone() { |
243 |
|
// Minimize lock bias and in/de-flation effects by maximizing |
244 |
|
// chances of waiting inside sync |
245 |
|
try { |
246 |
|
while (status >= 0) |
247 |
< |
synchronized(this) { if (status >= 0) wait(); } |
247 |
> |
synchronized (this) { if (status >= 0) wait(); } |
248 |
|
} catch (InterruptedException ie) { |
249 |
|
onInterruptedWait(); |
250 |
|
} |
251 |
|
} |
252 |
|
|
253 |
|
/** |
254 |
< |
* Performs the actual monitor wait for awaitDone |
254 |
> |
* Performs the actual timed monitor wait for awaitDone. |
255 |
|
*/ |
256 |
|
private void doAwaitDone(long startTime, long nanos) { |
257 |
< |
synchronized(this) { |
257 |
> |
synchronized (this) { |
258 |
|
try { |
259 |
|
while (status >= 0) { |
260 |
< |
long nt = nanos - System.nanoTime() - startTime; |
260 |
> |
long nt = nanos - (System.nanoTime() - startTime); |
261 |
|
if (nt <= 0) |
262 |
|
break; |
263 |
< |
wait(nt / 1000000, (int)(nt % 1000000)); |
263 |
> |
wait(nt / 1000000, (int) (nt % 1000000)); |
264 |
|
} |
265 |
|
} catch (InterruptedException ie) { |
266 |
|
onInterruptedWait(); |
273 |
|
/** |
274 |
|
* Sets status to indicate there is joiner, then waits for join, |
275 |
|
* surrounded with pool notifications. |
276 |
+ |
* |
277 |
|
* @return status upon exit |
278 |
|
*/ |
279 |
< |
final int awaitDone(ForkJoinWorkerThread w, boolean maintainParallelism) { |
280 |
< |
ForkJoinPool pool = w == null? null : w.pool; |
279 |
> |
private int awaitDone(ForkJoinWorkerThread w, |
280 |
> |
boolean maintainParallelism) { |
281 |
> |
ForkJoinPool pool = (w == null) ? null : w.pool; |
282 |
|
int s; |
283 |
|
while ((s = status) >= 0) { |
284 |
< |
if (casStatus(s, pool == null? s|EXTERNAL_SIGNAL : s+1)) { |
284 |
> |
if (casStatus(s, (pool == null) ? s|EXTERNAL_SIGNAL : s+1)) { |
285 |
|
if (pool == null || !pool.preJoin(this, maintainParallelism)) |
286 |
|
doAwaitDone(); |
287 |
|
if (((s = status) & INTERNAL_SIGNAL_MASK) != 0) |
294 |
|
|
295 |
|
/** |
296 |
|
* Timed version of awaitDone |
297 |
+ |
* |
298 |
|
* @return status upon exit |
299 |
|
*/ |
300 |
< |
final int awaitDone(ForkJoinWorkerThread w, long nanos) { |
301 |
< |
ForkJoinPool pool = w == null? null : w.pool; |
300 |
> |
private int awaitDone(ForkJoinWorkerThread w, long nanos) { |
301 |
> |
ForkJoinPool pool = (w == null) ? null : w.pool; |
302 |
|
int s; |
303 |
|
while ((s = status) >= 0) { |
304 |
< |
if (casStatus(s, pool == null? s|EXTERNAL_SIGNAL : s+1)) { |
304 |
> |
if (casStatus(s, (pool == null) ? s|EXTERNAL_SIGNAL : s+1)) { |
305 |
|
long startTime = System.nanoTime(); |
306 |
|
if (pool == null || !pool.preJoin(this, false)) |
307 |
|
doAwaitDone(startTime, nanos); |
318 |
|
} |
319 |
|
|
320 |
|
/** |
321 |
< |
* Notify pool that thread is unblocked. Called by signalled |
321 |
> |
* Notifies pool that thread is unblocked. Called by signalled |
322 |
|
* threads when woken by non-FJ threads (which is atypical). |
323 |
|
*/ |
324 |
|
private void adjustPoolCountsOnUnblock(ForkJoinPool pool) { |
325 |
|
int s; |
326 |
< |
do;while ((s = status) < 0 && !casStatus(s, s & COMPLETION_MASK)); |
326 |
> |
do {} while ((s = status) < 0 && !casStatus(s, s & COMPLETION_MASK)); |
327 |
|
if (pool != null && (s &= INTERNAL_SIGNAL_MASK) != 0) |
328 |
|
pool.updateRunningCount(s); |
329 |
|
} |
330 |
|
|
331 |
|
/** |
332 |
< |
* Notify pool to adjust counts on cancelled or timed out wait |
332 |
> |
* Notifies pool to adjust counts on cancelled or timed out wait. |
333 |
|
*/ |
334 |
|
private void adjustPoolCountsOnCancelledWait(ForkJoinPool pool) { |
335 |
|
if (pool != null) { |
343 |
|
} |
344 |
|
} |
345 |
|
|
346 |
+ |
/** |
347 |
+ |
* Handles interruptions during waits. |
348 |
+ |
*/ |
349 |
|
private void onInterruptedWait() { |
350 |
< |
Thread t = Thread.currentThread(); |
351 |
< |
if (t instanceof ForkJoinWorkerThread) { |
352 |
< |
ForkJoinWorkerThread w = (ForkJoinWorkerThread)t; |
353 |
< |
if (w.isTerminating()) |
354 |
< |
cancelIgnoreExceptions(); |
355 |
< |
} |
324 |
< |
else { // re-interrupt |
325 |
< |
try { |
326 |
< |
t.interrupt(); |
327 |
< |
} catch (SecurityException ignore) { |
328 |
< |
} |
329 |
< |
} |
350 |
> |
ForkJoinWorkerThread w = getWorker(); |
351 |
> |
if (w == null) |
352 |
> |
Thread.currentThread().interrupt(); // re-interrupt |
353 |
> |
else if (w.isTerminating()) |
354 |
> |
cancelIgnoringExceptions(); |
355 |
> |
// else if FJworker, ignore interrupt |
356 |
|
} |
357 |
|
|
358 |
|
// Recording and reporting exceptions |
363 |
|
} |
364 |
|
|
365 |
|
/** |
366 |
< |
* Throws the exception associated with status s; |
366 |
> |
* Throws the exception associated with status s. |
367 |
> |
* |
368 |
|
* @throws the exception |
369 |
|
*/ |
370 |
|
private void reportException(int s) { |
377 |
|
} |
378 |
|
|
379 |
|
/** |
380 |
< |
* Returns result or throws exception using j.u.c.Future conventions |
381 |
< |
* Only call when isDone known to be true. |
380 |
> |
* Returns result or throws exception using j.u.c.Future conventions. |
381 |
> |
* Only call when {@code isDone} known to be true. |
382 |
|
*/ |
383 |
|
private V reportFutureResult() |
384 |
|
throws ExecutionException, InterruptedException { |
397 |
|
|
398 |
|
/** |
399 |
|
* Returns result or throws exception using j.u.c.Future conventions |
400 |
< |
* with timeouts |
400 |
> |
* with timeouts. |
401 |
|
*/ |
402 |
|
private V reportTimedFutureResult() |
403 |
|
throws InterruptedException, ExecutionException, TimeoutException { |
418 |
|
|
419 |
|
/** |
420 |
|
* Calls exec, recording completion, and rethrowing exception if |
421 |
< |
* encountered. Caller should normally check status before calling |
421 |
> |
* encountered. Caller should normally check status before calling. |
422 |
> |
* |
423 |
|
* @return true if completed normally |
424 |
|
*/ |
425 |
|
private boolean tryExec() { |
437 |
|
|
438 |
|
/** |
439 |
|
* Main execution method used by worker threads. Invokes |
440 |
< |
* base computation unless already complete |
440 |
> |
* base computation unless already complete. |
441 |
|
*/ |
442 |
|
final void quietlyExec() { |
443 |
|
if (status >= 0) { |
444 |
|
try { |
445 |
|
if (!exec()) |
446 |
|
return; |
447 |
< |
} catch(Throwable rex) { |
447 |
> |
} catch (Throwable rex) { |
448 |
|
setDoneExceptionally(rex); |
449 |
|
return; |
450 |
|
} |
453 |
|
} |
454 |
|
|
455 |
|
/** |
456 |
< |
* Calls exec, recording but not rethrowing exception |
457 |
< |
* Caller should normally check status before calling |
456 |
> |
* Calls exec(), recording but not rethrowing exception. |
457 |
> |
* Caller should normally check status before calling. |
458 |
> |
* |
459 |
|
* @return true if completed normally |
460 |
|
*/ |
461 |
|
private boolean tryQuietlyInvoke() { |
471 |
|
} |
472 |
|
|
473 |
|
/** |
474 |
< |
* Cancel, ignoring any exceptions it throws |
474 |
> |
* Cancels, ignoring any exceptions it throws. |
475 |
|
*/ |
476 |
< |
final void cancelIgnoreExceptions() { |
476 |
> |
final void cancelIgnoringExceptions() { |
477 |
|
try { |
478 |
|
cancel(false); |
479 |
< |
} catch(Throwable ignore) { |
479 |
> |
} catch (Throwable ignore) { |
480 |
|
} |
481 |
|
} |
482 |
|
|
483 |
+ |
/** |
484 |
+ |
* Main implementation of helpJoin |
485 |
+ |
*/ |
486 |
+ |
private int busyJoin(ForkJoinWorkerThread w) { |
487 |
+ |
int s; |
488 |
+ |
ForkJoinTask<?> t; |
489 |
+ |
while ((s = status) >= 0 && (t = w.scanWhileJoining(this)) != null) |
490 |
+ |
t.quietlyExec(); |
491 |
+ |
return (s >= 0) ? awaitDone(w, false) : s; // block if no work |
492 |
+ |
} |
493 |
+ |
|
494 |
|
// public methods |
495 |
|
|
496 |
|
/** |
497 |
|
* Arranges to asynchronously execute this task. While it is not |
498 |
|
* necessarily enforced, it is a usage error to fork a task more |
499 |
< |
* than once unless it has completed and been reinitialized. This |
500 |
< |
* method may be invoked only from within other ForkJoinTask |
501 |
< |
* computations. Attempts to invoke in other contexts result in |
502 |
< |
* exceptions or errors including ClassCastException. |
499 |
> |
* than once unless it has completed and been reinitialized. |
500 |
> |
* |
501 |
> |
* <p>This method may be invoked only from within {@code |
502 |
> |
* ForkJoinTask} computations (as may be determined using method |
503 |
> |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
504 |
> |
* result in exceptions or errors, possibly including {@code |
505 |
> |
* ClassCastException}. |
506 |
> |
* |
507 |
> |
* @return {@code this}, to simplify usage |
508 |
|
*/ |
509 |
< |
public final void fork() { |
510 |
< |
((ForkJoinWorkerThread)(Thread.currentThread())).pushTask(this); |
509 |
> |
public final ForkJoinTask<V> fork() { |
510 |
> |
((ForkJoinWorkerThread) Thread.currentThread()) |
511 |
> |
.pushTask(this); |
512 |
> |
return this; |
513 |
|
} |
514 |
|
|
515 |
|
/** |
516 |
|
* Returns the result of the computation when it is ready. |
517 |
< |
* This method differs from <tt>get</tt> in that abnormal |
518 |
< |
* completion results in RuntimeExceptions or Errors, not |
519 |
< |
* ExecutionExceptions. |
517 |
> |
* This method differs from {@link #get()} in that |
518 |
> |
* abnormal completion results in {@code RuntimeException} or |
519 |
> |
* {@code Error}, not {@code ExecutionException}. |
520 |
|
* |
521 |
|
* @return the computed result |
522 |
|
*/ |
527 |
|
return getRawResult(); |
528 |
|
} |
529 |
|
|
483 |
– |
public final V get() throws InterruptedException, ExecutionException { |
484 |
– |
ForkJoinWorkerThread w = getWorker(); |
485 |
– |
if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke()) |
486 |
– |
awaitDone(w, true); |
487 |
– |
return reportFutureResult(); |
488 |
– |
} |
489 |
– |
|
490 |
– |
public final V get(long timeout, TimeUnit unit) |
491 |
– |
throws InterruptedException, ExecutionException, TimeoutException { |
492 |
– |
ForkJoinWorkerThread w = getWorker(); |
493 |
– |
if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke()) |
494 |
– |
awaitDone(w, unit.toNanos(timeout)); |
495 |
– |
return reportTimedFutureResult(); |
496 |
– |
} |
497 |
– |
|
498 |
– |
/** |
499 |
– |
* Possibly executes other tasks until this task is ready, then |
500 |
– |
* returns the result of the computation. This method may be more |
501 |
– |
* efficient than <tt>join</tt>, but is only applicable when there |
502 |
– |
* are no potemtial dependencies between continuation of the |
503 |
– |
* current task and that of any other task that might be executed |
504 |
– |
* while helping. (This usually holds for pure divide-and-conquer |
505 |
– |
* tasks). |
506 |
– |
* @return the computed result |
507 |
– |
*/ |
508 |
– |
public final V helpJoin() { |
509 |
– |
ForkJoinWorkerThread w = (ForkJoinWorkerThread)(Thread.currentThread()); |
510 |
– |
if (status < 0 || !w.unpushTask(this) || !tryExec()) |
511 |
– |
reportException(w.helpJoinTask(this)); |
512 |
– |
return getRawResult(); |
513 |
– |
} |
514 |
– |
|
530 |
|
/** |
531 |
< |
* Performs this task, awaits its completion if necessary, and |
532 |
< |
* return its result. |
531 |
> |
* Commences performing this task, awaits its completion if |
532 |
> |
* necessary, and return its result. |
533 |
> |
* |
534 |
|
* @throws Throwable (a RuntimeException, Error, or unchecked |
535 |
< |
* exception) if the underlying computation did so. |
535 |
> |
* exception) if the underlying computation did so |
536 |
|
* @return the computed result |
537 |
|
*/ |
538 |
|
public final V invoke() { |
543 |
|
} |
544 |
|
|
545 |
|
/** |
546 |
< |
* Joins this task, without returning its result or throwing an |
547 |
< |
* exception. This method may be useful when processing |
548 |
< |
* collections of tasks when some have been cancelled or otherwise |
549 |
< |
* known to have aborted. |
546 |
> |
* Forks the given tasks, returning when {@code isDone} holds |
547 |
> |
* for each task or an exception is encountered. |
548 |
> |
* |
549 |
> |
* <p>This method may be invoked only from within {@code |
550 |
> |
* ForkJoinTask} computations (as may be determined using method |
551 |
> |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
552 |
> |
* result in exceptions or errors, possibly including {@code |
553 |
> |
* ClassCastException}. |
554 |
> |
* |
555 |
> |
* @param t1 the first task |
556 |
> |
* @param t2 the second task |
557 |
> |
* @throws NullPointerException if any task is null |
558 |
> |
* @throws RuntimeException or Error if a task did so |
559 |
|
*/ |
560 |
< |
public final void quietlyJoin() { |
561 |
< |
if (status >= 0) { |
562 |
< |
ForkJoinWorkerThread w = getWorker(); |
563 |
< |
if (w == null || !w.unpushTask(this) || !tryQuietlyInvoke()) |
539 |
< |
awaitDone(w, true); |
540 |
< |
} |
560 |
> |
public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) { |
561 |
> |
t2.fork(); |
562 |
> |
t1.invoke(); |
563 |
> |
t2.join(); |
564 |
|
} |
565 |
|
|
566 |
|
/** |
567 |
< |
* Possibly executes other tasks until this task is ready. |
567 |
> |
* Forks the given tasks, returning when {@code isDone} holds for |
568 |
> |
* each task or an exception is encountered. If any task |
569 |
> |
* encounters an exception, others may be, but are not guaranteed |
570 |
> |
* to be, cancelled. |
571 |
> |
* |
572 |
> |
* <p>This method may be invoked only from within {@code |
573 |
> |
* ForkJoinTask} computations (as may be determined using method |
574 |
> |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
575 |
> |
* result in exceptions or errors, possibly including {@code |
576 |
> |
* ClassCastException}. |
577 |
> |
* |
578 |
> |
* @param tasks the tasks |
579 |
> |
* @throws NullPointerException if tasks or any element are null |
580 |
> |
* @throws RuntimeException or Error if any task did so |
581 |
|
*/ |
582 |
< |
public final void quietlyHelpJoin() { |
583 |
< |
if (status >= 0) { |
584 |
< |
ForkJoinWorkerThread w = |
585 |
< |
(ForkJoinWorkerThread)(Thread.currentThread()); |
586 |
< |
if (!w.unpushTask(this) || !tryQuietlyInvoke()) |
587 |
< |
w.helpJoinTask(this); |
582 |
> |
public static void invokeAll(ForkJoinTask<?>... tasks) { |
583 |
> |
Throwable ex = null; |
584 |
> |
int last = tasks.length - 1; |
585 |
> |
for (int i = last; i >= 0; --i) { |
586 |
> |
ForkJoinTask<?> t = tasks[i]; |
587 |
> |
if (t == null) { |
588 |
> |
if (ex == null) |
589 |
> |
ex = new NullPointerException(); |
590 |
> |
} |
591 |
> |
else if (i != 0) |
592 |
> |
t.fork(); |
593 |
> |
else { |
594 |
> |
t.quietlyInvoke(); |
595 |
> |
if (ex == null) |
596 |
> |
ex = t.getException(); |
597 |
> |
} |
598 |
> |
} |
599 |
> |
for (int i = 1; i <= last; ++i) { |
600 |
> |
ForkJoinTask<?> t = tasks[i]; |
601 |
> |
if (t != null) { |
602 |
> |
if (ex != null) |
603 |
> |
t.cancel(false); |
604 |
> |
else { |
605 |
> |
t.quietlyJoin(); |
606 |
> |
if (ex == null) |
607 |
> |
ex = t.getException(); |
608 |
> |
} |
609 |
> |
} |
610 |
|
} |
611 |
+ |
if (ex != null) |
612 |
+ |
rethrowException(ex); |
613 |
|
} |
614 |
|
|
615 |
|
/** |
616 |
< |
* Performs this task and awaits its completion if necessary, |
617 |
< |
* without returning its result or throwing an exception. This |
618 |
< |
* method may be useful when processing collections of tasks when |
619 |
< |
* some have been cancelled or otherwise known to have aborted. |
620 |
< |
*/ |
621 |
< |
public final void quietlyInvoke() { |
622 |
< |
if (status >= 0 && !tryQuietlyInvoke()) |
623 |
< |
quietlyJoin(); |
616 |
> |
* Forks all tasks in the specified collection, returning when |
617 |
> |
* {@code isDone} holds for each task or an exception is |
618 |
> |
* encountered. If any task encounters an exception, others may |
619 |
> |
* be, but are not guaranteed to be, cancelled. The behavior of |
620 |
> |
* this operation is undefined if the specified collection is |
621 |
> |
* modified while the operation is in progress. |
622 |
> |
* |
623 |
> |
* <p>This method may be invoked only from within {@code |
624 |
> |
* ForkJoinTask} computations (as may be determined using method |
625 |
> |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
626 |
> |
* result in exceptions or errors, possibly including {@code |
627 |
> |
* ClassCastException}. |
628 |
> |
* |
629 |
> |
* @param tasks the collection of tasks |
630 |
> |
* @return the tasks argument, to simplify usage |
631 |
> |
* @throws NullPointerException if tasks or any element are null |
632 |
> |
* @throws RuntimeException or Error if any task did so |
633 |
> |
*/ |
634 |
> |
public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) { |
635 |
> |
if (!(tasks instanceof RandomAccess) || !(tasks instanceof List<?>)) { |
636 |
> |
invokeAll(tasks.toArray(new ForkJoinTask<?>[tasks.size()])); |
637 |
> |
return tasks; |
638 |
> |
} |
639 |
> |
@SuppressWarnings("unchecked") |
640 |
> |
List<? extends ForkJoinTask<?>> ts = |
641 |
> |
(List<? extends ForkJoinTask<?>>) tasks; |
642 |
> |
Throwable ex = null; |
643 |
> |
int last = ts.size() - 1; |
644 |
> |
for (int i = last; i >= 0; --i) { |
645 |
> |
ForkJoinTask<?> t = ts.get(i); |
646 |
> |
if (t == null) { |
647 |
> |
if (ex == null) |
648 |
> |
ex = new NullPointerException(); |
649 |
> |
} |
650 |
> |
else if (i != 0) |
651 |
> |
t.fork(); |
652 |
> |
else { |
653 |
> |
t.quietlyInvoke(); |
654 |
> |
if (ex == null) |
655 |
> |
ex = t.getException(); |
656 |
> |
} |
657 |
> |
} |
658 |
> |
for (int i = 1; i <= last; ++i) { |
659 |
> |
ForkJoinTask<?> t = ts.get(i); |
660 |
> |
if (t != null) { |
661 |
> |
if (ex != null) |
662 |
> |
t.cancel(false); |
663 |
> |
else { |
664 |
> |
t.quietlyJoin(); |
665 |
> |
if (ex == null) |
666 |
> |
ex = t.getException(); |
667 |
> |
} |
668 |
> |
} |
669 |
> |
} |
670 |
> |
if (ex != null) |
671 |
> |
rethrowException(ex); |
672 |
> |
return tasks; |
673 |
|
} |
674 |
|
|
675 |
|
/** |
676 |
< |
* Returns true if the computation performed by this task has |
677 |
< |
* completed (or has been cancelled). |
678 |
< |
* @return true if this computation has completed |
676 |
> |
* Returns {@code true} if the computation performed by this task |
677 |
> |
* has completed (or has been cancelled). |
678 |
> |
* |
679 |
> |
* @return {@code true} if this computation has completed |
680 |
|
*/ |
681 |
|
public final boolean isDone() { |
682 |
|
return status < 0; |
683 |
|
} |
684 |
|
|
685 |
|
/** |
686 |
< |
* Returns true if this task was cancelled. |
687 |
< |
* @return true if this task was cancelled |
686 |
> |
* Returns {@code true} if this task was cancelled. |
687 |
> |
* |
688 |
> |
* @return {@code true} if this task was cancelled |
689 |
|
*/ |
690 |
|
public final boolean isCancelled() { |
691 |
|
return (status & COMPLETION_MASK) == CANCELLED; |
692 |
|
} |
693 |
|
|
694 |
|
/** |
584 |
– |
* Returns true if this task threw an exception or was cancelled |
585 |
– |
* @return true if this task threw an exception or was cancelled |
586 |
– |
*/ |
587 |
– |
public final boolean completedAbnormally() { |
588 |
– |
return (status & COMPLETION_MASK) < NORMAL; |
589 |
– |
} |
590 |
– |
|
591 |
– |
/** |
592 |
– |
* Returns the exception thrown by the base computation, or a |
593 |
– |
* CancellationException if cancelled, or null if none or if the |
594 |
– |
* method has not yet completed. |
595 |
– |
* @return the exception, or null if none |
596 |
– |
*/ |
597 |
– |
public final Throwable getException() { |
598 |
– |
int s = status & COMPLETION_MASK; |
599 |
– |
if (s >= NORMAL) |
600 |
– |
return null; |
601 |
– |
if (s == CANCELLED) |
602 |
– |
return new CancellationException(); |
603 |
– |
return exceptionMap.get(this); |
604 |
– |
} |
605 |
– |
|
606 |
– |
/** |
695 |
|
* Asserts that the results of this task's computation will not be |
696 |
< |
* used. If a cancellation occurs before this task is processed, |
697 |
< |
* then its <tt>compute</tt> method will not be executed, |
698 |
< |
* <tt>isCancelled</tt> will report true, and <tt>join</tt> will |
699 |
< |
* result in a CancellationException being thrown. Otherwise, when |
696 |
> |
* used. If a cancellation occurs before attempting to execute this |
697 |
> |
* task, execution will be suppressed, {@link #isCancelled} |
698 |
> |
* will report true, and {@link #join} will result in a |
699 |
> |
* {@code CancellationException} being thrown. Otherwise, when |
700 |
|
* cancellation races with completion, there are no guarantees |
701 |
< |
* about whether <tt>isCancelled</tt> will report true, whether |
702 |
< |
* <tt>join</tt> will return normally or via an exception, or |
703 |
< |
* whether these behaviors will remain consistent upon repeated |
701 |
> |
* about whether {@code isCancelled} will report {@code true}, |
702 |
> |
* whether {@code join} will return normally or via an exception, |
703 |
> |
* or whether these behaviors will remain consistent upon repeated |
704 |
|
* invocation. |
705 |
|
* |
706 |
|
* <p>This method may be overridden in subclasses, but if so, must |
707 |
|
* still ensure that these minimal properties hold. In particular, |
708 |
< |
* the cancel method itself must not throw exceptions. |
708 |
> |
* the {@code cancel} method itself must not throw exceptions. |
709 |
|
* |
710 |
< |
* <p> This method is designed to be invoked by <em>other</em> |
710 |
> |
* <p>This method is designed to be invoked by <em>other</em> |
711 |
|
* tasks. To terminate the current task, you can just return or |
712 |
|
* throw an unchecked exception from its computation method, or |
713 |
< |
* invoke <tt>completeExceptionally(someException)</tt>. |
713 |
> |
* invoke {@link #completeExceptionally}. |
714 |
|
* |
715 |
|
* @param mayInterruptIfRunning this value is ignored in the |
716 |
|
* default implementation because tasks are not in general |
717 |
< |
* cancelled via interruption. |
717 |
> |
* cancelled via interruption |
718 |
|
* |
719 |
< |
* @return true if this task is now cancelled |
719 |
> |
* @return {@code true} if this task is now cancelled |
720 |
|
*/ |
721 |
|
public boolean cancel(boolean mayInterruptIfRunning) { |
722 |
|
setCompletion(CANCELLED); |
724 |
|
} |
725 |
|
|
726 |
|
/** |
727 |
+ |
* Returns {@code true} if this task threw an exception or was cancelled. |
728 |
+ |
* |
729 |
+ |
* @return {@code true} if this task threw an exception or was cancelled |
730 |
+ |
*/ |
731 |
+ |
public final boolean isCompletedAbnormally() { |
732 |
+ |
return (status & COMPLETION_MASK) < NORMAL; |
733 |
+ |
} |
734 |
+ |
|
735 |
+ |
/** |
736 |
+ |
* Returns the exception thrown by the base computation, or a |
737 |
+ |
* {@code CancellationException} if cancelled, or {@code null} if |
738 |
+ |
* none or if the method has not yet completed. |
739 |
+ |
* |
740 |
+ |
* @return the exception, or {@code null} if none |
741 |
+ |
*/ |
742 |
+ |
public final Throwable getException() { |
743 |
+ |
int s = status & COMPLETION_MASK; |
744 |
+ |
if (s >= NORMAL) |
745 |
+ |
return null; |
746 |
+ |
if (s == CANCELLED) |
747 |
+ |
return new CancellationException(); |
748 |
+ |
return exceptionMap.get(this); |
749 |
+ |
} |
750 |
+ |
|
751 |
+ |
/** |
752 |
|
* Completes this task abnormally, and if not already aborted or |
753 |
|
* cancelled, causes it to throw the given exception upon |
754 |
< |
* <tt>join</tt> and related operations. This method may be used |
754 |
> |
* {@code join} and related operations. This method may be used |
755 |
|
* to induce exceptions in asynchronous tasks, or to force |
756 |
< |
* completion of tasks that would not otherwise complete. This |
757 |
< |
* method is overridable, but overridden versions must invoke |
758 |
< |
* <tt>super</tt> implementation to maintain guarantees. |
756 |
> |
* completion of tasks that would not otherwise complete. Its use |
757 |
> |
* in other situations is discouraged. This method is |
758 |
> |
* overridable, but overridden versions must invoke {@code super} |
759 |
> |
* implementation to maintain guarantees. |
760 |
> |
* |
761 |
|
* @param ex the exception to throw. If this exception is |
762 |
|
* not a RuntimeException or Error, the actual exception thrown |
763 |
|
* will be a RuntimeException with cause ex. |
764 |
|
*/ |
765 |
|
public void completeExceptionally(Throwable ex) { |
766 |
|
setDoneExceptionally((ex instanceof RuntimeException) || |
767 |
< |
(ex instanceof Error)? ex : |
767 |
> |
(ex instanceof Error) ? ex : |
768 |
|
new RuntimeException(ex)); |
769 |
|
} |
770 |
|
|
771 |
|
/** |
772 |
|
* Completes this task, and if not already aborted or cancelled, |
773 |
< |
* returning a <tt>null</tt> result upon <tt>join</tt> and related |
773 |
> |
* returning a {@code null} result upon {@code join} and related |
774 |
|
* operations. This method may be used to provide results for |
775 |
|
* asynchronous tasks, or to provide alternative handling for |
776 |
< |
* tasks that would not otherwise complete normally. |
776 |
> |
* tasks that would not otherwise complete normally. Its use in |
777 |
> |
* other situations is discouraged. This method is |
778 |
> |
* overridable, but overridden versions must invoke {@code super} |
779 |
> |
* implementation to maintain guarantees. |
780 |
|
* |
781 |
< |
* @param value the result value for this task. |
781 |
> |
* @param value the result value for this task |
782 |
|
*/ |
783 |
|
public void complete(V value) { |
784 |
|
try { |
785 |
|
setRawResult(value); |
786 |
< |
} catch(Throwable rex) { |
786 |
> |
} catch (Throwable rex) { |
787 |
|
setDoneExceptionally(rex); |
788 |
|
return; |
789 |
|
} |
790 |
|
setNormalCompletion(); |
791 |
|
} |
792 |
|
|
793 |
+ |
public final V get() throws InterruptedException, ExecutionException { |
794 |
+ |
ForkJoinWorkerThread w = getWorker(); |
795 |
+ |
if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke()) |
796 |
+ |
awaitDone(w, true); |
797 |
+ |
return reportFutureResult(); |
798 |
+ |
} |
799 |
+ |
|
800 |
+ |
public final V get(long timeout, TimeUnit unit) |
801 |
+ |
throws InterruptedException, ExecutionException, TimeoutException { |
802 |
+ |
long nanos = unit.toNanos(timeout); |
803 |
+ |
ForkJoinWorkerThread w = getWorker(); |
804 |
+ |
if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke()) |
805 |
+ |
awaitDone(w, nanos); |
806 |
+ |
return reportTimedFutureResult(); |
807 |
+ |
} |
808 |
+ |
|
809 |
+ |
/** |
810 |
+ |
* Possibly executes other tasks until this task is ready, then |
811 |
+ |
* returns the result of the computation. This method may be more |
812 |
+ |
* efficient than {@code join}, but is only applicable when |
813 |
+ |
* there are no potential dependencies between continuation of the |
814 |
+ |
* current task and that of any other task that might be executed |
815 |
+ |
* while helping. (This usually holds for pure divide-and-conquer |
816 |
+ |
* tasks). |
817 |
+ |
* |
818 |
+ |
* <p>This method may be invoked only from within {@code |
819 |
+ |
* ForkJoinTask} computations (as may be determined using method |
820 |
+ |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
821 |
+ |
* result in exceptions or errors, possibly including {@code |
822 |
+ |
* ClassCastException}. |
823 |
+ |
* |
824 |
+ |
* @return the computed result |
825 |
+ |
*/ |
826 |
+ |
public final V helpJoin() { |
827 |
+ |
ForkJoinWorkerThread w = (ForkJoinWorkerThread) Thread.currentThread(); |
828 |
+ |
if (status < 0 || !w.unpushTask(this) || !tryExec()) |
829 |
+ |
reportException(busyJoin(w)); |
830 |
+ |
return getRawResult(); |
831 |
+ |
} |
832 |
+ |
|
833 |
+ |
/** |
834 |
+ |
* Possibly executes other tasks until this task is ready. This |
835 |
+ |
* method may be useful when processing collections of tasks when |
836 |
+ |
* some have been cancelled or otherwise known to have aborted. |
837 |
+ |
* |
838 |
+ |
* <p>This method may be invoked only from within {@code |
839 |
+ |
* ForkJoinTask} computations (as may be determined using method |
840 |
+ |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
841 |
+ |
* result in exceptions or errors, possibly including {@code |
842 |
+ |
* ClassCastException}. |
843 |
+ |
*/ |
844 |
+ |
public final void quietlyHelpJoin() { |
845 |
+ |
if (status >= 0) { |
846 |
+ |
ForkJoinWorkerThread w = |
847 |
+ |
(ForkJoinWorkerThread) Thread.currentThread(); |
848 |
+ |
if (!w.unpushTask(this) || !tryQuietlyInvoke()) |
849 |
+ |
busyJoin(w); |
850 |
+ |
} |
851 |
+ |
} |
852 |
+ |
|
853 |
+ |
/** |
854 |
+ |
* Joins this task, without returning its result or throwing an |
855 |
+ |
* exception. This method may be useful when processing |
856 |
+ |
* collections of tasks when some have been cancelled or otherwise |
857 |
+ |
* known to have aborted. |
858 |
+ |
*/ |
859 |
+ |
public final void quietlyJoin() { |
860 |
+ |
if (status >= 0) { |
861 |
+ |
ForkJoinWorkerThread w = getWorker(); |
862 |
+ |
if (w == null || !w.unpushTask(this) || !tryQuietlyInvoke()) |
863 |
+ |
awaitDone(w, true); |
864 |
+ |
} |
865 |
+ |
} |
866 |
+ |
|
867 |
+ |
/** |
868 |
+ |
* Commences performing this task and awaits its completion if |
869 |
+ |
* necessary, without returning its result or throwing an |
870 |
+ |
* exception. This method may be useful when processing |
871 |
+ |
* collections of tasks when some have been cancelled or otherwise |
872 |
+ |
* known to have aborted. |
873 |
+ |
*/ |
874 |
+ |
public final void quietlyInvoke() { |
875 |
+ |
if (status >= 0 && !tryQuietlyInvoke()) |
876 |
+ |
quietlyJoin(); |
877 |
+ |
} |
878 |
+ |
|
879 |
+ |
/** |
880 |
+ |
* Possibly executes tasks until the pool hosting the current task |
881 |
+ |
* {@link ForkJoinPool#isQuiescent}. This method may be of use in |
882 |
+ |
* designs in which many tasks are forked, but none are explicitly |
883 |
+ |
* joined, instead executing them until all are processed. |
884 |
+ |
* |
885 |
+ |
* <p>This method may be invoked only from within {@code |
886 |
+ |
* ForkJoinTask} computations (as may be determined using method |
887 |
+ |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
888 |
+ |
* result in exceptions or errors, possibly including {@code |
889 |
+ |
* ClassCastException}. |
890 |
+ |
*/ |
891 |
+ |
public static void helpQuiesce() { |
892 |
+ |
((ForkJoinWorkerThread) Thread.currentThread()) |
893 |
+ |
.helpQuiescePool(); |
894 |
+ |
} |
895 |
+ |
|
896 |
|
/** |
897 |
|
* Resets the internal bookkeeping state of this task, allowing a |
898 |
< |
* subsequent <tt>fork</tt>. This method allows repeated reuse of |
898 |
> |
* subsequent {@code fork}. This method allows repeated reuse of |
899 |
|
* this task, but only if reuse occurs when this task has either |
900 |
|
* never been forked, or has been forked, then completed and all |
901 |
|
* outstanding joins of this task have also completed. Effects |
902 |
< |
* under any other usage conditions are not guaranteed, and are |
903 |
< |
* almost surely wrong. This method may be useful when executing |
902 |
> |
* under any other usage conditions are not guaranteed. |
903 |
> |
* This method may be useful when executing |
904 |
|
* pre-constructed trees of subtasks in loops. |
905 |
|
*/ |
906 |
|
public void reinitialize() { |
910 |
|
} |
911 |
|
|
912 |
|
/** |
913 |
< |
* Tries to unschedule this task for execution. This method will |
914 |
< |
* typically succeed if this task is the next task that would be |
915 |
< |
* executed by the current thread, and will typically fail (return |
916 |
< |
* false) otherwise. This method may be useful when arranging |
917 |
< |
* faster local processing of tasks that could have been, but were |
697 |
< |
* not, stolen. |
698 |
< |
* @return true if unforked |
913 |
> |
* Returns the pool hosting the current task execution, or null |
914 |
> |
* if this task is executing outside of any ForkJoinPool. |
915 |
> |
* |
916 |
> |
* @see #inForkJoinPool |
917 |
> |
* @return the pool, or {@code null} if none |
918 |
|
*/ |
919 |
< |
public boolean tryUnfork() { |
920 |
< |
return ((ForkJoinWorkerThread)(Thread.currentThread())).unpushTask(this); |
919 |
> |
public static ForkJoinPool getPool() { |
920 |
> |
Thread t = Thread.currentThread(); |
921 |
> |
return (t instanceof ForkJoinWorkerThread) ? |
922 |
> |
((ForkJoinWorkerThread) t).pool : null; |
923 |
|
} |
924 |
|
|
925 |
|
/** |
926 |
< |
* Forks both tasks, returning when <tt>isDone</tt> holds for both |
927 |
< |
* of them or an exception is encountered. This method may be |
928 |
< |
* invoked only from within other ForkJoinTask |
929 |
< |
* computations. Attempts to invoke in other contexts result in |
930 |
< |
* exceptions or errors including ClassCastException. |
710 |
< |
* @param t1 one task |
711 |
< |
* @param t2 the other task |
712 |
< |
* @throws NullPointerException if t1 or t2 are null |
713 |
< |
* @throws RuntimeException or Error if either task did so. |
926 |
> |
* Returns {@code true} if the current thread is executing as a |
927 |
> |
* ForkJoinPool computation. |
928 |
> |
* |
929 |
> |
* @return {@code true} if the current thread is executing as a |
930 |
> |
* ForkJoinPool computation, or false otherwise |
931 |
|
*/ |
932 |
< |
public static void invokeAll(ForkJoinTask<?>t1, ForkJoinTask<?> t2) { |
933 |
< |
t2.fork(); |
717 |
< |
t1.invoke(); |
718 |
< |
t2.join(); |
932 |
> |
public static boolean inForkJoinPool() { |
933 |
> |
return Thread.currentThread() instanceof ForkJoinWorkerThread; |
934 |
|
} |
935 |
|
|
936 |
|
/** |
937 |
< |
* Forks the given tasks, returning when <tt>isDone</tt> holds for |
938 |
< |
* all of them. If any task encounters an exception, others may be |
939 |
< |
* cancelled. This method may be invoked only from within other |
940 |
< |
* ForkJoinTask computations. Attempts to invoke in other contexts |
941 |
< |
* result in exceptions or errors including ClassCastException. |
942 |
< |
* @param tasks the array of tasks |
943 |
< |
* @throws NullPointerException if tasks or any element are null. |
944 |
< |
* @throws RuntimeException or Error if any task did so. |
945 |
< |
*/ |
946 |
< |
public static void invokeAll(ForkJoinTask<?>... tasks) { |
947 |
< |
Throwable ex = null; |
948 |
< |
int last = tasks.length - 1; |
949 |
< |
for (int i = last; i >= 0; --i) { |
950 |
< |
ForkJoinTask<?> t = tasks[i]; |
736 |
< |
if (t == null) { |
737 |
< |
if (ex == null) |
738 |
< |
ex = new NullPointerException(); |
739 |
< |
} |
740 |
< |
else if (i != 0) |
741 |
< |
t.fork(); |
742 |
< |
else { |
743 |
< |
t.quietlyInvoke(); |
744 |
< |
if (ex == null) |
745 |
< |
ex = t.getException(); |
746 |
< |
} |
747 |
< |
} |
748 |
< |
for (int i = 1; i <= last; ++i) { |
749 |
< |
ForkJoinTask<?> t = tasks[i]; |
750 |
< |
if (t != null) { |
751 |
< |
if (ex != null) |
752 |
< |
t.cancel(false); |
753 |
< |
else { |
754 |
< |
t.quietlyJoin(); |
755 |
< |
if (ex == null) |
756 |
< |
ex = t.getException(); |
757 |
< |
} |
758 |
< |
} |
759 |
< |
} |
760 |
< |
if (ex != null) |
761 |
< |
rethrowException(ex); |
762 |
< |
} |
763 |
< |
|
764 |
< |
/** |
765 |
< |
* Forks all tasks in the collection, returning when |
766 |
< |
* <tt>isDone</tt> holds for all of them. If any task encounters |
767 |
< |
* an exception, others may be cancelled. This method may be |
768 |
< |
* invoked only from within other ForkJoinTask |
769 |
< |
* computations. Attempts to invoke in other contexts result in |
770 |
< |
* exceptions or errors including ClassCastException. |
771 |
< |
* @param tasks the collection of tasks |
772 |
< |
* @throws NullPointerException if tasks or any element are null. |
773 |
< |
* @throws RuntimeException or Error if any task did so. |
937 |
> |
* Tries to unschedule this task for execution. This method will |
938 |
> |
* typically succeed if this task is the most recently forked task |
939 |
> |
* by the current thread, and has not commenced executing in |
940 |
> |
* another thread. This method may be useful when arranging |
941 |
> |
* alternative local processing of tasks that could have been, but |
942 |
> |
* were not, stolen. |
943 |
> |
* |
944 |
> |
* <p>This method may be invoked only from within {@code |
945 |
> |
* ForkJoinTask} computations (as may be determined using method |
946 |
> |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
947 |
> |
* result in exceptions or errors, possibly including {@code |
948 |
> |
* ClassCastException}. |
949 |
> |
* |
950 |
> |
* @return {@code true} if unforked |
951 |
|
*/ |
952 |
< |
public static void invokeAll(Collection<? extends ForkJoinTask<?>> tasks) { |
953 |
< |
if (!(tasks instanceof List)) { |
954 |
< |
invokeAll(tasks.toArray(new ForkJoinTask[tasks.size()])); |
778 |
< |
return; |
779 |
< |
} |
780 |
< |
List<? extends ForkJoinTask<?>> ts = |
781 |
< |
(List<? extends ForkJoinTask<?>>)tasks; |
782 |
< |
Throwable ex = null; |
783 |
< |
int last = ts.size() - 1; |
784 |
< |
for (int i = last; i >= 0; --i) { |
785 |
< |
ForkJoinTask<?> t = ts.get(i); |
786 |
< |
if (t == null) { |
787 |
< |
if (ex == null) |
788 |
< |
ex = new NullPointerException(); |
789 |
< |
} |
790 |
< |
else if (i != 0) |
791 |
< |
t.fork(); |
792 |
< |
else { |
793 |
< |
t.quietlyInvoke(); |
794 |
< |
if (ex == null) |
795 |
< |
ex = t.getException(); |
796 |
< |
} |
797 |
< |
} |
798 |
< |
for (int i = 1; i <= last; ++i) { |
799 |
< |
ForkJoinTask<?> t = ts.get(i); |
800 |
< |
if (t != null) { |
801 |
< |
if (ex != null) |
802 |
< |
t.cancel(false); |
803 |
< |
else { |
804 |
< |
t.quietlyJoin(); |
805 |
< |
if (ex == null) |
806 |
< |
ex = t.getException(); |
807 |
< |
} |
808 |
< |
} |
809 |
< |
} |
810 |
< |
if (ex != null) |
811 |
< |
rethrowException(ex); |
952 |
> |
public boolean tryUnfork() { |
953 |
> |
return ((ForkJoinWorkerThread) Thread.currentThread()) |
954 |
> |
.unpushTask(this); |
955 |
|
} |
956 |
|
|
957 |
|
/** |
958 |
< |
* Possibly executes tasks until the pool hosting the current task |
959 |
< |
* {@link ForkJoinPool#isQuiescent}. This method may be of use in |
960 |
< |
* designs in which many tasks are forked, but none are explicitly |
961 |
< |
* joined, instead executing them until all are processed. |
958 |
> |
* Returns an estimate of the number of tasks that have been |
959 |
> |
* forked by the current worker thread but not yet executed. This |
960 |
> |
* value may be useful for heuristic decisions about whether to |
961 |
> |
* fork other tasks. |
962 |
> |
* |
963 |
> |
* <p>This method may be invoked only from within {@code |
964 |
> |
* ForkJoinTask} computations (as may be determined using method |
965 |
> |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
966 |
> |
* result in exceptions or errors, possibly including {@code |
967 |
> |
* ClassCastException}. |
968 |
> |
* |
969 |
> |
* @return the number of tasks |
970 |
|
*/ |
971 |
< |
public static void helpQuiesce() { |
972 |
< |
((ForkJoinWorkerThread)(Thread.currentThread())). |
973 |
< |
helpQuiescePool(); |
971 |
> |
public static int getQueuedTaskCount() { |
972 |
> |
return ((ForkJoinWorkerThread) Thread.currentThread()) |
973 |
> |
.getQueueSize(); |
974 |
|
} |
975 |
|
|
976 |
|
/** |
977 |
< |
* Returns a estimate of how many more locally queued tasks are |
977 |
> |
* Returns an estimate of how many more locally queued tasks are |
978 |
|
* held by the current worker thread than there are other worker |
979 |
< |
* threads that might want to steal them. This value may be |
980 |
< |
* useful for heuristic decisions about whether to fork other |
981 |
< |
* tasks. In many usages of ForkJoinTasks, at steady state, each |
982 |
< |
* worker should aim to maintain a small constant surplus (for |
983 |
< |
* example, 3) of tasks, and to process computations locally if |
984 |
< |
* this threshold is exceeded. |
979 |
> |
* threads that might steal them. This value may be useful for |
980 |
> |
* heuristic decisions about whether to fork other tasks. In many |
981 |
> |
* usages of ForkJoinTasks, at steady state, each worker should |
982 |
> |
* aim to maintain a small constant surplus (for example, 3) of |
983 |
> |
* tasks, and to process computations locally if this threshold is |
984 |
> |
* exceeded. |
985 |
> |
* |
986 |
> |
* <p>This method may be invoked only from within {@code |
987 |
> |
* ForkJoinTask} computations (as may be determined using method |
988 |
> |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
989 |
> |
* result in exceptions or errors, possibly including {@code |
990 |
> |
* ClassCastException}. |
991 |
> |
* |
992 |
|
* @return the surplus number of tasks, which may be negative |
993 |
|
*/ |
994 |
< |
public static int surplus() { |
995 |
< |
return ((ForkJoinWorkerThread)(Thread.currentThread())) |
994 |
> |
public static int getSurplusQueuedTaskCount() { |
995 |
> |
return ((ForkJoinWorkerThread) Thread.currentThread()) |
996 |
|
.getEstimatedSurplusTaskCount(); |
997 |
|
} |
998 |
|
|
999 |
< |
// Extension kit |
999 |
> |
// Extension methods |
1000 |
|
|
1001 |
|
/** |
1002 |
< |
* Returns the result that would be returned by <tt>join</tt>, or |
1003 |
< |
* null if this task is not known to have been completed. This |
1004 |
< |
* method is designed to aid debugging, as well as to support |
1005 |
< |
* extensions. Its use in any other context is discouraged. |
1002 |
> |
* Returns the result that would be returned by {@link #join}, even |
1003 |
> |
* if this task completed abnormally, or {@code null} if this task |
1004 |
> |
* is not known to have been completed. This method is designed |
1005 |
> |
* to aid debugging, as well as to support extensions. Its use in |
1006 |
> |
* any other context is discouraged. |
1007 |
|
* |
1008 |
< |
* @return the result, or null if not completed. |
1008 |
> |
* @return the result, or {@code null} if not completed |
1009 |
|
*/ |
1010 |
|
public abstract V getRawResult(); |
1011 |
|
|
1024 |
|
* called otherwise. The return value controls whether this task |
1025 |
|
* is considered to be done normally. It may return false in |
1026 |
|
* asynchronous actions that require explicit invocations of |
1027 |
< |
* <tt>complete</tt> to become joinable. It may throw exceptions |
1027 |
> |
* {@link #complete} to become joinable. It may throw exceptions |
1028 |
|
* to indicate abnormal exit. |
1029 |
< |
* @return true if completed normally |
1029 |
> |
* |
1030 |
> |
* @return {@code true} if completed normally |
1031 |
|
* @throws Error or RuntimeException if encountered during computation |
1032 |
|
*/ |
1033 |
|
protected abstract boolean exec(); |
1034 |
|
|
1035 |
+ |
/** |
1036 |
+ |
* Returns, but does not unschedule or execute, a task queued by |
1037 |
+ |
* the current thread but not yet executed, if one is immediately |
1038 |
+ |
* available. There is no guarantee that this task will actually |
1039 |
+ |
* be polled or executed next. Conversely, this method may return |
1040 |
+ |
* null even if a task exists but cannot be accessed without |
1041 |
+ |
* contention with other threads. This method is designed |
1042 |
+ |
* primarily to support extensions, and is unlikely to be useful |
1043 |
+ |
* otherwise. |
1044 |
+ |
* |
1045 |
+ |
* <p>This method may be invoked only from within {@code |
1046 |
+ |
* ForkJoinTask} computations (as may be determined using method |
1047 |
+ |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
1048 |
+ |
* result in exceptions or errors, possibly including {@code |
1049 |
+ |
* ClassCastException}. |
1050 |
+ |
* |
1051 |
+ |
* @return the next task, or {@code null} if none are available |
1052 |
+ |
*/ |
1053 |
+ |
protected static ForkJoinTask<?> peekNextLocalTask() { |
1054 |
+ |
return ((ForkJoinWorkerThread) Thread.currentThread()) |
1055 |
+ |
.peekTask(); |
1056 |
+ |
} |
1057 |
+ |
|
1058 |
+ |
/** |
1059 |
+ |
* Unschedules and returns, without executing, the next task |
1060 |
+ |
* queued by the current thread but not yet executed. This method |
1061 |
+ |
* is designed primarily to support extensions, and is unlikely to |
1062 |
+ |
* be useful otherwise. |
1063 |
+ |
* |
1064 |
+ |
* <p>This method may be invoked only from within {@code |
1065 |
+ |
* ForkJoinTask} computations (as may be determined using method |
1066 |
+ |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
1067 |
+ |
* result in exceptions or errors, possibly including {@code |
1068 |
+ |
* ClassCastException}. |
1069 |
+ |
* |
1070 |
+ |
* @return the next task, or {@code null} if none are available |
1071 |
+ |
*/ |
1072 |
+ |
protected static ForkJoinTask<?> pollNextLocalTask() { |
1073 |
+ |
return ((ForkJoinWorkerThread) Thread.currentThread()) |
1074 |
+ |
.pollLocalTask(); |
1075 |
+ |
} |
1076 |
+ |
|
1077 |
+ |
/** |
1078 |
+ |
* Unschedules and returns, without executing, the next task |
1079 |
+ |
* queued by the current thread but not yet executed, if one is |
1080 |
+ |
* available, or if not available, a task that was forked by some |
1081 |
+ |
* other thread, if available. Availability may be transient, so a |
1082 |
+ |
* {@code null} result does not necessarily imply quiescence |
1083 |
+ |
* of the pool this task is operating in. This method is designed |
1084 |
+ |
* primarily to support extensions, and is unlikely to be useful |
1085 |
+ |
* otherwise. |
1086 |
+ |
* |
1087 |
+ |
* <p>This method may be invoked only from within {@code |
1088 |
+ |
* ForkJoinTask} computations (as may be determined using method |
1089 |
+ |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
1090 |
+ |
* result in exceptions or errors, possibly including {@code |
1091 |
+ |
* ClassCastException}. |
1092 |
+ |
* |
1093 |
+ |
* @return a task, or {@code null} if none are available |
1094 |
+ |
*/ |
1095 |
+ |
protected static ForkJoinTask<?> pollTask() { |
1096 |
+ |
return ((ForkJoinWorkerThread) Thread.currentThread()) |
1097 |
+ |
.pollTask(); |
1098 |
+ |
} |
1099 |
+ |
|
1100 |
+ |
/** |
1101 |
+ |
* Adaptor for Runnables. This implements RunnableFuture |
1102 |
+ |
* to be compliant with AbstractExecutorService constraints |
1103 |
+ |
* when used in ForkJoinPool. |
1104 |
+ |
*/ |
1105 |
+ |
static final class AdaptedRunnable<T> extends ForkJoinTask<T> |
1106 |
+ |
implements RunnableFuture<T> { |
1107 |
+ |
final Runnable runnable; |
1108 |
+ |
final T resultOnCompletion; |
1109 |
+ |
T result; |
1110 |
+ |
AdaptedRunnable(Runnable runnable, T result) { |
1111 |
+ |
if (runnable == null) throw new NullPointerException(); |
1112 |
+ |
this.runnable = runnable; |
1113 |
+ |
this.resultOnCompletion = result; |
1114 |
+ |
} |
1115 |
+ |
public T getRawResult() { return result; } |
1116 |
+ |
public void setRawResult(T v) { result = v; } |
1117 |
+ |
public boolean exec() { |
1118 |
+ |
runnable.run(); |
1119 |
+ |
result = resultOnCompletion; |
1120 |
+ |
return true; |
1121 |
+ |
} |
1122 |
+ |
public void run() { invoke(); } |
1123 |
+ |
private static final long serialVersionUID = 5232453952276885070L; |
1124 |
+ |
} |
1125 |
+ |
|
1126 |
+ |
/** |
1127 |
+ |
* Adaptor for Callables |
1128 |
+ |
*/ |
1129 |
+ |
static final class AdaptedCallable<T> extends ForkJoinTask<T> |
1130 |
+ |
implements RunnableFuture<T> { |
1131 |
+ |
final Callable<? extends T> callable; |
1132 |
+ |
T result; |
1133 |
+ |
AdaptedCallable(Callable<? extends T> callable) { |
1134 |
+ |
if (callable == null) throw new NullPointerException(); |
1135 |
+ |
this.callable = callable; |
1136 |
+ |
} |
1137 |
+ |
public T getRawResult() { return result; } |
1138 |
+ |
public void setRawResult(T v) { result = v; } |
1139 |
+ |
public boolean exec() { |
1140 |
+ |
try { |
1141 |
+ |
result = callable.call(); |
1142 |
+ |
return true; |
1143 |
+ |
} catch (Error err) { |
1144 |
+ |
throw err; |
1145 |
+ |
} catch (RuntimeException rex) { |
1146 |
+ |
throw rex; |
1147 |
+ |
} catch (Exception ex) { |
1148 |
+ |
throw new RuntimeException(ex); |
1149 |
+ |
} |
1150 |
+ |
} |
1151 |
+ |
public void run() { invoke(); } |
1152 |
+ |
private static final long serialVersionUID = 2838392045355241008L; |
1153 |
+ |
} |
1154 |
+ |
|
1155 |
+ |
/** |
1156 |
+ |
* Returns a new {@code ForkJoinTask} that performs the {@code run} |
1157 |
+ |
* method of the given {@code Runnable} as its action, and returns |
1158 |
+ |
* a null result upon {@link #join}. |
1159 |
+ |
* |
1160 |
+ |
* @param runnable the runnable action |
1161 |
+ |
* @return the task |
1162 |
+ |
*/ |
1163 |
+ |
public static ForkJoinTask<?> adapt(Runnable runnable) { |
1164 |
+ |
return new AdaptedRunnable<Void>(runnable, null); |
1165 |
+ |
} |
1166 |
+ |
|
1167 |
+ |
/** |
1168 |
+ |
* Returns a new {@code ForkJoinTask} that performs the {@code run} |
1169 |
+ |
* method of the given {@code Runnable} as its action, and returns |
1170 |
+ |
* the given result upon {@link #join}. |
1171 |
+ |
* |
1172 |
+ |
* @param runnable the runnable action |
1173 |
+ |
* @param result the result upon completion |
1174 |
+ |
* @return the task |
1175 |
+ |
*/ |
1176 |
+ |
public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) { |
1177 |
+ |
return new AdaptedRunnable<T>(runnable, result); |
1178 |
+ |
} |
1179 |
+ |
|
1180 |
+ |
/** |
1181 |
+ |
* Returns a new {@code ForkJoinTask} that performs the {@code call} |
1182 |
+ |
* method of the given {@code Callable} as its action, and returns |
1183 |
+ |
* its result upon {@link #join}, translating any checked exceptions |
1184 |
+ |
* encountered into {@code RuntimeException}. |
1185 |
+ |
* |
1186 |
+ |
* @param callable the callable action |
1187 |
+ |
* @return the task |
1188 |
+ |
*/ |
1189 |
+ |
public static <T> ForkJoinTask<T> adapt(Callable<? extends T> callable) { |
1190 |
+ |
return new AdaptedCallable<T>(callable); |
1191 |
+ |
} |
1192 |
+ |
|
1193 |
|
// Serialization support |
1194 |
|
|
1195 |
|
private static final long serialVersionUID = -7721805057305804111L; |
1198 |
|
* Save the state to a stream. |
1199 |
|
* |
1200 |
|
* @serialData the current run status and the exception thrown |
1201 |
< |
* during execution, or null if none. |
1201 |
> |
* during execution, or {@code null} if none |
1202 |
|
* @param s the stream |
1203 |
|
*/ |
1204 |
|
private void writeObject(java.io.ObjectOutputStream s) |
1209 |
|
|
1210 |
|
/** |
1211 |
|
* Reconstitute the instance from a stream. |
1212 |
+ |
* |
1213 |
|
* @param s the stream |
1214 |
|
*/ |
1215 |
|
private void readObject(java.io.ObjectInputStream s) |
1216 |
|
throws java.io.IOException, ClassNotFoundException { |
1217 |
|
s.defaultReadObject(); |
1218 |
< |
// status &= ~INTERNAL_SIGNAL_MASK; // todo: define policy |
1218 |
> |
status &= ~INTERNAL_SIGNAL_MASK; // clear internal signal counts |
1219 |
> |
status |= EXTERNAL_SIGNAL; // conservatively set external signal |
1220 |
|
Object ex = s.readObject(); |
1221 |
|
if (ex != null) |
1222 |
< |
setDoneExceptionally((Throwable)ex); |
1222 |
> |
setDoneExceptionally((Throwable) ex); |
1223 |
|
} |
1224 |
|
|
1225 |
< |
// Temporary Unsafe mechanics for preliminary release |
1225 |
> |
// Unsafe mechanics |
1226 |
|
|
1227 |
< |
static final Unsafe _unsafe; |
1228 |
< |
static final long statusOffset; |
1227 |
> |
private static final sun.misc.Unsafe UNSAFE = getUnsafe(); |
1228 |
> |
private static final long statusOffset = |
1229 |
> |
objectFieldOffset("status", ForkJoinTask.class); |
1230 |
|
|
1231 |
< |
static { |
1231 |
> |
private static long objectFieldOffset(String field, Class<?> klazz) { |
1232 |
|
try { |
1233 |
< |
if (ForkJoinTask.class.getClassLoader() != null) { |
1234 |
< |
Field f = Unsafe.class.getDeclaredField("theUnsafe"); |
1235 |
< |
f.setAccessible(true); |
1236 |
< |
_unsafe = (Unsafe)f.get(null); |
1237 |
< |
} |
1238 |
< |
else |
1239 |
< |
_unsafe = Unsafe.getUnsafe(); |
919 |
< |
statusOffset = _unsafe.objectFieldOffset |
920 |
< |
(ForkJoinTask.class.getDeclaredField("status")); |
921 |
< |
} catch (Exception ex) { throw new Error(ex); } |
1233 |
> |
return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field)); |
1234 |
> |
} catch (NoSuchFieldException e) { |
1235 |
> |
// Convert Exception to corresponding Error |
1236 |
> |
NoSuchFieldError error = new NoSuchFieldError(field); |
1237 |
> |
error.initCause(e); |
1238 |
> |
throw error; |
1239 |
> |
} |
1240 |
|
} |
1241 |
|
|
1242 |
+ |
/** |
1243 |
+ |
* Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package. |
1244 |
+ |
* Replace with a simple call to Unsafe.getUnsafe when integrating |
1245 |
+ |
* into a jdk. |
1246 |
+ |
* |
1247 |
+ |
* @return a sun.misc.Unsafe |
1248 |
+ |
*/ |
1249 |
+ |
private static sun.misc.Unsafe getUnsafe() { |
1250 |
+ |
try { |
1251 |
+ |
return sun.misc.Unsafe.getUnsafe(); |
1252 |
+ |
} catch (SecurityException se) { |
1253 |
+ |
try { |
1254 |
+ |
return java.security.AccessController.doPrivileged |
1255 |
+ |
(new java.security |
1256 |
+ |
.PrivilegedExceptionAction<sun.misc.Unsafe>() { |
1257 |
+ |
public sun.misc.Unsafe run() throws Exception { |
1258 |
+ |
java.lang.reflect.Field f = sun.misc |
1259 |
+ |
.Unsafe.class.getDeclaredField("theUnsafe"); |
1260 |
+ |
f.setAccessible(true); |
1261 |
+ |
return (sun.misc.Unsafe) f.get(null); |
1262 |
+ |
}}); |
1263 |
+ |
} catch (java.security.PrivilegedActionException e) { |
1264 |
+ |
throw new RuntimeException("Could not initialize intrinsics", |
1265 |
+ |
e.getCause()); |
1266 |
+ |
} |
1267 |
+ |
} |
1268 |
+ |
} |
1269 |
|
} |