6 |
|
|
7 |
|
package jsr166y; |
8 |
|
|
9 |
– |
import java.util.concurrent.*; |
10 |
– |
|
9 |
|
import java.io.Serializable; |
10 |
|
import java.util.Collection; |
11 |
|
import java.util.Collections; |
12 |
|
import java.util.List; |
13 |
+ |
import java.util.RandomAccess; |
14 |
|
import java.util.Map; |
15 |
< |
import java.util.WeakHashMap; |
15 |
> |
import java.lang.ref.WeakReference; |
16 |
> |
import java.lang.ref.ReferenceQueue; |
17 |
> |
import java.util.concurrent.Callable; |
18 |
> |
import java.util.concurrent.CancellationException; |
19 |
> |
import java.util.concurrent.ExecutionException; |
20 |
> |
import java.util.concurrent.Executor; |
21 |
> |
import java.util.concurrent.ExecutorService; |
22 |
> |
import java.util.concurrent.Future; |
23 |
> |
import java.util.concurrent.RejectedExecutionException; |
24 |
> |
import java.util.concurrent.RunnableFuture; |
25 |
> |
import java.util.concurrent.TimeUnit; |
26 |
> |
import java.util.concurrent.TimeoutException; |
27 |
> |
import java.util.concurrent.locks.ReentrantLock; |
28 |
> |
import java.lang.reflect.Constructor; |
29 |
|
|
30 |
|
/** |
31 |
< |
* Abstract base class for tasks that run within a {@link |
32 |
< |
* ForkJoinPool}. A ForkJoinTask is a thread-like entity that is much |
31 |
> |
* Abstract base class for tasks that run within a {@link ForkJoinPool}. |
32 |
> |
* A {@code ForkJoinTask} is a thread-like entity that is much |
33 |
|
* lighter weight than a normal thread. Huge numbers of tasks and |
34 |
|
* subtasks may be hosted by a small number of actual threads in a |
35 |
|
* ForkJoinPool, at the price of some usage limitations. |
36 |
|
* |
37 |
< |
* <p> A "main" ForkJoinTask begins execution when submitted to a |
38 |
< |
* {@link ForkJoinPool}. Once started, it will usually in turn start |
39 |
< |
* other subtasks. As indicated by the name of this class, many |
40 |
< |
* programs using ForkJoinTasks employ only methods {@code fork} |
41 |
< |
* and {@code join}, or derivatives such as |
42 |
< |
* {@code invokeAll}. However, this class also provides a number |
43 |
< |
* of other methods that can come into play in advanced usages, as |
44 |
< |
* well as extension mechanics that allow support of new forms of |
45 |
< |
* fork/join processing. |
37 |
> |
* <p>A "main" {@code ForkJoinTask} begins execution when submitted |
38 |
> |
* to a {@link ForkJoinPool}. Once started, it will usually in turn |
39 |
> |
* start other subtasks. As indicated by the name of this class, |
40 |
> |
* many programs using {@code ForkJoinTask} employ only methods |
41 |
> |
* {@link #fork} and {@link #join}, or derivatives such as {@link |
42 |
> |
* #invokeAll(ForkJoinTask...) invokeAll}. However, this class also |
43 |
> |
* provides a number of other methods that can come into play in |
44 |
> |
* advanced usages, as well as extension mechanics that allow |
45 |
> |
* support of new forms of fork/join processing. |
46 |
|
* |
47 |
< |
* <p>A ForkJoinTask is a lightweight form of {@link Future}. The |
48 |
< |
* efficiency of ForkJoinTasks stems from a set of restrictions (that |
49 |
< |
* are only partially statically enforceable) reflecting their |
50 |
< |
* intended use as computational tasks calculating pure functions or |
51 |
< |
* operating on purely isolated objects. The primary coordination |
52 |
< |
* mechanisms are {@link #fork}, that arranges asynchronous execution, |
53 |
< |
* and {@link #join}, that doesn't proceed until the task's result has |
54 |
< |
* been computed. Computations should avoid {@code synchronized} |
55 |
< |
* methods or blocks, and should minimize other blocking |
56 |
< |
* synchronization apart from joining other tasks or using |
57 |
< |
* synchronizers such as Phasers that are advertised to cooperate with |
58 |
< |
* fork/join scheduling. Tasks should also not perform blocking IO, |
59 |
< |
* and should ideally access variables that are completely independent |
60 |
< |
* of those accessed by other running tasks. Minor breaches of these |
61 |
< |
* restrictions, for example using shared output streams, may be |
62 |
< |
* tolerable in practice, but frequent use may result in poor |
63 |
< |
* performance, and the potential to indefinitely stall if the number |
64 |
< |
* of threads not waiting for IO or other external synchronization |
65 |
< |
* becomes exhausted. This usage restriction is in part enforced by |
66 |
< |
* not permitting checked exceptions such as {@code IOExceptions} |
67 |
< |
* to be thrown. However, computations may still encounter unchecked |
68 |
< |
* exceptions, that are rethrown to callers attempting join |
69 |
< |
* them. These exceptions may additionally include |
70 |
< |
* RejectedExecutionExceptions stemming from internal resource |
71 |
< |
* exhaustion such as failure to allocate internal task queues. |
47 |
> |
* <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}. |
48 |
> |
* The efficiency of {@code ForkJoinTask}s stems from a set of |
49 |
> |
* restrictions (that are only partially statically enforceable) |
50 |
> |
* reflecting their intended use as computational tasks calculating |
51 |
> |
* pure functions or operating on purely isolated objects. The |
52 |
> |
* primary coordination mechanisms are {@link #fork}, that arranges |
53 |
> |
* asynchronous execution, and {@link #join}, that doesn't proceed |
54 |
> |
* until the task's result has been computed. Computations should |
55 |
> |
* avoid {@code synchronized} methods or blocks, and should minimize |
56 |
> |
* other blocking synchronization apart from joining other tasks or |
57 |
> |
* using synchronizers such as Phasers that are advertised to |
58 |
> |
* cooperate with fork/join scheduling. Tasks should also not perform |
59 |
> |
* blocking IO, and should ideally access variables that are |
60 |
> |
* completely independent of those accessed by other running |
61 |
> |
* tasks. Minor breaches of these restrictions, for example using |
62 |
> |
* shared output streams, may be tolerable in practice, but frequent |
63 |
> |
* use may result in poor performance, and the potential to |
64 |
> |
* indefinitely stall if the number of threads not waiting for IO or |
65 |
> |
* other external synchronization becomes exhausted. This usage |
66 |
> |
* restriction is in part enforced by not permitting checked |
67 |
> |
* exceptions such as {@code IOExceptions} to be thrown. However, |
68 |
> |
* computations may still encounter unchecked exceptions, that are |
69 |
> |
* rethrown to callers attempting to join them. These exceptions may |
70 |
> |
* additionally include {@link RejectedExecutionException} stemming |
71 |
> |
* from internal resource exhaustion, such as failure to allocate |
72 |
> |
* internal task queues. Rethrown exceptions behave in the same way as |
73 |
> |
* regular exceptions, but, when possible, contain stack traces (as |
74 |
> |
* displayed for example using {@code ex.printStackTrace()}) of both |
75 |
> |
* the thread that initiated the computation as well as the thread |
76 |
> |
* actually encountering the exception; minimally only the latter. |
77 |
|
* |
78 |
|
* <p>The primary method for awaiting completion and extracting |
79 |
|
* results of a task is {@link #join}, but there are several variants: |
80 |
|
* The {@link Future#get} methods support interruptible and/or timed |
81 |
|
* waits for completion and report results using {@code Future} |
82 |
< |
* conventions. Method {@link #helpJoin} enables callers to actively |
83 |
< |
* execute other tasks while awaiting joins, which is sometimes more |
84 |
< |
* efficient but only applies when all subtasks are known to be |
85 |
< |
* strictly tree-structured. Method {@link #invoke} is semantically |
69 |
< |
* equivalent to {@code fork(); join()} but always attempts to |
70 |
< |
* begin execution in the current thread. The "<em>quiet</em>" forms |
71 |
< |
* of these methods do not extract results or report exceptions. These |
82 |
> |
* conventions. Method {@link #invoke} is semantically |
83 |
> |
* equivalent to {@code fork(); join()} but always attempts to begin |
84 |
> |
* execution in the current thread. The "<em>quiet</em>" forms of |
85 |
> |
* these methods do not extract results or report exceptions. These |
86 |
|
* may be useful when a set of tasks are being executed, and you need |
87 |
|
* to delay processing of results or exceptions until all complete. |
88 |
|
* Method {@code invokeAll} (available in multiple versions) |
89 |
|
* performs the most common form of parallel invocation: forking a set |
90 |
|
* of tasks and joining them all. |
91 |
|
* |
92 |
< |
* <p> The ForkJoinTask class is not usually directly subclassed. |
92 |
> |
* <p>The execution status of tasks may be queried at several levels |
93 |
> |
* of detail: {@link #isDone} is true if a task completed in any way |
94 |
> |
* (including the case where a task was cancelled without executing); |
95 |
> |
* {@link #isCompletedNormally} is true if a task completed without |
96 |
> |
* cancellation or encountering an exception; {@link #isCancelled} is |
97 |
> |
* true if the task was cancelled (in which case {@link #getException} |
98 |
> |
* returns a {@link java.util.concurrent.CancellationException}); and |
99 |
> |
* {@link #isCompletedAbnormally} is true if a task was either |
100 |
> |
* cancelled or encountered an exception, in which case {@link |
101 |
> |
* #getException} will return either the encountered exception or |
102 |
> |
* {@link java.util.concurrent.CancellationException}. |
103 |
> |
* |
104 |
> |
* <p>The ForkJoinTask class is not usually directly subclassed. |
105 |
|
* Instead, you subclass one of the abstract classes that support a |
106 |
< |
* particular style of fork/join processing. Normally, a concrete |
106 |
> |
* particular style of fork/join processing, typically {@link |
107 |
> |
* RecursiveAction} for computations that do not return results, or |
108 |
> |
* {@link RecursiveTask} for those that do. Normally, a concrete |
109 |
|
* ForkJoinTask subclass declares fields comprising its parameters, |
110 |
|
* established in a constructor, and then defines a {@code compute} |
111 |
|
* method that somehow uses the control methods supplied by this base |
112 |
|
* class. While these methods have {@code public} access (to allow |
113 |
< |
* instances of different task subclasses to call each others |
113 |
> |
* instances of different task subclasses to call each other's |
114 |
|
* methods), some of them may only be called from within other |
115 |
|
* ForkJoinTasks (as may be determined using method {@link |
116 |
|
* #inForkJoinPool}). Attempts to invoke them in other contexts |
117 |
|
* result in exceptions or errors, possibly including |
118 |
< |
* ClassCastException. |
118 |
> |
* {@code ClassCastException}. |
119 |
|
* |
120 |
< |
* <p>Most base support methods are {@code final} because their |
121 |
< |
* implementations are intrinsically tied to the underlying |
122 |
< |
* lightweight task scheduling framework, and so cannot be overridden. |
123 |
< |
* Developers creating new basic styles of fork/join processing should |
124 |
< |
* minimally implement {@code protected} methods |
125 |
< |
* {@code exec}, {@code setRawResult}, and |
126 |
< |
* {@code getRawResult}, while also introducing an abstract |
127 |
< |
* computational method that can be implemented in its subclasses, |
128 |
< |
* possibly relying on other {@code protected} methods provided |
129 |
< |
* by this class. |
120 |
> |
* <p>Method {@link #join} and its variants are appropriate for use |
121 |
> |
* only when completion dependencies are acyclic; that is, the |
122 |
> |
* parallel computation can be described as a directed acyclic graph |
123 |
> |
* (DAG). Otherwise, executions may encounter a form of deadlock as |
124 |
> |
* tasks cyclically wait for each other. However, this framework |
125 |
> |
* supports other methods and techniques (for example the use of |
126 |
> |
* {@link Phaser}, {@link #helpQuiesce}, and {@link #complete}) that |
127 |
> |
* may be of use in constructing custom subclasses for problems that |
128 |
> |
* are not statically structured as DAGs. |
129 |
> |
* |
130 |
> |
* <p>Most base support methods are {@code final}, to prevent |
131 |
> |
* overriding of implementations that are intrinsically tied to the |
132 |
> |
* underlying lightweight task scheduling framework. Developers |
133 |
> |
* creating new basic styles of fork/join processing should minimally |
134 |
> |
* implement {@code protected} methods {@link #exec}, {@link |
135 |
> |
* #setRawResult}, and {@link #getRawResult}, while also introducing |
136 |
> |
* an abstract computational method that can be implemented in its |
137 |
> |
* subclasses, possibly relying on other {@code protected} methods |
138 |
> |
* provided by this class. |
139 |
|
* |
140 |
|
* <p>ForkJoinTasks should perform relatively small amounts of |
141 |
< |
* computations, otherwise splitting into smaller tasks. As a very |
142 |
< |
* rough rule of thumb, a task should perform more than 100 and less |
143 |
< |
* than 10000 basic computational steps. If tasks are too big, then |
144 |
< |
* parallelism cannot improve throughput. If too small, then memory |
145 |
< |
* and internal task maintenance overhead may overwhelm processing. |
141 |
> |
* computation. Large tasks should be split into smaller subtasks, |
142 |
> |
* usually via recursive decomposition. As a very rough rule of thumb, |
143 |
> |
* a task should perform more than 100 and less than 10000 basic |
144 |
> |
* computational steps, and should avoid indefinite looping. If tasks |
145 |
> |
* are too big, then parallelism cannot improve throughput. If too |
146 |
> |
* small, then memory and internal task maintenance overhead may |
147 |
> |
* overwhelm processing. |
148 |
> |
* |
149 |
> |
* <p>This class provides {@code adapt} methods for {@link Runnable} |
150 |
> |
* and {@link Callable}, that may be of use when mixing execution of |
151 |
> |
* {@code ForkJoinTasks} with other kinds of tasks. When all tasks are |
152 |
> |
* of this form, consider using a pool constructed in <em>asyncMode</em>. |
153 |
|
* |
154 |
< |
* <p>ForkJoinTasks are {@code Serializable}, which enables them |
155 |
< |
* to be used in extensions such as remote execution frameworks. It is |
156 |
< |
* in general sensible to serialize tasks only before or after, but |
157 |
< |
* not during execution. Serialization is not relied on during |
114 |
< |
* execution itself. |
154 |
> |
* <p>ForkJoinTasks are {@code Serializable}, which enables them to be |
155 |
> |
* used in extensions such as remote execution frameworks. It is |
156 |
> |
* sensible to serialize tasks only before or after, but not during, |
157 |
> |
* execution. Serialization is not relied on during execution itself. |
158 |
|
* |
159 |
|
* @since 1.7 |
160 |
|
* @author Doug Lea |
161 |
|
*/ |
162 |
|
public abstract class ForkJoinTask<V> implements Future<V>, Serializable { |
163 |
|
|
164 |
< |
/** |
165 |
< |
* Run control status bits packed into a single int to minimize |
166 |
< |
* footprint and to ensure atomicity (via CAS). Status is |
167 |
< |
* initially zero, and takes on nonnegative values until |
168 |
< |
* completed, upon which status holds COMPLETED. CANCELLED, or |
169 |
< |
* EXCEPTIONAL, which use the top 3 bits. Tasks undergoing |
170 |
< |
* blocking waits by other threads have SIGNAL_MASK bits set -- |
171 |
< |
* bit 15 for external (nonFJ) waits, and the rest a count of |
172 |
< |
* waiting FJ threads. (This representation relies on |
173 |
< |
* ForkJoinPool max thread limits). Completion of a stolen task |
174 |
< |
* with SIGNAL_MASK bits set awakens waiter via notifyAll. Even |
175 |
< |
* though suboptimal for some purposes, we use basic builtin |
176 |
< |
* wait/notify to take advantage of "monitor inflation" in JVMs |
177 |
< |
* that we would otherwise need to emulate to avoid adding further |
178 |
< |
* per-task bookkeeping overhead. Note that bits 16-28 are |
179 |
< |
* currently unused. Also value 0x80000000 is available as spare |
180 |
< |
* completion value. |
181 |
< |
*/ |
182 |
< |
volatile int status; // accessed directly by pool and workers |
183 |
< |
|
184 |
< |
static final int COMPLETION_MASK = 0xe0000000; |
185 |
< |
static final int NORMAL = 0xe0000000; // == mask |
186 |
< |
static final int CANCELLED = 0xc0000000; |
187 |
< |
static final int EXCEPTIONAL = 0xa0000000; |
188 |
< |
static final int SIGNAL_MASK = 0x0000ffff; |
189 |
< |
static final int INTERNAL_SIGNAL_MASK = 0x00007fff; |
190 |
< |
static final int EXTERNAL_SIGNAL = 0x00008000; // top bit of low word |
148 |
< |
|
149 |
< |
/** |
150 |
< |
* Table of exceptions thrown by tasks, to enable reporting by |
151 |
< |
* callers. Because exceptions are rare, we don't directly keep |
152 |
< |
* them with task objects, but instead use a weak ref table. Note |
153 |
< |
* that cancellation exceptions don't appear in the table, but are |
154 |
< |
* instead recorded as status values. |
155 |
< |
* TODO: Use ConcurrentReferenceHashMap |
156 |
< |
*/ |
157 |
< |
static final Map<ForkJoinTask<?>, Throwable> exceptionMap = |
158 |
< |
Collections.synchronizedMap |
159 |
< |
(new WeakHashMap<ForkJoinTask<?>, Throwable>()); |
160 |
< |
|
161 |
< |
// within-package utilities |
162 |
< |
|
163 |
< |
/** |
164 |
< |
* Gets current worker thread, or null if not a worker thread. |
165 |
< |
*/ |
166 |
< |
static ForkJoinWorkerThread getWorker() { |
167 |
< |
Thread t = Thread.currentThread(); |
168 |
< |
return ((t instanceof ForkJoinWorkerThread) ? |
169 |
< |
(ForkJoinWorkerThread) t : null); |
170 |
< |
} |
171 |
< |
|
172 |
< |
final boolean casStatus(int cmp, int val) { |
173 |
< |
return UNSAFE.compareAndSwapInt(this, statusOffset, cmp, val); |
174 |
< |
} |
175 |
< |
|
176 |
< |
/** |
177 |
< |
* Workaround for not being able to rethrow unchecked exceptions. |
164 |
> |
/* |
165 |
> |
* See the internal documentation of class ForkJoinPool for a |
166 |
> |
* general implementation overview. ForkJoinTasks are mainly |
167 |
> |
* responsible for maintaining their "status" field amidst relays |
168 |
> |
* to methods in ForkJoinWorkerThread and ForkJoinPool. The |
169 |
> |
* methods of this class are more-or-less layered into (1) basic |
170 |
> |
* status maintenance (2) execution and awaiting completion (3) |
171 |
> |
* user-level methods that additionally report results. This is |
172 |
> |
* sometimes hard to see because this file orders exported methods |
173 |
> |
* in a way that flows well in javadocs. |
174 |
> |
*/ |
175 |
> |
|
176 |
> |
/* |
177 |
> |
* The status field holds run control status bits packed into a |
178 |
> |
* single int to minimize footprint and to ensure atomicity (via |
179 |
> |
* CAS). Status is initially zero, and takes on nonnegative |
180 |
> |
* values until completed, upon which status holds value |
181 |
> |
* NORMAL, CANCELLED, or EXCEPTIONAL. Tasks undergoing blocking |
182 |
> |
* waits by other threads have the SIGNAL bit set. Completion of |
183 |
> |
* a stolen task with SIGNAL set awakens any waiters via |
184 |
> |
* notifyAll. Even though suboptimal for some purposes, we use |
185 |
> |
* basic builtin wait/notify to take advantage of "monitor |
186 |
> |
* inflation" in JVMs that we would otherwise need to emulate to |
187 |
> |
* avoid adding further per-task bookkeeping overhead. We want |
188 |
> |
* these monitors to be "fat", i.e., not use biasing or thin-lock |
189 |
> |
* techniques, so use some odd coding idioms that tend to avoid |
190 |
> |
* them. |
191 |
|
*/ |
179 |
– |
static void rethrowException(Throwable ex) { |
180 |
– |
if (ex != null) |
181 |
– |
UNSAFE.throwException(ex); |
182 |
– |
} |
192 |
|
|
193 |
< |
// Setting completion status |
193 |
> |
/** The run status of this task */ |
194 |
> |
volatile int status; // accessed directly by pool and workers |
195 |
> |
private static final int NORMAL = -1; |
196 |
> |
private static final int CANCELLED = -2; |
197 |
> |
private static final int EXCEPTIONAL = -3; |
198 |
> |
private static final int SIGNAL = 1; |
199 |
|
|
200 |
|
/** |
201 |
< |
* Marks completion and wakes up threads waiting to join this task. |
201 |
> |
* Marks completion and wakes up threads waiting to join this task, |
202 |
> |
* also clearing signal request bits. |
203 |
|
* |
204 |
|
* @param completion one of NORMAL, CANCELLED, EXCEPTIONAL |
205 |
+ |
* @return completion status on exit |
206 |
|
*/ |
207 |
< |
final void setCompletion(int completion) { |
208 |
< |
ForkJoinPool pool = getPool(); |
209 |
< |
if (pool != null) { |
210 |
< |
int s; // Clear signal bits while setting completion status |
211 |
< |
do {} while ((s = status) >= 0 && !casStatus(s, completion)); |
212 |
< |
|
213 |
< |
if ((s & SIGNAL_MASK) != 0) { |
214 |
< |
if ((s &= INTERNAL_SIGNAL_MASK) != 0) |
199 |
< |
pool.updateRunningCount(s); |
200 |
< |
synchronized (this) { notifyAll(); } |
207 |
> |
private int setCompletion(int completion) { |
208 |
> |
for (int s;;) { |
209 |
> |
if ((s = status) < 0) |
210 |
> |
return s; |
211 |
> |
if (UNSAFE.compareAndSwapInt(this, statusOffset, s, completion)) { |
212 |
> |
if (s != 0) |
213 |
> |
synchronized (this) { notifyAll(); } |
214 |
> |
return completion; |
215 |
|
} |
216 |
|
} |
203 |
– |
else |
204 |
– |
externallySetCompletion(completion); |
217 |
|
} |
218 |
|
|
219 |
|
/** |
220 |
< |
* Version of setCompletion for non-FJ threads. Leaves signal |
221 |
< |
* bits for unblocked threads to adjust, and always notifies. |
220 |
> |
* Tries to block a worker thread until completed or timed out. |
221 |
> |
* Uses Object.wait time argument conventions. |
222 |
> |
* May fail on contention or interrupt. |
223 |
> |
* |
224 |
> |
* @param millis if > 0, wait time. |
225 |
|
*/ |
226 |
< |
private void externallySetCompletion(int completion) { |
226 |
> |
final void tryAwaitDone(long millis) { |
227 |
|
int s; |
213 |
– |
do {} while ((s = status) >= 0 && |
214 |
– |
!casStatus(s, (s & SIGNAL_MASK) | completion)); |
215 |
– |
synchronized (this) { notifyAll(); } |
216 |
– |
} |
217 |
– |
|
218 |
– |
/** |
219 |
– |
* Sets status to indicate normal completion. |
220 |
– |
*/ |
221 |
– |
final void setNormalCompletion() { |
222 |
– |
// Try typical fast case -- single CAS, no signal, not already done. |
223 |
– |
// Manually expand casStatus to improve chances of inlining it |
224 |
– |
if (!UNSAFE.compareAndSwapInt(this, statusOffset, 0, NORMAL)) |
225 |
– |
setCompletion(NORMAL); |
226 |
– |
} |
227 |
– |
|
228 |
– |
// internal waiting and notification |
229 |
– |
|
230 |
– |
/** |
231 |
– |
* Performs the actual monitor wait for awaitDone. |
232 |
– |
*/ |
233 |
– |
private void doAwaitDone() { |
234 |
– |
// Minimize lock bias and in/de-flation effects by maximizing |
235 |
– |
// chances of waiting inside sync |
228 |
|
try { |
229 |
< |
while (status >= 0) |
230 |
< |
synchronized (this) { if (status >= 0) wait(); } |
231 |
< |
} catch (InterruptedException ie) { |
232 |
< |
onInterruptedWait(); |
233 |
< |
} |
234 |
< |
} |
235 |
< |
|
244 |
< |
/** |
245 |
< |
* Performs the actual timed monitor wait for awaitDone. |
246 |
< |
*/ |
247 |
< |
private void doAwaitDone(long startTime, long nanos) { |
248 |
< |
synchronized (this) { |
249 |
< |
try { |
250 |
< |
while (status >= 0) { |
251 |
< |
long nt = nanos - System.nanoTime() - startTime; |
252 |
< |
if (nt <= 0) |
253 |
< |
break; |
254 |
< |
wait(nt / 1000000, (int) (nt % 1000000)); |
229 |
> |
if (((s = status) > 0 || |
230 |
> |
(s == 0 && |
231 |
> |
UNSAFE.compareAndSwapInt(this, statusOffset, 0, SIGNAL))) && |
232 |
> |
status > 0) { |
233 |
> |
synchronized (this) { |
234 |
> |
if (status > 0) |
235 |
> |
wait(millis); |
236 |
|
} |
256 |
– |
} catch (InterruptedException ie) { |
257 |
– |
onInterruptedWait(); |
237 |
|
} |
238 |
+ |
} catch (InterruptedException ie) { |
239 |
+ |
// caller must check termination |
240 |
|
} |
241 |
|
} |
242 |
|
|
262 |
– |
// Awaiting completion |
263 |
– |
|
243 |
|
/** |
244 |
< |
* Sets status to indicate there is joiner, then waits for join, |
245 |
< |
* surrounded with pool notifications. |
267 |
< |
* |
268 |
< |
* @return status upon exit |
244 |
> |
* Blocks a non-worker-thread until completion. |
245 |
> |
* @return status upon completion |
246 |
|
*/ |
247 |
< |
private int awaitDone(ForkJoinWorkerThread w, |
271 |
< |
boolean maintainParallelism) { |
272 |
< |
ForkJoinPool pool = (w == null) ? null : w.pool; |
247 |
> |
private int externalAwaitDone() { |
248 |
|
int s; |
249 |
< |
while ((s = status) >= 0) { |
250 |
< |
if (casStatus(s, (pool == null) ? s|EXTERNAL_SIGNAL : s+1)) { |
251 |
< |
if (pool == null || !pool.preJoin(this, maintainParallelism)) |
252 |
< |
doAwaitDone(); |
253 |
< |
if (((s = status) & INTERNAL_SIGNAL_MASK) != 0) |
254 |
< |
adjustPoolCountsOnUnblock(pool); |
255 |
< |
break; |
249 |
> |
if ((s = status) >= 0) { |
250 |
> |
boolean interrupted = false; |
251 |
> |
synchronized (this) { |
252 |
> |
while ((s = status) >= 0) { |
253 |
> |
if (s == 0) |
254 |
> |
UNSAFE.compareAndSwapInt(this, statusOffset, |
255 |
> |
0, SIGNAL); |
256 |
> |
else { |
257 |
> |
try { |
258 |
> |
wait(); |
259 |
> |
} catch (InterruptedException ie) { |
260 |
> |
interrupted = true; |
261 |
> |
} |
262 |
> |
} |
263 |
> |
} |
264 |
|
} |
265 |
+ |
if (interrupted) |
266 |
+ |
Thread.currentThread().interrupt(); |
267 |
|
} |
268 |
|
return s; |
269 |
|
} |
270 |
|
|
271 |
|
/** |
272 |
< |
* Timed version of awaitDone |
288 |
< |
* |
289 |
< |
* @return status upon exit |
272 |
> |
* Blocks a non-worker-thread until completion or interruption or timeout. |
273 |
|
*/ |
274 |
< |
private int awaitDone(ForkJoinWorkerThread w, long nanos) { |
275 |
< |
ForkJoinPool pool = (w == null) ? null : w.pool; |
274 |
> |
private int externalInterruptibleAwaitDone(long millis) |
275 |
> |
throws InterruptedException { |
276 |
|
int s; |
277 |
< |
while ((s = status) >= 0) { |
278 |
< |
if (casStatus(s, (pool == null) ? s|EXTERNAL_SIGNAL : s+1)) { |
279 |
< |
long startTime = System.nanoTime(); |
280 |
< |
if (pool == null || !pool.preJoin(this, false)) |
281 |
< |
doAwaitDone(startTime, nanos); |
282 |
< |
if ((s = status) >= 0) { |
283 |
< |
adjustPoolCountsOnCancelledWait(pool); |
284 |
< |
s = status; |
277 |
> |
if (Thread.interrupted()) |
278 |
> |
throw new InterruptedException(); |
279 |
> |
if ((s = status) >= 0) { |
280 |
> |
synchronized (this) { |
281 |
> |
while ((s = status) >= 0) { |
282 |
> |
if (s == 0) |
283 |
> |
UNSAFE.compareAndSwapInt(this, statusOffset, |
284 |
> |
0, SIGNAL); |
285 |
> |
else { |
286 |
> |
wait(millis); |
287 |
> |
if (millis > 0L) |
288 |
> |
break; |
289 |
> |
} |
290 |
|
} |
303 |
– |
if (s < 0 && (s & INTERNAL_SIGNAL_MASK) != 0) |
304 |
– |
adjustPoolCountsOnUnblock(pool); |
305 |
– |
break; |
291 |
|
} |
292 |
|
} |
293 |
|
return s; |
294 |
|
} |
295 |
|
|
296 |
|
/** |
297 |
< |
* Notifies pool that thread is unblocked. Called by signalled |
298 |
< |
* threads when woken by non-FJ threads (which is atypical). |
297 |
> |
* Primary execution method for stolen tasks. Unless done, calls |
298 |
> |
* exec and records status if completed, but doesn't wait for |
299 |
> |
* completion otherwise. |
300 |
|
*/ |
301 |
< |
private void adjustPoolCountsOnUnblock(ForkJoinPool pool) { |
302 |
< |
int s; |
303 |
< |
do {} while ((s = status) < 0 && !casStatus(s, s & COMPLETION_MASK)); |
304 |
< |
if (pool != null && (s &= INTERNAL_SIGNAL_MASK) != 0) |
305 |
< |
pool.updateRunningCount(s); |
301 |
> |
final void doExec() { |
302 |
> |
if (status >= 0) { |
303 |
> |
boolean completed; |
304 |
> |
try { |
305 |
> |
completed = exec(); |
306 |
> |
} catch (Throwable rex) { |
307 |
> |
setExceptionalCompletion(rex); |
308 |
> |
return; |
309 |
> |
} |
310 |
> |
if (completed) |
311 |
> |
setCompletion(NORMAL); // must be outside try block |
312 |
> |
} |
313 |
|
} |
314 |
|
|
315 |
|
/** |
316 |
< |
* Notifies pool to adjust counts on cancelled or timed out wait. |
316 |
> |
* Primary mechanics for join, get, quietlyJoin. |
317 |
> |
* @return status upon completion |
318 |
|
*/ |
319 |
< |
private void adjustPoolCountsOnCancelledWait(ForkJoinPool pool) { |
320 |
< |
if (pool != null) { |
321 |
< |
int s; |
322 |
< |
while ((s = status) >= 0 && (s & INTERNAL_SIGNAL_MASK) != 0) { |
323 |
< |
if (casStatus(s, s - 1)) { |
324 |
< |
pool.updateRunningCount(1); |
325 |
< |
break; |
319 |
> |
private int doJoin() { |
320 |
> |
Thread t; ForkJoinWorkerThread w; int s; boolean completed; |
321 |
> |
if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) { |
322 |
> |
if ((s = status) < 0) |
323 |
> |
return s; |
324 |
> |
if ((w = (ForkJoinWorkerThread)t).unpushTask(this)) { |
325 |
> |
try { |
326 |
> |
completed = exec(); |
327 |
> |
} catch (Throwable rex) { |
328 |
> |
return setExceptionalCompletion(rex); |
329 |
|
} |
330 |
+ |
if (completed) |
331 |
+ |
return setCompletion(NORMAL); |
332 |
|
} |
333 |
+ |
return w.joinTask(this); |
334 |
|
} |
335 |
+ |
else |
336 |
+ |
return externalAwaitDone(); |
337 |
|
} |
338 |
|
|
339 |
|
/** |
340 |
< |
* Handles interruptions during waits. |
340 |
> |
* Primary mechanics for invoke, quietlyInvoke. |
341 |
> |
* @return status upon completion |
342 |
|
*/ |
343 |
< |
private void onInterruptedWait() { |
344 |
< |
ForkJoinWorkerThread w = getWorker(); |
345 |
< |
if (w == null) |
346 |
< |
Thread.currentThread().interrupt(); // re-interrupt |
347 |
< |
else if (w.isTerminating()) |
348 |
< |
cancelIgnoringExceptions(); |
349 |
< |
// else if FJworker, ignore interrupt |
343 |
> |
private int doInvoke() { |
344 |
> |
int s; boolean completed; |
345 |
> |
if ((s = status) < 0) |
346 |
> |
return s; |
347 |
> |
try { |
348 |
> |
completed = exec(); |
349 |
> |
} catch (Throwable rex) { |
350 |
> |
return setExceptionalCompletion(rex); |
351 |
> |
} |
352 |
> |
if (completed) |
353 |
> |
return setCompletion(NORMAL); |
354 |
> |
else |
355 |
> |
return doJoin(); |
356 |
|
} |
357 |
|
|
358 |
< |
// Recording and reporting exceptions |
350 |
< |
|
351 |
< |
private void setDoneExceptionally(Throwable rex) { |
352 |
< |
exceptionMap.put(this, rex); |
353 |
< |
setCompletion(EXCEPTIONAL); |
354 |
< |
} |
358 |
> |
// Exception table support |
359 |
|
|
360 |
|
/** |
361 |
< |
* Throws the exception associated with status s. |
361 |
> |
* Table of exceptions thrown by tasks, to enable reporting by |
362 |
> |
* callers. Because exceptions are rare, we don't directly keep |
363 |
> |
* them with task objects, but instead use a weak ref table. Note |
364 |
> |
* that cancellation exceptions don't appear in the table, but are |
365 |
> |
* instead recorded as status values. |
366 |
|
* |
367 |
< |
* @throws the exception |
367 |
> |
* Note: These statics are initialized below in static block. |
368 |
|
*/ |
369 |
< |
private void reportException(int s) { |
370 |
< |
if ((s &= COMPLETION_MASK) < NORMAL) { |
371 |
< |
if (s == CANCELLED) |
364 |
< |
throw new CancellationException(); |
365 |
< |
else |
366 |
< |
rethrowException(exceptionMap.get(this)); |
367 |
< |
} |
368 |
< |
} |
369 |
> |
private static final ExceptionNode[] exceptionTable; |
370 |
> |
private static final ReentrantLock exceptionTableLock; |
371 |
> |
private static final ReferenceQueue<Object> exceptionTableRefQueue; |
372 |
|
|
373 |
|
/** |
374 |
< |
* Returns result or throws exception using j.u.c.Future conventions. |
372 |
< |
* Only call when {@code isDone} known to be true. |
374 |
> |
* Fixed capacity for exceptionTable. |
375 |
|
*/ |
376 |
< |
private V reportFutureResult() |
375 |
< |
throws ExecutionException, InterruptedException { |
376 |
< |
int s = status & COMPLETION_MASK; |
377 |
< |
if (s < NORMAL) { |
378 |
< |
Throwable ex; |
379 |
< |
if (s == CANCELLED) |
380 |
< |
throw new CancellationException(); |
381 |
< |
if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null) |
382 |
< |
throw new ExecutionException(ex); |
383 |
< |
if (Thread.interrupted()) |
384 |
< |
throw new InterruptedException(); |
385 |
< |
} |
386 |
< |
return getRawResult(); |
387 |
< |
} |
376 |
> |
private static final int EXCEPTION_MAP_CAPACITY = 32; |
377 |
|
|
378 |
|
/** |
379 |
< |
* Returns result or throws exception using j.u.c.Future conventions |
380 |
< |
* with timeouts. |
379 |
> |
* Key-value nodes for exception table. The chained hash table |
380 |
> |
* uses identity comparisons, full locking, and weak references |
381 |
> |
* for keys. The table has a fixed capacity because it only |
382 |
> |
* maintains task exceptions long enough for joiners to access |
383 |
> |
* them, so should never become very large for sustained |
384 |
> |
* periods. However, since we do not know when the last joiner |
385 |
> |
* completes, we must use weak references and expunge them. We do |
386 |
> |
* so on each operation (hence full locking). Also, some thread in |
387 |
> |
* any ForkJoinPool will call helpExpungeStaleExceptions when its |
388 |
> |
* pool becomes isQuiescent. |
389 |
|
*/ |
390 |
< |
private V reportTimedFutureResult() |
391 |
< |
throws InterruptedException, ExecutionException, TimeoutException { |
392 |
< |
Throwable ex; |
393 |
< |
int s = status & COMPLETION_MASK; |
394 |
< |
if (s == NORMAL) |
395 |
< |
return getRawResult(); |
396 |
< |
if (s == CANCELLED) |
397 |
< |
throw new CancellationException(); |
398 |
< |
if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null) |
399 |
< |
throw new ExecutionException(ex); |
403 |
< |
if (Thread.interrupted()) |
404 |
< |
throw new InterruptedException(); |
405 |
< |
throw new TimeoutException(); |
390 |
> |
static final class ExceptionNode extends WeakReference<ForkJoinTask<?>>{ |
391 |
> |
final Throwable ex; |
392 |
> |
ExceptionNode next; |
393 |
> |
final long thrower; // use id not ref to avoid weak cycles |
394 |
> |
ExceptionNode(ForkJoinTask<?> task, Throwable ex, ExceptionNode next) { |
395 |
> |
super(task, exceptionTableRefQueue); |
396 |
> |
this.ex = ex; |
397 |
> |
this.next = next; |
398 |
> |
this.thrower = Thread.currentThread().getId(); |
399 |
> |
} |
400 |
|
} |
401 |
|
|
408 |
– |
// internal execution methods |
409 |
– |
|
402 |
|
/** |
403 |
< |
* Calls exec, recording completion, and rethrowing exception if |
412 |
< |
* encountered. Caller should normally check status before calling. |
403 |
> |
* Records exception and sets exceptional completion. |
404 |
|
* |
405 |
< |
* @return true if completed normally |
405 |
> |
* @return status on exit |
406 |
|
*/ |
407 |
< |
private boolean tryExec() { |
408 |
< |
try { // try block must contain only call to exec |
409 |
< |
if (!exec()) |
410 |
< |
return false; |
411 |
< |
} catch (Throwable rex) { |
412 |
< |
setDoneExceptionally(rex); |
413 |
< |
rethrowException(rex); |
414 |
< |
return false; // not reached |
407 |
> |
private int setExceptionalCompletion(Throwable ex) { |
408 |
> |
int h = System.identityHashCode(this); |
409 |
> |
final ReentrantLock lock = exceptionTableLock; |
410 |
> |
lock.lock(); |
411 |
> |
try { |
412 |
> |
expungeStaleExceptions(); |
413 |
> |
ExceptionNode[] t = exceptionTable; |
414 |
> |
int i = h & (t.length - 1); |
415 |
> |
for (ExceptionNode e = t[i]; ; e = e.next) { |
416 |
> |
if (e == null) { |
417 |
> |
t[i] = new ExceptionNode(this, ex, t[i]); |
418 |
> |
break; |
419 |
> |
} |
420 |
> |
if (e.get() == this) // already present |
421 |
> |
break; |
422 |
> |
} |
423 |
> |
} finally { |
424 |
> |
lock.unlock(); |
425 |
|
} |
426 |
< |
setNormalCompletion(); |
426 |
< |
return true; |
426 |
> |
return setCompletion(EXCEPTIONAL); |
427 |
|
} |
428 |
|
|
429 |
|
/** |
430 |
< |
* Main execution method used by worker threads. Invokes |
431 |
< |
* base computation unless already complete. |
430 |
> |
* Removes exception node and clears status |
431 |
|
*/ |
432 |
< |
final void quietlyExec() { |
433 |
< |
if (status >= 0) { |
434 |
< |
try { |
435 |
< |
if (!exec()) |
436 |
< |
return; |
437 |
< |
} catch (Throwable rex) { |
438 |
< |
setDoneExceptionally(rex); |
439 |
< |
return; |
432 |
> |
private void clearExceptionalCompletion() { |
433 |
> |
int h = System.identityHashCode(this); |
434 |
> |
final ReentrantLock lock = exceptionTableLock; |
435 |
> |
lock.lock(); |
436 |
> |
try { |
437 |
> |
ExceptionNode[] t = exceptionTable; |
438 |
> |
int i = h & (t.length - 1); |
439 |
> |
ExceptionNode e = t[i]; |
440 |
> |
ExceptionNode pred = null; |
441 |
> |
while (e != null) { |
442 |
> |
ExceptionNode next = e.next; |
443 |
> |
if (e.get() == this) { |
444 |
> |
if (pred == null) |
445 |
> |
t[i] = next; |
446 |
> |
else |
447 |
> |
pred.next = next; |
448 |
> |
break; |
449 |
> |
} |
450 |
> |
pred = e; |
451 |
> |
e = next; |
452 |
|
} |
453 |
< |
setNormalCompletion(); |
453 |
> |
expungeStaleExceptions(); |
454 |
> |
status = 0; |
455 |
> |
} finally { |
456 |
> |
lock.unlock(); |
457 |
|
} |
458 |
|
} |
459 |
|
|
460 |
|
/** |
461 |
< |
* Calls exec(), recording but not rethrowing exception. |
462 |
< |
* Caller should normally check status before calling. |
461 |
> |
* Returns a rethrowable exception for the given task, if |
462 |
> |
* available. To provide accurate stack traces, if the exception |
463 |
> |
* was not thrown by the current thread, we try to create a new |
464 |
> |
* exception of the same type as the one thrown, but with the |
465 |
> |
* recorded exception as its cause. If there is no such |
466 |
> |
* constructor, we instead try to use a no-arg constructor, |
467 |
> |
* followed by initCause, to the same effect. If none of these |
468 |
> |
* apply, or any fail due to other exceptions, we return the |
469 |
> |
* recorded exception, which is still correct, although it may |
470 |
> |
* contain a misleading stack trace. |
471 |
|
* |
472 |
< |
* @return true if completed normally |
472 |
> |
* @return the exception, or null if none |
473 |
|
*/ |
474 |
< |
private boolean tryQuietlyInvoke() { |
474 |
> |
private Throwable getThrowableException() { |
475 |
> |
if (status != EXCEPTIONAL) |
476 |
> |
return null; |
477 |
> |
int h = System.identityHashCode(this); |
478 |
> |
ExceptionNode e; |
479 |
> |
final ReentrantLock lock = exceptionTableLock; |
480 |
> |
lock.lock(); |
481 |
|
try { |
482 |
< |
if (!exec()) |
483 |
< |
return false; |
484 |
< |
} catch (Throwable rex) { |
485 |
< |
setDoneExceptionally(rex); |
486 |
< |
return false; |
482 |
> |
expungeStaleExceptions(); |
483 |
> |
ExceptionNode[] t = exceptionTable; |
484 |
> |
e = t[h & (t.length - 1)]; |
485 |
> |
while (e != null && e.get() != this) |
486 |
> |
e = e.next; |
487 |
> |
} finally { |
488 |
> |
lock.unlock(); |
489 |
> |
} |
490 |
> |
Throwable ex; |
491 |
> |
if (e == null || (ex = e.ex) == null) |
492 |
> |
return null; |
493 |
> |
if (e.thrower != Thread.currentThread().getId()) { |
494 |
> |
Class ec = ex.getClass(); |
495 |
> |
try { |
496 |
> |
Constructor<?> noArgCtor = null; |
497 |
> |
Constructor<?>[] cs = ec.getConstructors();// public ctors only |
498 |
> |
for (int i = 0; i < cs.length; ++i) { |
499 |
> |
Constructor<?> c = cs[i]; |
500 |
> |
Class<?>[] ps = c.getParameterTypes(); |
501 |
> |
if (ps.length == 0) |
502 |
> |
noArgCtor = c; |
503 |
> |
else if (ps.length == 1 && ps[0] == Throwable.class) |
504 |
> |
return (Throwable)(c.newInstance(ex)); |
505 |
> |
} |
506 |
> |
if (noArgCtor != null) { |
507 |
> |
Throwable wx = (Throwable)(noArgCtor.newInstance()); |
508 |
> |
wx.initCause(ex); |
509 |
> |
return wx; |
510 |
> |
} |
511 |
> |
} catch (Exception ignore) { |
512 |
> |
} |
513 |
|
} |
514 |
< |
setNormalCompletion(); |
461 |
< |
return true; |
514 |
> |
return ex; |
515 |
|
} |
516 |
|
|
517 |
|
/** |
518 |
< |
* Cancels, ignoring any exceptions it throws. |
518 |
> |
* Poll stale refs and remove them. Call only while holding lock. |
519 |
|
*/ |
520 |
< |
final void cancelIgnoringExceptions() { |
521 |
< |
try { |
522 |
< |
cancel(false); |
523 |
< |
} catch (Throwable ignore) { |
520 |
> |
private static void expungeStaleExceptions() { |
521 |
> |
for (Object x; (x = exceptionTableRefQueue.poll()) != null;) { |
522 |
> |
if (x instanceof ExceptionNode) { |
523 |
> |
ForkJoinTask<?> key = ((ExceptionNode)x).get(); |
524 |
> |
ExceptionNode[] t = exceptionTable; |
525 |
> |
int i = System.identityHashCode(key) & (t.length - 1); |
526 |
> |
ExceptionNode e = t[i]; |
527 |
> |
ExceptionNode pred = null; |
528 |
> |
while (e != null) { |
529 |
> |
ExceptionNode next = e.next; |
530 |
> |
if (e == x) { |
531 |
> |
if (pred == null) |
532 |
> |
t[i] = next; |
533 |
> |
else |
534 |
> |
pred.next = next; |
535 |
> |
break; |
536 |
> |
} |
537 |
> |
pred = e; |
538 |
> |
e = next; |
539 |
> |
} |
540 |
> |
} |
541 |
|
} |
542 |
|
} |
543 |
|
|
544 |
|
/** |
545 |
< |
* Main implementation of helpJoin |
545 |
> |
* If lock is available, poll stale refs and remove them. |
546 |
> |
* Called from ForkJoinPool when pools become quiescent. |
547 |
|
*/ |
548 |
< |
private int busyJoin(ForkJoinWorkerThread w) { |
549 |
< |
int s; |
550 |
< |
ForkJoinTask<?> t; |
551 |
< |
while ((s = status) >= 0 && (t = w.scanWhileJoining(this)) != null) |
552 |
< |
t.quietlyExec(); |
553 |
< |
return (s >= 0) ? awaitDone(w, false) : s; // block if no work |
548 |
> |
static final void helpExpungeStaleExceptions() { |
549 |
> |
final ReentrantLock lock = exceptionTableLock; |
550 |
> |
if (lock.tryLock()) { |
551 |
> |
try { |
552 |
> |
expungeStaleExceptions(); |
553 |
> |
} finally { |
554 |
> |
lock.unlock(); |
555 |
> |
} |
556 |
> |
} |
557 |
> |
} |
558 |
> |
|
559 |
> |
/** |
560 |
> |
* Report the result of invoke or join; called only upon |
561 |
> |
* non-normal return of internal versions. |
562 |
> |
*/ |
563 |
> |
private V reportResult() { |
564 |
> |
int s; Throwable ex; |
565 |
> |
if ((s = status) == CANCELLED) |
566 |
> |
throw new CancellationException(); |
567 |
> |
if (s == EXCEPTIONAL && (ex = getThrowableException()) != null) |
568 |
> |
UNSAFE.throwException(ex); |
569 |
> |
return getRawResult(); |
570 |
|
} |
571 |
|
|
572 |
|
// public methods |
574 |
|
/** |
575 |
|
* Arranges to asynchronously execute this task. While it is not |
576 |
|
* necessarily enforced, it is a usage error to fork a task more |
577 |
< |
* than once unless it has completed and been reinitialized. This |
578 |
< |
* method may be invoked only from within ForkJoinTask |
579 |
< |
* computations (as may be determined using method {@link |
580 |
< |
* #inForkJoinPool}). Attempts to invoke in other contexts result |
581 |
< |
* in exceptions or errors, possibly including ClassCastException. |
577 |
> |
* than once unless it has completed and been reinitialized. |
578 |
> |
* Subsequent modifications to the state of this task or any data |
579 |
> |
* it operates on are not necessarily consistently observable by |
580 |
> |
* any thread other than the one executing it unless preceded by a |
581 |
> |
* call to {@link #join} or related methods, or a call to {@link |
582 |
> |
* #isDone} returning {@code true}. |
583 |
> |
* |
584 |
> |
* <p>This method may be invoked only from within {@code |
585 |
> |
* ForkJoinPool} computations (as may be determined using method |
586 |
> |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
587 |
> |
* result in exceptions or errors, possibly including {@code |
588 |
> |
* ClassCastException}. |
589 |
|
* |
590 |
< |
* @return <code>this</code>, to simplify usage. |
590 |
> |
* @return {@code this}, to simplify usage |
591 |
|
*/ |
592 |
|
public final ForkJoinTask<V> fork() { |
593 |
|
((ForkJoinWorkerThread) Thread.currentThread()) |
596 |
|
} |
597 |
|
|
598 |
|
/** |
599 |
< |
* Returns the result of the computation when it is ready. |
600 |
< |
* This method differs from {@code get} in that abnormal |
601 |
< |
* completion results in RuntimeExceptions or Errors, not |
602 |
< |
* ExecutionExceptions. |
599 |
> |
* Returns the result of the computation when it {@link #isDone is |
600 |
> |
* done}. This method differs from {@link #get()} in that |
601 |
> |
* abnormal completion results in {@code RuntimeException} or |
602 |
> |
* {@code Error}, not {@code ExecutionException}, and that |
603 |
> |
* interrupts of the calling thread do <em>not</em> cause the |
604 |
> |
* method to abruptly return by throwing {@code |
605 |
> |
* InterruptedException}. |
606 |
|
* |
607 |
|
* @return the computed result |
608 |
|
*/ |
609 |
|
public final V join() { |
610 |
< |
ForkJoinWorkerThread w = getWorker(); |
611 |
< |
if (w == null || status < 0 || !w.unpushTask(this) || !tryExec()) |
612 |
< |
reportException(awaitDone(w, true)); |
613 |
< |
return getRawResult(); |
610 |
> |
if (doJoin() != NORMAL) |
611 |
> |
return reportResult(); |
612 |
> |
else |
613 |
> |
return getRawResult(); |
614 |
|
} |
615 |
|
|
616 |
|
/** |
617 |
|
* Commences performing this task, awaits its completion if |
618 |
< |
* necessary, and return its result. |
618 |
> |
* necessary, and returns its result, or throws an (unchecked) |
619 |
> |
* {@code RuntimeException} or {@code Error} if the underlying |
620 |
> |
* computation did so. |
621 |
|
* |
523 |
– |
* @throws Throwable (a RuntimeException, Error, or unchecked |
524 |
– |
* exception) if the underlying computation did so |
622 |
|
* @return the computed result |
623 |
|
*/ |
624 |
|
public final V invoke() { |
625 |
< |
if (status >= 0 && tryExec()) |
626 |
< |
return getRawResult(); |
625 |
> |
if (doInvoke() != NORMAL) |
626 |
> |
return reportResult(); |
627 |
|
else |
628 |
< |
return join(); |
628 |
> |
return getRawResult(); |
629 |
|
} |
630 |
|
|
631 |
|
/** |
632 |
< |
* Forks both tasks, returning when {@code isDone} holds for |
633 |
< |
* both of them or an exception is encountered. This method may be |
634 |
< |
* invoked only from within ForkJoinTask computations (as may be |
635 |
< |
* determined using method {@link #inForkJoinPool}). Attempts to |
636 |
< |
* invoke in other contexts result in exceptions or errors, |
637 |
< |
* possibly including ClassCastException. |
638 |
< |
* |
639 |
< |
* @param t1 one task |
640 |
< |
* @param t2 the other task |
641 |
< |
* @throws NullPointerException if t1 or t2 are null |
642 |
< |
* @throws RuntimeException or Error if either task did so |
632 |
> |
* Forks the given tasks, returning when {@code isDone} holds for |
633 |
> |
* each task or an (unchecked) exception is encountered, in which |
634 |
> |
* case the exception is rethrown. If more than one task |
635 |
> |
* encounters an exception, then this method throws any one of |
636 |
> |
* these exceptions. If any task encounters an exception, the |
637 |
> |
* other may be cancelled. However, the execution status of |
638 |
> |
* individual tasks is not guaranteed upon exceptional return. The |
639 |
> |
* status of each task may be obtained using {@link |
640 |
> |
* #getException()} and related methods to check if they have been |
641 |
> |
* cancelled, completed normally or exceptionally, or left |
642 |
> |
* unprocessed. |
643 |
> |
* |
644 |
> |
* <p>This method may be invoked only from within {@code |
645 |
> |
* ForkJoinPool} computations (as may be determined using method |
646 |
> |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
647 |
> |
* result in exceptions or errors, possibly including {@code |
648 |
> |
* ClassCastException}. |
649 |
> |
* |
650 |
> |
* @param t1 the first task |
651 |
> |
* @param t2 the second task |
652 |
> |
* @throws NullPointerException if any task is null |
653 |
|
*/ |
654 |
< |
public static void invokeAll(ForkJoinTask<?>t1, ForkJoinTask<?> t2) { |
654 |
> |
public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) { |
655 |
|
t2.fork(); |
656 |
|
t1.invoke(); |
657 |
|
t2.join(); |
658 |
|
} |
659 |
|
|
660 |
|
/** |
661 |
< |
* Forks the given tasks, returning when {@code isDone} holds |
662 |
< |
* for all of them. If any task encounters an exception, others |
663 |
< |
* may be cancelled. This method may be invoked only from within |
664 |
< |
* ForkJoinTask computations (as may be determined using method |
665 |
< |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
666 |
< |
* result in exceptions or errors, possibly including |
667 |
< |
* ClassCastException. |
661 |
> |
* Forks the given tasks, returning when {@code isDone} holds for |
662 |
> |
* each task or an (unchecked) exception is encountered, in which |
663 |
> |
* case the exception is rethrown. If more than one task |
664 |
> |
* encounters an exception, then this method throws any one of |
665 |
> |
* these exceptions. If any task encounters an exception, others |
666 |
> |
* may be cancelled. However, the execution status of individual |
667 |
> |
* tasks is not guaranteed upon exceptional return. The status of |
668 |
> |
* each task may be obtained using {@link #getException()} and |
669 |
> |
* related methods to check if they have been cancelled, completed |
670 |
> |
* normally or exceptionally, or left unprocessed. |
671 |
> |
* |
672 |
> |
* <p>This method may be invoked only from within {@code |
673 |
> |
* ForkJoinPool} computations (as may be determined using method |
674 |
> |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
675 |
> |
* result in exceptions or errors, possibly including {@code |
676 |
> |
* ClassCastException}. |
677 |
|
* |
678 |
< |
* @param tasks the array of tasks |
679 |
< |
* @throws NullPointerException if tasks or any element are null |
564 |
< |
* @throws RuntimeException or Error if any task did so |
678 |
> |
* @param tasks the tasks |
679 |
> |
* @throws NullPointerException if any task is null |
680 |
|
*/ |
681 |
|
public static void invokeAll(ForkJoinTask<?>... tasks) { |
682 |
|
Throwable ex = null; |
689 |
|
} |
690 |
|
else if (i != 0) |
691 |
|
t.fork(); |
692 |
< |
else { |
693 |
< |
t.quietlyInvoke(); |
579 |
< |
if (ex == null) |
580 |
< |
ex = t.getException(); |
581 |
< |
} |
692 |
> |
else if (t.doInvoke() < NORMAL && ex == null) |
693 |
> |
ex = t.getException(); |
694 |
|
} |
695 |
|
for (int i = 1; i <= last; ++i) { |
696 |
|
ForkJoinTask<?> t = tasks[i]; |
697 |
|
if (t != null) { |
698 |
|
if (ex != null) |
699 |
|
t.cancel(false); |
700 |
< |
else { |
701 |
< |
t.quietlyJoin(); |
590 |
< |
if (ex == null) |
591 |
< |
ex = t.getException(); |
592 |
< |
} |
700 |
> |
else if (t.doJoin() < NORMAL && ex == null) |
701 |
> |
ex = t.getException(); |
702 |
|
} |
703 |
|
} |
704 |
|
if (ex != null) |
705 |
< |
rethrowException(ex); |
705 |
> |
UNSAFE.throwException(ex); |
706 |
|
} |
707 |
|
|
708 |
|
/** |
709 |
< |
* Forks all tasks in the collection, returning when |
710 |
< |
* {@code isDone} holds for all of them. If any task |
711 |
< |
* encounters an exception, others may be cancelled. This method |
712 |
< |
* may be invoked only from within ForkJoinTask computations (as |
713 |
< |
* may be determined using method {@link |
714 |
< |
* #inForkJoinPool}). Attempts to invoke in other contexts result |
715 |
< |
* in exceptions or errors, possibly including ClassCastException. |
709 |
> |
* Forks all tasks in the specified collection, returning when |
710 |
> |
* {@code isDone} holds for each task or an (unchecked) exception |
711 |
> |
* is encountered, in which case the exception is rethrown. If |
712 |
> |
* more than one task encounters an exception, then this method |
713 |
> |
* throws any one of these exceptions. If any task encounters an |
714 |
> |
* exception, others may be cancelled. However, the execution |
715 |
> |
* status of individual tasks is not guaranteed upon exceptional |
716 |
> |
* return. The status of each task may be obtained using {@link |
717 |
> |
* #getException()} and related methods to check if they have been |
718 |
> |
* cancelled, completed normally or exceptionally, or left |
719 |
> |
* unprocessed. |
720 |
> |
* |
721 |
> |
* <p>This method may be invoked only from within {@code |
722 |
> |
* ForkJoinPool} computations (as may be determined using method |
723 |
> |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
724 |
> |
* result in exceptions or errors, possibly including {@code |
725 |
> |
* ClassCastException}. |
726 |
|
* |
727 |
|
* @param tasks the collection of tasks |
728 |
|
* @return the tasks argument, to simplify usage |
729 |
|
* @throws NullPointerException if tasks or any element are null |
611 |
– |
* @throws RuntimeException or Error if any task did so |
730 |
|
*/ |
731 |
|
public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) { |
732 |
< |
if (!(tasks instanceof List<?>)) { |
732 |
> |
if (!(tasks instanceof RandomAccess) || !(tasks instanceof List<?>)) { |
733 |
|
invokeAll(tasks.toArray(new ForkJoinTask<?>[tasks.size()])); |
734 |
|
return tasks; |
735 |
|
} |
746 |
|
} |
747 |
|
else if (i != 0) |
748 |
|
t.fork(); |
749 |
< |
else { |
750 |
< |
t.quietlyInvoke(); |
633 |
< |
if (ex == null) |
634 |
< |
ex = t.getException(); |
635 |
< |
} |
749 |
> |
else if (t.doInvoke() < NORMAL && ex == null) |
750 |
> |
ex = t.getException(); |
751 |
|
} |
752 |
|
for (int i = 1; i <= last; ++i) { |
753 |
|
ForkJoinTask<?> t = ts.get(i); |
754 |
|
if (t != null) { |
755 |
|
if (ex != null) |
756 |
|
t.cancel(false); |
757 |
< |
else { |
758 |
< |
t.quietlyJoin(); |
644 |
< |
if (ex == null) |
645 |
< |
ex = t.getException(); |
646 |
< |
} |
757 |
> |
else if (t.doJoin() < NORMAL && ex == null) |
758 |
> |
ex = t.getException(); |
759 |
|
} |
760 |
|
} |
761 |
|
if (ex != null) |
762 |
< |
rethrowException(ex); |
762 |
> |
UNSAFE.throwException(ex); |
763 |
|
return tasks; |
764 |
|
} |
765 |
|
|
766 |
|
/** |
767 |
< |
* Returns true if the computation performed by this task has |
768 |
< |
* completed (or has been cancelled). |
767 |
> |
* Attempts to cancel execution of this task. This attempt will |
768 |
> |
* fail if the task has already completed or could not be |
769 |
> |
* cancelled for some other reason. If successful, and this task |
770 |
> |
* has not started when {@code cancel} is called, execution of |
771 |
> |
* this task is suppressed. After this method returns |
772 |
> |
* successfully, unless there is an intervening call to {@link |
773 |
> |
* #reinitialize}, subsequent calls to {@link #isCancelled}, |
774 |
> |
* {@link #isDone}, and {@code cancel} will return {@code true} |
775 |
> |
* and calls to {@link #join} and related methods will result in |
776 |
> |
* {@code CancellationException}. |
777 |
> |
* |
778 |
> |
* <p>This method may be overridden in subclasses, but if so, must |
779 |
> |
* still ensure that these properties hold. In particular, the |
780 |
> |
* {@code cancel} method itself must not throw exceptions. |
781 |
> |
* |
782 |
> |
* <p>This method is designed to be invoked by <em>other</em> |
783 |
> |
* tasks. To terminate the current task, you can just return or |
784 |
> |
* throw an unchecked exception from its computation method, or |
785 |
> |
* invoke {@link #completeExceptionally}. |
786 |
|
* |
787 |
< |
* @return true if this computation has completed |
787 |
> |
* @param mayInterruptIfRunning this value has no effect in the |
788 |
> |
* default implementation because interrupts are not used to |
789 |
> |
* control cancellation. |
790 |
> |
* |
791 |
> |
* @return {@code true} if this task is now cancelled |
792 |
|
*/ |
793 |
< |
public final boolean isDone() { |
794 |
< |
return status < 0; |
793 |
> |
public boolean cancel(boolean mayInterruptIfRunning) { |
794 |
> |
return setCompletion(CANCELLED) == CANCELLED; |
795 |
|
} |
796 |
|
|
797 |
|
/** |
798 |
< |
* Returns true if this task was cancelled. |
799 |
< |
* |
800 |
< |
* @return true if this task was cancelled |
798 |
> |
* Cancels, ignoring any exceptions thrown by cancel. Used during |
799 |
> |
* worker and pool shutdown. Cancel is spec'ed not to throw any |
800 |
> |
* exceptions, but if it does anyway, we have no recourse during |
801 |
> |
* shutdown, so guard against this case. |
802 |
|
*/ |
803 |
+ |
final void cancelIgnoringExceptions() { |
804 |
+ |
try { |
805 |
+ |
cancel(false); |
806 |
+ |
} catch (Throwable ignore) { |
807 |
+ |
} |
808 |
+ |
} |
809 |
+ |
|
810 |
+ |
public final boolean isDone() { |
811 |
+ |
return status < 0; |
812 |
+ |
} |
813 |
+ |
|
814 |
|
public final boolean isCancelled() { |
815 |
< |
return (status & COMPLETION_MASK) == CANCELLED; |
815 |
> |
return status == CANCELLED; |
816 |
|
} |
817 |
|
|
818 |
|
/** |
819 |
< |
* Asserts that the results of this task's computation will not be |
675 |
< |
* used. If a cancellation occurs before attempting to execute this |
676 |
< |
* task, then execution will be suppressed, {@code isCancelled} |
677 |
< |
* will report true, and {@code join} will result in a |
678 |
< |
* {@code CancellationException} being thrown. Otherwise, when |
679 |
< |
* cancellation races with completion, there are no guarantees |
680 |
< |
* about whether {@code isCancelled} will report true, whether |
681 |
< |
* {@code join} will return normally or via an exception, or |
682 |
< |
* whether these behaviors will remain consistent upon repeated |
683 |
< |
* invocation. |
684 |
< |
* |
685 |
< |
* <p>This method may be overridden in subclasses, but if so, must |
686 |
< |
* still ensure that these minimal properties hold. In particular, |
687 |
< |
* the cancel method itself must not throw exceptions. |
688 |
< |
* |
689 |
< |
* <p> This method is designed to be invoked by <em>other</em> |
690 |
< |
* tasks. To terminate the current task, you can just return or |
691 |
< |
* throw an unchecked exception from its computation method, or |
692 |
< |
* invoke {@code completeExceptionally}. |
693 |
< |
* |
694 |
< |
* @param mayInterruptIfRunning this value is ignored in the |
695 |
< |
* default implementation because tasks are not in general |
696 |
< |
* cancelled via interruption |
819 |
> |
* Returns {@code true} if this task threw an exception or was cancelled. |
820 |
|
* |
821 |
< |
* @return true if this task is now cancelled |
821 |
> |
* @return {@code true} if this task threw an exception or was cancelled |
822 |
|
*/ |
823 |
< |
public boolean cancel(boolean mayInterruptIfRunning) { |
824 |
< |
setCompletion(CANCELLED); |
702 |
< |
return (status & COMPLETION_MASK) == CANCELLED; |
823 |
> |
public final boolean isCompletedAbnormally() { |
824 |
> |
return status < NORMAL; |
825 |
|
} |
826 |
|
|
827 |
|
/** |
828 |
< |
* Returns true if this task threw an exception or was cancelled. |
828 |
> |
* Returns {@code true} if this task completed without throwing an |
829 |
> |
* exception and was not cancelled. |
830 |
|
* |
831 |
< |
* @return true if this task threw an exception or was cancelled |
831 |
> |
* @return {@code true} if this task completed without throwing an |
832 |
> |
* exception and was not cancelled |
833 |
|
*/ |
834 |
< |
public final boolean isCompletedAbnormally() { |
835 |
< |
return (status & COMPLETION_MASK) < NORMAL; |
834 |
> |
public final boolean isCompletedNormally() { |
835 |
> |
return status == NORMAL; |
836 |
|
} |
837 |
|
|
838 |
|
/** |
839 |
|
* Returns the exception thrown by the base computation, or a |
840 |
< |
* CancellationException if cancelled, or null if none or if the |
841 |
< |
* method has not yet completed. |
840 |
> |
* {@code CancellationException} if cancelled, or {@code null} if |
841 |
> |
* none or if the method has not yet completed. |
842 |
|
* |
843 |
< |
* @return the exception, or null if none |
843 |
> |
* @return the exception, or {@code null} if none |
844 |
|
*/ |
845 |
|
public final Throwable getException() { |
846 |
< |
int s = status & COMPLETION_MASK; |
847 |
< |
if (s >= NORMAL) |
848 |
< |
return null; |
849 |
< |
if (s == CANCELLED) |
726 |
< |
return new CancellationException(); |
727 |
< |
return exceptionMap.get(this); |
846 |
> |
int s = status; |
847 |
> |
return ((s >= NORMAL) ? null : |
848 |
> |
(s == CANCELLED) ? new CancellationException() : |
849 |
> |
getThrowableException()); |
850 |
|
} |
851 |
|
|
852 |
|
/** |
855 |
|
* {@code join} and related operations. This method may be used |
856 |
|
* to induce exceptions in asynchronous tasks, or to force |
857 |
|
* completion of tasks that would not otherwise complete. Its use |
858 |
< |
* in other situations is likely to be wrong. This method is |
858 |
> |
* in other situations is discouraged. This method is |
859 |
|
* overridable, but overridden versions must invoke {@code super} |
860 |
|
* implementation to maintain guarantees. |
861 |
|
* |
862 |
< |
* @param ex the exception to throw. If this exception is |
863 |
< |
* not a RuntimeException or Error, the actual exception thrown |
864 |
< |
* will be a RuntimeException with cause ex. |
862 |
> |
* @param ex the exception to throw. If this exception is not a |
863 |
> |
* {@code RuntimeException} or {@code Error}, the actual exception |
864 |
> |
* thrown will be a {@code RuntimeException} with cause {@code ex}. |
865 |
|
*/ |
866 |
|
public void completeExceptionally(Throwable ex) { |
867 |
< |
setDoneExceptionally((ex instanceof RuntimeException) || |
868 |
< |
(ex instanceof Error) ? ex : |
869 |
< |
new RuntimeException(ex)); |
867 |
> |
setExceptionalCompletion((ex instanceof RuntimeException) || |
868 |
> |
(ex instanceof Error) ? ex : |
869 |
> |
new RuntimeException(ex)); |
870 |
|
} |
871 |
|
|
872 |
|
/** |
873 |
|
* Completes this task, and if not already aborted or cancelled, |
874 |
< |
* returning a {@code null} result upon {@code join} and related |
875 |
< |
* operations. This method may be used to provide results for |
876 |
< |
* asynchronous tasks, or to provide alternative handling for |
877 |
< |
* tasks that would not otherwise complete normally. Its use in |
878 |
< |
* other situations is likely to be wrong. This method is |
879 |
< |
* overridable, but overridden versions must invoke {@code super} |
880 |
< |
* implementation to maintain guarantees. |
874 |
> |
* returning the given value as the result of subsequent |
875 |
> |
* invocations of {@code join} and related operations. This method |
876 |
> |
* may be used to provide results for asynchronous tasks, or to |
877 |
> |
* provide alternative handling for tasks that would not otherwise |
878 |
> |
* complete normally. Its use in other situations is |
879 |
> |
* discouraged. This method is overridable, but overridden |
880 |
> |
* versions must invoke {@code super} implementation to maintain |
881 |
> |
* guarantees. |
882 |
|
* |
883 |
|
* @param value the result value for this task |
884 |
|
*/ |
886 |
|
try { |
887 |
|
setRawResult(value); |
888 |
|
} catch (Throwable rex) { |
889 |
< |
setDoneExceptionally(rex); |
889 |
> |
setExceptionalCompletion(rex); |
890 |
|
return; |
891 |
|
} |
892 |
< |
setNormalCompletion(); |
770 |
< |
} |
771 |
< |
|
772 |
< |
public final V get() throws InterruptedException, ExecutionException { |
773 |
< |
ForkJoinWorkerThread w = getWorker(); |
774 |
< |
if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke()) |
775 |
< |
awaitDone(w, true); |
776 |
< |
return reportFutureResult(); |
777 |
< |
} |
778 |
< |
|
779 |
< |
public final V get(long timeout, TimeUnit unit) |
780 |
< |
throws InterruptedException, ExecutionException, TimeoutException { |
781 |
< |
ForkJoinWorkerThread w = getWorker(); |
782 |
< |
if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke()) |
783 |
< |
awaitDone(w, unit.toNanos(timeout)); |
784 |
< |
return reportTimedFutureResult(); |
892 |
> |
setCompletion(NORMAL); |
893 |
|
} |
894 |
|
|
895 |
|
/** |
896 |
< |
* Possibly executes other tasks until this task is ready, then |
897 |
< |
* returns the result of the computation. This method may be more |
790 |
< |
* efficient than {@code join}, but is only applicable when |
791 |
< |
* there are no potential dependencies between continuation of the |
792 |
< |
* current task and that of any other task that might be executed |
793 |
< |
* while helping. (This usually holds for pure divide-and-conquer |
794 |
< |
* tasks). This method may be invoked only from within |
795 |
< |
* ForkJoinTask computations (as may be determined using method |
796 |
< |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
797 |
< |
* result in exceptions or errors, possibly including |
798 |
< |
* ClassCastException. |
896 |
> |
* Waits if necessary for the computation to complete, and then |
897 |
> |
* retrieves its result. |
898 |
|
* |
899 |
|
* @return the computed result |
900 |
+ |
* @throws CancellationException if the computation was cancelled |
901 |
+ |
* @throws ExecutionException if the computation threw an |
902 |
+ |
* exception |
903 |
+ |
* @throws InterruptedException if the current thread is not a |
904 |
+ |
* member of a ForkJoinPool and was interrupted while waiting |
905 |
|
*/ |
906 |
< |
public final V helpJoin() { |
907 |
< |
ForkJoinWorkerThread w = (ForkJoinWorkerThread) Thread.currentThread(); |
908 |
< |
if (status < 0 || !w.unpushTask(this) || !tryExec()) |
909 |
< |
reportException(busyJoin(w)); |
906 |
> |
public final V get() throws InterruptedException, ExecutionException { |
907 |
> |
int s = (Thread.currentThread() instanceof ForkJoinWorkerThread) ? |
908 |
> |
doJoin() : externalInterruptibleAwaitDone(0L); |
909 |
> |
Throwable ex; |
910 |
> |
if (s == CANCELLED) |
911 |
> |
throw new CancellationException(); |
912 |
> |
if (s == EXCEPTIONAL && (ex = getThrowableException()) != null) |
913 |
> |
throw new ExecutionException(ex); |
914 |
|
return getRawResult(); |
915 |
|
} |
916 |
|
|
917 |
|
/** |
918 |
< |
* Possibly executes other tasks until this task is ready. This |
919 |
< |
* method may be invoked only from within ForkJoinTask |
920 |
< |
* computations (as may be determined using method {@link |
921 |
< |
* #inForkJoinPool}). Attempts to invoke in other contexts result |
922 |
< |
* in exceptions or errors, possibly including ClassCastException. |
918 |
> |
* Waits if necessary for at most the given time for the computation |
919 |
> |
* to complete, and then retrieves its result, if available. |
920 |
> |
* |
921 |
> |
* @param timeout the maximum time to wait |
922 |
> |
* @param unit the time unit of the timeout argument |
923 |
> |
* @return the computed result |
924 |
> |
* @throws CancellationException if the computation was cancelled |
925 |
> |
* @throws ExecutionException if the computation threw an |
926 |
> |
* exception |
927 |
> |
* @throws InterruptedException if the current thread is not a |
928 |
> |
* member of a ForkJoinPool and was interrupted while waiting |
929 |
> |
* @throws TimeoutException if the wait timed out |
930 |
|
*/ |
931 |
< |
public final void quietlyHelpJoin() { |
932 |
< |
if (status >= 0) { |
933 |
< |
ForkJoinWorkerThread w = |
934 |
< |
(ForkJoinWorkerThread) Thread.currentThread(); |
935 |
< |
if (!w.unpushTask(this) || !tryQuietlyInvoke()) |
936 |
< |
busyJoin(w); |
931 |
> |
public final V get(long timeout, TimeUnit unit) |
932 |
> |
throws InterruptedException, ExecutionException, TimeoutException { |
933 |
> |
Thread t = Thread.currentThread(); |
934 |
> |
if (t instanceof ForkJoinWorkerThread) { |
935 |
> |
ForkJoinWorkerThread w = (ForkJoinWorkerThread) t; |
936 |
> |
long nanos = unit.toNanos(timeout); |
937 |
> |
if (status >= 0) { |
938 |
> |
boolean completed = false; |
939 |
> |
if (w.unpushTask(this)) { |
940 |
> |
try { |
941 |
> |
completed = exec(); |
942 |
> |
} catch (Throwable rex) { |
943 |
> |
setExceptionalCompletion(rex); |
944 |
> |
} |
945 |
> |
} |
946 |
> |
if (completed) |
947 |
> |
setCompletion(NORMAL); |
948 |
> |
else if (status >= 0 && nanos > 0) |
949 |
> |
w.pool.timedAwaitJoin(this, nanos); |
950 |
> |
} |
951 |
> |
} |
952 |
> |
else { |
953 |
> |
long millis = unit.toMillis(timeout); |
954 |
> |
if (millis > 0) |
955 |
> |
externalInterruptibleAwaitDone(millis); |
956 |
> |
} |
957 |
> |
int s = status; |
958 |
> |
if (s != NORMAL) { |
959 |
> |
Throwable ex; |
960 |
> |
if (s == CANCELLED) |
961 |
> |
throw new CancellationException(); |
962 |
> |
if (s != EXCEPTIONAL) |
963 |
> |
throw new TimeoutException(); |
964 |
> |
if ((ex = getThrowableException()) != null) |
965 |
> |
throw new ExecutionException(ex); |
966 |
|
} |
967 |
+ |
return getRawResult(); |
968 |
|
} |
969 |
|
|
970 |
|
/** |
971 |
< |
* Joins this task, without returning its result or throwing an |
971 |
> |
* Joins this task, without returning its result or throwing its |
972 |
|
* exception. This method may be useful when processing |
973 |
|
* collections of tasks when some have been cancelled or otherwise |
974 |
|
* known to have aborted. |
975 |
|
*/ |
976 |
|
public final void quietlyJoin() { |
977 |
< |
if (status >= 0) { |
833 |
< |
ForkJoinWorkerThread w = getWorker(); |
834 |
< |
if (w == null || !w.unpushTask(this) || !tryQuietlyInvoke()) |
835 |
< |
awaitDone(w, true); |
836 |
< |
} |
977 |
> |
doJoin(); |
978 |
|
} |
979 |
|
|
980 |
|
/** |
981 |
|
* Commences performing this task and awaits its completion if |
982 |
< |
* necessary, without returning its result or throwing an |
983 |
< |
* exception. This method may be useful when processing |
843 |
< |
* collections of tasks when some have been cancelled or otherwise |
844 |
< |
* known to have aborted. |
982 |
> |
* necessary, without returning its result or throwing its |
983 |
> |
* exception. |
984 |
|
*/ |
985 |
|
public final void quietlyInvoke() { |
986 |
< |
if (status >= 0 && !tryQuietlyInvoke()) |
848 |
< |
quietlyJoin(); |
986 |
> |
doInvoke(); |
987 |
|
} |
988 |
|
|
989 |
|
/** |
990 |
|
* Possibly executes tasks until the pool hosting the current task |
991 |
< |
* {@link ForkJoinPool#isQuiescent}. This method may be of use in |
992 |
< |
* designs in which many tasks are forked, but none are explicitly |
993 |
< |
* joined, instead executing them until all are processed. |
991 |
> |
* {@link ForkJoinPool#isQuiescent is quiescent}. This method may |
992 |
> |
* be of use in designs in which many tasks are forked, but none |
993 |
> |
* are explicitly joined, instead executing them until all are |
994 |
> |
* processed. |
995 |
> |
* |
996 |
> |
* <p>This method may be invoked only from within {@code |
997 |
> |
* ForkJoinPool} computations (as may be determined using method |
998 |
> |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
999 |
> |
* result in exceptions or errors, possibly including {@code |
1000 |
> |
* ClassCastException}. |
1001 |
|
*/ |
1002 |
|
public static void helpQuiesce() { |
1003 |
|
((ForkJoinWorkerThread) Thread.currentThread()) |
1010 |
|
* this task, but only if reuse occurs when this task has either |
1011 |
|
* never been forked, or has been forked, then completed and all |
1012 |
|
* outstanding joins of this task have also completed. Effects |
1013 |
< |
* under any other usage conditions are not guaranteed, and are |
1014 |
< |
* almost surely wrong. This method may be useful when executing |
1013 |
> |
* under any other usage conditions are not guaranteed. |
1014 |
> |
* This method may be useful when executing |
1015 |
|
* pre-constructed trees of subtasks in loops. |
1016 |
+ |
* |
1017 |
+ |
* <p>Upon completion of this method, {@code isDone()} reports |
1018 |
+ |
* {@code false}, and {@code getException()} reports {@code |
1019 |
+ |
* null}. However, the value returned by {@code getRawResult} is |
1020 |
+ |
* unaffected. To clear this value, you can invoke {@code |
1021 |
+ |
* setRawResult(null)}. |
1022 |
|
*/ |
1023 |
|
public void reinitialize() { |
1024 |
< |
if ((status & COMPLETION_MASK) == EXCEPTIONAL) |
1025 |
< |
exceptionMap.remove(this); |
1026 |
< |
status = 0; |
1024 |
> |
if (status == EXCEPTIONAL) |
1025 |
> |
clearExceptionalCompletion(); |
1026 |
> |
else |
1027 |
> |
status = 0; |
1028 |
|
} |
1029 |
|
|
1030 |
|
/** |
1031 |
|
* Returns the pool hosting the current task execution, or null |
1032 |
|
* if this task is executing outside of any ForkJoinPool. |
1033 |
|
* |
1034 |
< |
* @return the pool, or null if none |
1034 |
> |
* @see #inForkJoinPool |
1035 |
> |
* @return the pool, or {@code null} if none |
1036 |
|
*/ |
1037 |
|
public static ForkJoinPool getPool() { |
1038 |
|
Thread t = Thread.currentThread(); |
1041 |
|
} |
1042 |
|
|
1043 |
|
/** |
1044 |
< |
* Returns {@code true} if the current thread is executing as a |
1045 |
< |
* ForkJoinPool computation. |
1044 |
> |
* Returns {@code true} if the current thread is a {@link |
1045 |
> |
* ForkJoinWorkerThread} executing as a ForkJoinPool computation. |
1046 |
|
* |
1047 |
< |
* @return {@code true} if the current thread is executing as a |
1048 |
< |
* ForkJoinPool computation, or false otherwise |
1047 |
> |
* @return {@code true} if the current thread is a {@link |
1048 |
> |
* ForkJoinWorkerThread} executing as a ForkJoinPool computation, |
1049 |
> |
* or {@code false} otherwise |
1050 |
|
*/ |
1051 |
|
public static boolean inForkJoinPool() { |
1052 |
|
return Thread.currentThread() instanceof ForkJoinWorkerThread; |
1058 |
|
* by the current thread, and has not commenced executing in |
1059 |
|
* another thread. This method may be useful when arranging |
1060 |
|
* alternative local processing of tasks that could have been, but |
1061 |
< |
* were not, stolen. This method may be invoked only from within |
908 |
< |
* ForkJoinTask computations (as may be determined using method |
909 |
< |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
910 |
< |
* result in exceptions or errors, possibly including |
911 |
< |
* ClassCastException. |
1061 |
> |
* were not, stolen. |
1062 |
|
* |
1063 |
< |
* @return true if unforked |
1063 |
> |
* <p>This method may be invoked only from within {@code |
1064 |
> |
* ForkJoinPool} computations (as may be determined using method |
1065 |
> |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
1066 |
> |
* result in exceptions or errors, possibly including {@code |
1067 |
> |
* ClassCastException}. |
1068 |
> |
* |
1069 |
> |
* @return {@code true} if unforked |
1070 |
|
*/ |
1071 |
|
public boolean tryUnfork() { |
1072 |
|
return ((ForkJoinWorkerThread) Thread.currentThread()) |
1079 |
|
* value may be useful for heuristic decisions about whether to |
1080 |
|
* fork other tasks. |
1081 |
|
* |
1082 |
+ |
* <p>This method may be invoked only from within {@code |
1083 |
+ |
* ForkJoinPool} computations (as may be determined using method |
1084 |
+ |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
1085 |
+ |
* result in exceptions or errors, possibly including {@code |
1086 |
+ |
* ClassCastException}. |
1087 |
+ |
* |
1088 |
|
* @return the number of tasks |
1089 |
|
*/ |
1090 |
|
public static int getQueuedTaskCount() { |
1102 |
|
* tasks, and to process computations locally if this threshold is |
1103 |
|
* exceeded. |
1104 |
|
* |
1105 |
+ |
* <p>This method may be invoked only from within {@code |
1106 |
+ |
* ForkJoinPool} computations (as may be determined using method |
1107 |
+ |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
1108 |
+ |
* result in exceptions or errors, possibly including {@code |
1109 |
+ |
* ClassCastException}. |
1110 |
+ |
* |
1111 |
|
* @return the surplus number of tasks, which may be negative |
1112 |
|
*/ |
1113 |
|
public static int getSurplusQueuedTaskCount() { |
1118 |
|
// Extension methods |
1119 |
|
|
1120 |
|
/** |
1121 |
< |
* Returns the result that would be returned by {@code join}, |
1122 |
< |
* even if this task completed abnormally, or null if this task is |
1123 |
< |
* not known to have been completed. This method is designed to |
1124 |
< |
* aid debugging, as well as to support extensions. Its use in any |
1125 |
< |
* other context is discouraged. |
1121 |
> |
* Returns the result that would be returned by {@link #join}, even |
1122 |
> |
* if this task completed abnormally, or {@code null} if this task |
1123 |
> |
* is not known to have been completed. This method is designed |
1124 |
> |
* to aid debugging, as well as to support extensions. Its use in |
1125 |
> |
* any other context is discouraged. |
1126 |
|
* |
1127 |
< |
* @return the result, or null if not completed |
1127 |
> |
* @return the result, or {@code null} if not completed |
1128 |
|
*/ |
1129 |
|
public abstract V getRawResult(); |
1130 |
|
|
1143 |
|
* called otherwise. The return value controls whether this task |
1144 |
|
* is considered to be done normally. It may return false in |
1145 |
|
* asynchronous actions that require explicit invocations of |
1146 |
< |
* {@code complete} to become joinable. It may throw exceptions |
1147 |
< |
* to indicate abnormal exit. |
1146 |
> |
* {@link #complete} to become joinable. It may also throw an |
1147 |
> |
* (unchecked) exception to indicate abnormal exit. |
1148 |
|
* |
1149 |
< |
* @return true if completed normally |
982 |
< |
* @throws Error or RuntimeException if encountered during computation |
1149 |
> |
* @return {@code true} if completed normally |
1150 |
|
*/ |
1151 |
|
protected abstract boolean exec(); |
1152 |
|
|
1153 |
|
/** |
1154 |
< |
* Returns, but does not unschedule or execute, the task queued by |
1155 |
< |
* the current thread but not yet executed, if one is |
1154 |
> |
* Returns, but does not unschedule or execute, a task queued by |
1155 |
> |
* the current thread but not yet executed, if one is immediately |
1156 |
|
* available. There is no guarantee that this task will actually |
1157 |
< |
* be polled or executed next. This method is designed primarily |
1158 |
< |
* to support extensions, and is unlikely to be useful otherwise. |
1159 |
< |
* This method may be invoked only from within ForkJoinTask |
1160 |
< |
* computations (as may be determined using method {@link |
1161 |
< |
* #inForkJoinPool}). Attempts to invoke in other contexts result |
995 |
< |
* in exceptions or errors, possibly including ClassCastException. |
1157 |
> |
* be polled or executed next. Conversely, this method may return |
1158 |
> |
* null even if a task exists but cannot be accessed without |
1159 |
> |
* contention with other threads. This method is designed |
1160 |
> |
* primarily to support extensions, and is unlikely to be useful |
1161 |
> |
* otherwise. |
1162 |
|
* |
1163 |
< |
* @return the next task, or null if none are available |
1163 |
> |
* <p>This method may be invoked only from within {@code |
1164 |
> |
* ForkJoinPool} computations (as may be determined using method |
1165 |
> |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
1166 |
> |
* result in exceptions or errors, possibly including {@code |
1167 |
> |
* ClassCastException}. |
1168 |
> |
* |
1169 |
> |
* @return the next task, or {@code null} if none are available |
1170 |
|
*/ |
1171 |
|
protected static ForkJoinTask<?> peekNextLocalTask() { |
1172 |
|
return ((ForkJoinWorkerThread) Thread.currentThread()) |
1177 |
|
* Unschedules and returns, without executing, the next task |
1178 |
|
* queued by the current thread but not yet executed. This method |
1179 |
|
* is designed primarily to support extensions, and is unlikely to |
1180 |
< |
* be useful otherwise. This method may be invoked only from |
1181 |
< |
* within ForkJoinTask computations (as may be determined using |
1182 |
< |
* method {@link #inForkJoinPool}). Attempts to invoke in other |
1183 |
< |
* contexts result in exceptions or errors, possibly including |
1184 |
< |
* ClassCastException. |
1180 |
> |
* be useful otherwise. |
1181 |
> |
* |
1182 |
> |
* <p>This method may be invoked only from within {@code |
1183 |
> |
* ForkJoinPool} computations (as may be determined using method |
1184 |
> |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
1185 |
> |
* result in exceptions or errors, possibly including {@code |
1186 |
> |
* ClassCastException}. |
1187 |
|
* |
1188 |
< |
* @return the next task, or null if none are available |
1188 |
> |
* @return the next task, or {@code null} if none are available |
1189 |
|
*/ |
1190 |
|
protected static ForkJoinTask<?> pollNextLocalTask() { |
1191 |
|
return ((ForkJoinWorkerThread) Thread.currentThread()) |
1200 |
|
* {@code null} result does not necessarily imply quiescence |
1201 |
|
* of the pool this task is operating in. This method is designed |
1202 |
|
* primarily to support extensions, and is unlikely to be useful |
1203 |
< |
* otherwise. This method may be invoked only from within |
1030 |
< |
* ForkJoinTask computations (as may be determined using method |
1031 |
< |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
1032 |
< |
* result in exceptions or errors, possibly including |
1033 |
< |
* ClassCastException. |
1203 |
> |
* otherwise. |
1204 |
|
* |
1205 |
< |
* @return a task, or null if none are available |
1205 |
> |
* <p>This method may be invoked only from within {@code |
1206 |
> |
* ForkJoinPool} computations (as may be determined using method |
1207 |
> |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
1208 |
> |
* result in exceptions or errors, possibly including {@code |
1209 |
> |
* ClassCastException}. |
1210 |
> |
* |
1211 |
> |
* @return a task, or {@code null} if none are available |
1212 |
|
*/ |
1213 |
|
protected static ForkJoinTask<?> pollTask() { |
1214 |
|
return ((ForkJoinWorkerThread) Thread.currentThread()) |
1215 |
|
.pollTask(); |
1216 |
|
} |
1217 |
|
|
1218 |
< |
// adaptors |
1218 |
> |
/** |
1219 |
> |
* Adaptor for Runnables. This implements RunnableFuture |
1220 |
> |
* to be compliant with AbstractExecutorService constraints |
1221 |
> |
* when used in ForkJoinPool. |
1222 |
> |
*/ |
1223 |
> |
static final class AdaptedRunnable<T> extends ForkJoinTask<T> |
1224 |
> |
implements RunnableFuture<T> { |
1225 |
> |
final Runnable runnable; |
1226 |
> |
final T resultOnCompletion; |
1227 |
> |
T result; |
1228 |
> |
AdaptedRunnable(Runnable runnable, T result) { |
1229 |
> |
if (runnable == null) throw new NullPointerException(); |
1230 |
> |
this.runnable = runnable; |
1231 |
> |
this.resultOnCompletion = result; |
1232 |
> |
} |
1233 |
> |
public T getRawResult() { return result; } |
1234 |
> |
public void setRawResult(T v) { result = v; } |
1235 |
> |
public boolean exec() { |
1236 |
> |
runnable.run(); |
1237 |
> |
result = resultOnCompletion; |
1238 |
> |
return true; |
1239 |
> |
} |
1240 |
> |
public void run() { invoke(); } |
1241 |
> |
private static final long serialVersionUID = 5232453952276885070L; |
1242 |
> |
} |
1243 |
> |
|
1244 |
> |
/** |
1245 |
> |
* Adaptor for Callables |
1246 |
> |
*/ |
1247 |
> |
static final class AdaptedCallable<T> extends ForkJoinTask<T> |
1248 |
> |
implements RunnableFuture<T> { |
1249 |
> |
final Callable<? extends T> callable; |
1250 |
> |
T result; |
1251 |
> |
AdaptedCallable(Callable<? extends T> callable) { |
1252 |
> |
if (callable == null) throw new NullPointerException(); |
1253 |
> |
this.callable = callable; |
1254 |
> |
} |
1255 |
> |
public T getRawResult() { return result; } |
1256 |
> |
public void setRawResult(T v) { result = v; } |
1257 |
> |
public boolean exec() { |
1258 |
> |
try { |
1259 |
> |
result = callable.call(); |
1260 |
> |
return true; |
1261 |
> |
} catch (Error err) { |
1262 |
> |
throw err; |
1263 |
> |
} catch (RuntimeException rex) { |
1264 |
> |
throw rex; |
1265 |
> |
} catch (Exception ex) { |
1266 |
> |
throw new RuntimeException(ex); |
1267 |
> |
} |
1268 |
> |
} |
1269 |
> |
public void run() { invoke(); } |
1270 |
> |
private static final long serialVersionUID = 2838392045355241008L; |
1271 |
> |
} |
1272 |
|
|
1273 |
|
/** |
1274 |
< |
* Returns a new ForkJoinTask that performs the <code>run</code> |
1275 |
< |
* method of the given Runnable as its action, and returns a null |
1276 |
< |
* result upon <code>join</code>. |
1274 |
> |
* Returns a new {@code ForkJoinTask} that performs the {@code run} |
1275 |
> |
* method of the given {@code Runnable} as its action, and returns |
1276 |
> |
* a null result upon {@link #join}. |
1277 |
|
* |
1278 |
|
* @param runnable the runnable action |
1279 |
|
* @return the task |
1280 |
|
*/ |
1281 |
< |
public static ForkJoinTask<Void> adapt(Runnable runnable) { |
1282 |
< |
return new ForkJoinPool.AdaptedRunnable<Void>(runnable, null); |
1281 |
> |
public static ForkJoinTask<?> adapt(Runnable runnable) { |
1282 |
> |
return new AdaptedRunnable<Void>(runnable, null); |
1283 |
|
} |
1284 |
|
|
1285 |
|
/** |
1286 |
< |
* Returns a new ForkJoinTask that performs the <code>run</code> |
1287 |
< |
* method of the given Runnable as its action, and returns the |
1288 |
< |
* given result upon <code>join</code>. |
1286 |
> |
* Returns a new {@code ForkJoinTask} that performs the {@code run} |
1287 |
> |
* method of the given {@code Runnable} as its action, and returns |
1288 |
> |
* the given result upon {@link #join}. |
1289 |
|
* |
1290 |
|
* @param runnable the runnable action |
1291 |
|
* @param result the result upon completion |
1292 |
|
* @return the task |
1293 |
|
*/ |
1294 |
|
public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) { |
1295 |
< |
return new ForkJoinPool.AdaptedRunnable<T>(runnable, result); |
1295 |
> |
return new AdaptedRunnable<T>(runnable, result); |
1296 |
|
} |
1297 |
|
|
1298 |
|
/** |
1299 |
< |
* Returns a new ForkJoinTask that performs the <code>call</code> |
1300 |
< |
* method of the given Callable as its action, and returns its |
1301 |
< |
* result upon <code>join</code>, translating any checked |
1302 |
< |
* exceptions encountered into <code>RuntimeException<code>. |
1299 |
> |
* Returns a new {@code ForkJoinTask} that performs the {@code call} |
1300 |
> |
* method of the given {@code Callable} as its action, and returns |
1301 |
> |
* its result upon {@link #join}, translating any checked exceptions |
1302 |
> |
* encountered into {@code RuntimeException}. |
1303 |
|
* |
1304 |
|
* @param callable the callable action |
1305 |
|
* @return the task |
1306 |
|
*/ |
1307 |
< |
public static <T> ForkJoinTask<T> adapt(Callable<T> callable) { |
1308 |
< |
return new ForkJoinPool.AdaptedCallable<T>(callable); |
1307 |
> |
public static <T> ForkJoinTask<T> adapt(Callable<? extends T> callable) { |
1308 |
> |
return new AdaptedCallable<T>(callable); |
1309 |
|
} |
1310 |
|
|
1311 |
|
// Serialization support |
1313 |
|
private static final long serialVersionUID = -7721805057305804111L; |
1314 |
|
|
1315 |
|
/** |
1316 |
< |
* Save the state to a stream. |
1316 |
> |
* Saves the state to a stream (that is, serializes it). |
1317 |
|
* |
1318 |
|
* @serialData the current run status and the exception thrown |
1319 |
< |
* during execution, or null if none |
1319 |
> |
* during execution, or {@code null} if none |
1320 |
|
* @param s the stream |
1321 |
|
*/ |
1322 |
|
private void writeObject(java.io.ObjectOutputStream s) |
1326 |
|
} |
1327 |
|
|
1328 |
|
/** |
1329 |
< |
* Reconstitute the instance from a stream. |
1329 |
> |
* Reconstitutes the instance from a stream (that is, deserializes it). |
1330 |
|
* |
1331 |
|
* @param s the stream |
1332 |
|
*/ |
1333 |
|
private void readObject(java.io.ObjectInputStream s) |
1334 |
|
throws java.io.IOException, ClassNotFoundException { |
1335 |
|
s.defaultReadObject(); |
1107 |
– |
status &= ~INTERNAL_SIGNAL_MASK; // clear internal signal counts |
1108 |
– |
status |= EXTERNAL_SIGNAL; // conservatively set external signal |
1336 |
|
Object ex = s.readObject(); |
1337 |
|
if (ex != null) |
1338 |
< |
setDoneExceptionally((Throwable) ex); |
1338 |
> |
setExceptionalCompletion((Throwable)ex); |
1339 |
> |
} |
1340 |
> |
|
1341 |
> |
// Unsafe mechanics |
1342 |
> |
private static final sun.misc.Unsafe UNSAFE; |
1343 |
> |
private static final long statusOffset; |
1344 |
> |
static { |
1345 |
> |
exceptionTableLock = new ReentrantLock(); |
1346 |
> |
exceptionTableRefQueue = new ReferenceQueue<Object>(); |
1347 |
> |
exceptionTable = new ExceptionNode[EXCEPTION_MAP_CAPACITY]; |
1348 |
> |
try { |
1349 |
> |
UNSAFE = getUnsafe(); |
1350 |
> |
statusOffset = UNSAFE.objectFieldOffset |
1351 |
> |
(ForkJoinTask.class.getDeclaredField("status")); |
1352 |
> |
} catch (Exception e) { |
1353 |
> |
throw new Error(e); |
1354 |
> |
} |
1355 |
|
} |
1356 |
|
|
1357 |
< |
// Unsafe mechanics for jsr166y 3rd party package. |
1357 |
> |
/** |
1358 |
> |
* Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package. |
1359 |
> |
* Replace with a simple call to Unsafe.getUnsafe when integrating |
1360 |
> |
* into a jdk. |
1361 |
> |
* |
1362 |
> |
* @return a sun.misc.Unsafe |
1363 |
> |
*/ |
1364 |
|
private static sun.misc.Unsafe getUnsafe() { |
1365 |
|
try { |
1366 |
|
return sun.misc.Unsafe.getUnsafe(); |
1367 |
|
} catch (SecurityException se) { |
1368 |
|
try { |
1369 |
|
return java.security.AccessController.doPrivileged |
1370 |
< |
(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() { |
1370 |
> |
(new java.security |
1371 |
> |
.PrivilegedExceptionAction<sun.misc.Unsafe>() { |
1372 |
|
public sun.misc.Unsafe run() throws Exception { |
1373 |
< |
return getUnsafeByReflection(); |
1373 |
> |
java.lang.reflect.Field f = sun.misc |
1374 |
> |
.Unsafe.class.getDeclaredField("theUnsafe"); |
1375 |
> |
f.setAccessible(true); |
1376 |
> |
return (sun.misc.Unsafe) f.get(null); |
1377 |
|
}}); |
1378 |
|
} catch (java.security.PrivilegedActionException e) { |
1379 |
|
throw new RuntimeException("Could not initialize intrinsics", |
1381 |
|
} |
1382 |
|
} |
1383 |
|
} |
1131 |
– |
|
1132 |
– |
private static sun.misc.Unsafe getUnsafeByReflection() |
1133 |
– |
throws NoSuchFieldException, IllegalAccessException { |
1134 |
– |
java.lang.reflect.Field f = |
1135 |
– |
sun.misc.Unsafe.class.getDeclaredField("theUnsafe"); |
1136 |
– |
f.setAccessible(true); |
1137 |
– |
return (sun.misc.Unsafe) f.get(null); |
1138 |
– |
} |
1139 |
– |
|
1140 |
– |
private static long fieldOffset(String fieldName, Class<?> klazz) { |
1141 |
– |
try { |
1142 |
– |
return UNSAFE.objectFieldOffset(klazz.getDeclaredField(fieldName)); |
1143 |
– |
} catch (NoSuchFieldException e) { |
1144 |
– |
// Convert Exception to Error |
1145 |
– |
NoSuchFieldError error = new NoSuchFieldError(fieldName); |
1146 |
– |
error.initCause(e); |
1147 |
– |
throw error; |
1148 |
– |
} |
1149 |
– |
} |
1150 |
– |
|
1151 |
– |
private static final sun.misc.Unsafe UNSAFE = getUnsafe(); |
1152 |
– |
static final long statusOffset = |
1153 |
– |
fieldOffset("status", ForkJoinTask.class); |
1154 |
– |
|
1384 |
|
} |