ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/ForkJoinTask.java
Revision: 1.25
Committed: Fri Jul 31 16:27:08 2009 UTC (14 years, 9 months ago) by dl
Branch: MAIN
Changes since 1.24: +71 -14 lines
Log Message:
Refactor Adapted tasks into ForkJoinTask; mesh peek/pollNextLocalTask specs and code

File Contents

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