ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/ForkJoinPool.java
(Generate patch)

Comparing jsr166/src/jsr166y/ForkJoinPool.java (file contents):
Revision 1.16 by jsr166, Thu Jul 23 19:44:46 2009 UTC vs.
Revision 1.21 by jsr166, Fri Jul 24 23:47:01 2009 UTC

# Line 9 | Line 9 | import java.util.*;
9   import java.util.concurrent.*;
10   import java.util.concurrent.locks.*;
11   import java.util.concurrent.atomic.*;
12 import sun.misc.Unsafe;
13 import java.lang.reflect.*;
12  
13   /**
14   * An {@link ExecutorService} for running {@link ForkJoinTask}s.  A
# Line 90 | Line 88 | public class ForkJoinPool extends Abstra
88      }
89  
90      /**
91 <     * Default ForkJoinWorkerThreadFactory implementation, creates a
91 >     * Default ForkJoinWorkerThreadFactory implementation; creates a
92       * new ForkJoinWorkerThread.
93       */
94      static class  DefaultForkJoinWorkerThreadFactory
# Line 184 | Line 182 | public class ForkJoinPool extends Abstra
182      private final LinkedTransferQueue<ForkJoinTask<?>> submissionQueue;
183  
184      /**
185 <     * Head of Treiber stack for barrier sync. See below for explanation
185 >     * Head of Treiber stack for barrier sync. See below for explanation.
186       */
187      private volatile WaitQueueNode syncStack;
188  
# Line 232 | Line 230 | public class ForkJoinPool extends Abstra
230       * Adds delta (which may be negative) to running count.  This must
231       * be called before (with negative arg) and after (with positive)
232       * any managed synchronization (i.e., mainly, joins).
233 +     *
234       * @param delta the number to add
235       */
236      final void updateRunningCount(int delta) {
237          int s;
238 <        do;while (!casWorkerCounts(s = workerCounts, s + delta));
238 >        do {} while (!casWorkerCounts(s = workerCounts, s + delta));
239      }
240  
241      /**
242       * Adds delta (which may be negative) to both total and running
243       * count.  This must be called upon creation and termination of
244       * worker threads.
245 +     *
246       * @param delta the number to add
247       */
248      private void updateWorkerCount(int delta) {
249          int d = delta + (delta << 16); // add to both lo and hi parts
250          int s;
251 <        do;while (!casWorkerCounts(s = workerCounts, s + d));
251 >        do {} while (!casWorkerCounts(s = workerCounts, s + d));
252      }
253  
254      /**
# Line 274 | Line 274 | public class ForkJoinPool extends Abstra
274      private static int runControlFor(int r, int a)   { return (r << 16) + a; }
275  
276      /**
277 <     * Try incrementing active count; fail on contention. Called by
278 <     * workers before/during executing tasks.
277 >     * Tries incrementing active count; fails on contention.
278 >     * Called by workers before/during executing tasks.
279 >     *
280       * @return true on success
281       */
282      final boolean tryIncrementActiveCount() {
# Line 287 | Line 288 | public class ForkJoinPool extends Abstra
288       * Tries decrementing active count; fails on contention.
289       * Possibly triggers termination on success.
290       * Called by workers when they can't find tasks.
291 +     *
292       * @return true on success
293       */
294      final boolean tryDecrementActiveCount() {
# Line 305 | Line 307 | public class ForkJoinPool extends Abstra
307       * terminating on shutdown.
308       */
309      private static boolean canTerminateOnShutdown(int c) {
310 <        return ((c & -c) >>> 16) != 0; // i.e. least bit is nonzero runState bit
310 >        // i.e. least bit is nonzero runState bit
311 >        return ((c & -c) >>> 16) != 0;
312      }
313  
314      /**
# Line 331 | Line 334 | public class ForkJoinPool extends Abstra
334  
335      /**
336       * Creates a ForkJoinPool with a pool size equal to the number of
337 <     * processors available on the system and using the default
338 <     * ForkJoinWorkerThreadFactory,
337 >     * processors available on the system, using the default
338 >     * ForkJoinWorkerThreadFactory.
339 >     *
340       * @throws SecurityException if a security manager exists and
341       *         the caller is not permitted to modify threads
342       *         because it does not hold {@link
343 <     *         java.lang.RuntimePermission}{@code ("modifyThread")},
343 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
344       */
345      public ForkJoinPool() {
346          this(Runtime.getRuntime().availableProcessors(),
# Line 345 | Line 349 | public class ForkJoinPool extends Abstra
349  
350      /**
351       * Creates a ForkJoinPool with the indicated parallelism level
352 <     * threads, and using the default ForkJoinWorkerThreadFactory,
352 >     * threads and using the default ForkJoinWorkerThreadFactory.
353 >     *
354       * @param parallelism the number of worker threads
355       * @throws IllegalArgumentException if parallelism less than or
356       * equal to zero
357       * @throws SecurityException if a security manager exists and
358       *         the caller is not permitted to modify threads
359       *         because it does not hold {@link
360 <     *         java.lang.RuntimePermission}{@code ("modifyThread")},
360 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
361       */
362      public ForkJoinPool(int parallelism) {
363          this(parallelism, defaultForkJoinWorkerThreadFactory);
# Line 361 | Line 366 | public class ForkJoinPool extends Abstra
366      /**
367       * Creates a ForkJoinPool with parallelism equal to the number of
368       * processors available on the system and using the given
369 <     * ForkJoinWorkerThreadFactory,
369 >     * ForkJoinWorkerThreadFactory.
370 >     *
371       * @param factory the factory for creating new threads
372       * @throws NullPointerException if factory is null
373       * @throws SecurityException if a security manager exists and
374       *         the caller is not permitted to modify threads
375       *         because it does not hold {@link
376 <     *         java.lang.RuntimePermission}{@code ("modifyThread")},
376 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
377       */
378      public ForkJoinPool(ForkJoinWorkerThreadFactory factory) {
379          this(Runtime.getRuntime().availableProcessors(), factory);
# Line 384 | Line 390 | public class ForkJoinPool extends Abstra
390       * @throws SecurityException if a security manager exists and
391       *         the caller is not permitted to modify threads
392       *         because it does not hold {@link
393 <     *         java.lang.RuntimePermission}{@code ("modifyThread")},
393 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
394       */
395      public ForkJoinPool(int parallelism, ForkJoinWorkerThreadFactory factory) {
396          if (parallelism <= 0 || parallelism > MAX_THREADS)
# Line 405 | Line 411 | public class ForkJoinPool extends Abstra
411      }
412  
413      /**
414 <     * Create new worker using factory.
414 >     * Creates a new worker thread using factory.
415 >     *
416       * @param index the index to assign worker
417       * @return new worker, or null of factory failed
418       */
# Line 427 | Line 434 | public class ForkJoinPool extends Abstra
434       * Returns a good size for worker array given pool size.
435       * Currently requires size to be a power of two.
436       */
437 <    private static int arraySizeFor(int ps) {
438 <        return ps <= 1? 1 : (1 << (32 - Integer.numberOfLeadingZeros(ps-1)));
437 >    private static int arraySizeFor(int poolSize) {
438 >        return (poolSize <= 1) ? 1 :
439 >            (1 << (32 - Integer.numberOfLeadingZeros(poolSize-1)));
440      }
441  
442      /**
# Line 448 | Line 456 | public class ForkJoinPool extends Abstra
456      }
457  
458      /**
459 <     * Try to shrink workers into smaller array after one or more terminate
459 >     * Tries to shrink workers into smaller array after one or more terminate.
460       */
461      private void tryShrinkWorkerArray() {
462          ForkJoinWorkerThread[] ws = workers;
# Line 464 | Line 472 | public class ForkJoinPool extends Abstra
472      }
473  
474      /**
475 <     * Initialize workers if necessary
475 >     * Initializes workers if necessary.
476       */
477      final void ensureWorkerInitialization() {
478          ForkJoinWorkerThread[] ws = workers;
# Line 540 | Line 548 | public class ForkJoinPool extends Abstra
548      }
549  
550      /**
551 <     * Performs the given task; returning its result upon completion
551 >     * Performs the given task, returning its result upon completion.
552 >     *
553       * @param task the task
554       * @return the task's result
555       * @throws NullPointerException if task is null
# Line 553 | Line 562 | public class ForkJoinPool extends Abstra
562  
563      /**
564       * Arranges for (asynchronous) execution of the given task.
565 +     *
566       * @param task the task
567       * @throws NullPointerException if task is null
568       * @throws RejectedExecutionException if pool is shut down
# Line 587 | Line 597 | public class ForkJoinPool extends Abstra
597  
598      /**
599       * Adaptor for Runnables. This implements RunnableFuture
600 <     * to be compliant with AbstractExecutorService constraints
600 >     * to be compliant with AbstractExecutorService constraints.
601       */
602      static final class AdaptedRunnable<T> extends ForkJoinTask<T>
603          implements RunnableFuture<T> {
# Line 607 | Line 617 | public class ForkJoinPool extends Abstra
617              return true;
618          }
619          public void run() { invoke(); }
620 +        private static final long serialVersionUID = 5232453952276885070L;
621      }
622  
623      /**
# Line 635 | Line 646 | public class ForkJoinPool extends Abstra
646              }
647          }
648          public void run() { invoke(); }
649 +        private static final long serialVersionUID = 2838392045355241008L;
650      }
651  
652      public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) {
653 <        ArrayList<ForkJoinTask<T>> ts =
653 >        ArrayList<ForkJoinTask<T>> forkJoinTasks =
654              new ArrayList<ForkJoinTask<T>>(tasks.size());
655 <        for (Callable<T> c : tasks)
656 <            ts.add(new AdaptedCallable<T>(c));
657 <        invoke(new InvokeAll<T>(ts));
658 <        return (List<Future<T>>)(List)ts;
655 >        for (Callable<T> task : tasks)
656 >            forkJoinTasks.add(new AdaptedCallable<T>(task));
657 >        invoke(new InvokeAll<T>(forkJoinTasks));
658 >
659 >        @SuppressWarnings({"unchecked", "rawtypes"})
660 >        List<Future<T>> futures = (List<Future<T>>) (List) forkJoinTasks;
661 >        return futures;
662      }
663  
664      static final class InvokeAll<T> extends RecursiveAction {
665          final ArrayList<ForkJoinTask<T>> tasks;
666          InvokeAll(ArrayList<ForkJoinTask<T>> tasks) { this.tasks = tasks; }
667          public void compute() {
668 <            try { invokeAll(tasks); } catch(Exception ignore) {}
668 >            try { invokeAll(tasks); }
669 >            catch (Exception ignore) {}
670          }
671 +        private static final long serialVersionUID = -7914297376763021607L;
672      }
673  
674      // Configuration and status settings and queries
675  
676      /**
677 <     * Returns the factory used for constructing new workers
677 >     * Returns the factory used for constructing new workers.
678       *
679       * @return the factory used for constructing new workers
680       */
# Line 668 | Line 685 | public class ForkJoinPool extends Abstra
685      /**
686       * Returns the handler for internal worker threads that terminate
687       * due to unrecoverable errors encountered while executing tasks.
688 +     *
689       * @return the handler, or null if none
690       */
691      public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() {
# Line 693 | Line 711 | public class ForkJoinPool extends Abstra
711       * @throws SecurityException if a security manager exists and
712       *         the caller is not permitted to modify threads
713       *         because it does not hold {@link
714 <     *         java.lang.RuntimePermission}{@code ("modifyThread")},
714 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
715       */
716      public Thread.UncaughtExceptionHandler
717          setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler h) {
# Line 721 | Line 739 | public class ForkJoinPool extends Abstra
739  
740      /**
741       * Sets the target parallelism level of this pool.
742 +     *
743       * @param parallelism the target parallelism
744       * @throws IllegalArgumentException if parallelism less than or
745       * equal to zero or greater than maximum size bounds
746       * @throws SecurityException if a security manager exists and
747       *         the caller is not permitted to modify threads
748       *         because it does not hold {@link
749 <     *         java.lang.RuntimePermission}{@code ("modifyThread")},
749 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
750       */
751      public void setParallelism(int parallelism) {
752          checkPermission();
# Line 774 | Line 793 | public class ForkJoinPool extends Abstra
793      /**
794       * Returns the maximum number of threads allowed to exist in the
795       * pool, even if there are insufficient unblocked running threads.
796 +     *
797       * @return the maximum
798       */
799      public int getMaximumPoolSize() {
# Line 785 | Line 805 | public class ForkJoinPool extends Abstra
805       * pool, even if there are insufficient unblocked running threads.
806       * Setting this value has no effect on current pool size. It
807       * controls construction of new threads.
808 +     *
809       * @throws IllegalArgumentException if negative or greater then
810       * internal implementation limit
811       */
# Line 799 | Line 820 | public class ForkJoinPool extends Abstra
820       * Returns true if this pool dynamically maintains its target
821       * parallelism level. If false, new threads are added only to
822       * avoid possible starvation.
823 <     * This setting is by default true;
823 >     * This setting is by default true.
824 >     *
825       * @return true if maintains parallelism
826       */
827      public boolean getMaintainsParallelism() {
# Line 810 | Line 832 | public class ForkJoinPool extends Abstra
832       * Sets whether this pool dynamically maintains its target
833       * parallelism level. If false, new threads are added only to
834       * avoid possible starvation.
835 +     *
836       * @param enable true to maintains parallelism
837       */
838      public void setMaintainsParallelism(boolean enable) {
# Line 867 | Line 890 | public class ForkJoinPool extends Abstra
890       * Returns an estimate of the number of threads that are currently
891       * stealing or executing tasks. This method may overestimate the
892       * number of active threads.
893 +     *
894       * @return the number of active threads
895       */
896      public int getActiveThreadCount() {
# Line 877 | Line 901 | public class ForkJoinPool extends Abstra
901       * Returns an estimate of the number of threads that are currently
902       * idle waiting for tasks. This method may underestimate the
903       * number of idle threads.
904 +     *
905       * @return the number of idle threads
906       */
907      final int getIdleThreadCount() {
908          int c = runningCountOf(workerCounts) - activeCountOf(runControl);
909 <        return (c <= 0)? 0 : c;
909 >        return (c <= 0) ? 0 : c;
910      }
911  
912      /**
913       * Returns true if all worker threads are currently idle. An idle
914       * worker is one that cannot obtain a task to execute because none
915       * are available to steal from other threads, and there are no
916 <     * pending submissions to the pool. This method is conservative:
917 <     * It might not return true immediately upon idleness of all
916 >     * pending submissions to the pool. This method is conservative;
917 >     * it might not return true immediately upon idleness of all
918       * threads, but will eventually become true if threads remain
919       * inactive.
920 +     *
921       * @return true if all threads are currently idle
922       */
923      public boolean isQuiescent() {
# Line 903 | Line 929 | public class ForkJoinPool extends Abstra
929       * one thread's work queue by another. The reported value
930       * underestimates the actual total number of steals when the pool
931       * is not quiescent. This value may be useful for monitoring and
932 <     * tuning fork/join programs: In general, steal counts should be
932 >     * tuning fork/join programs: in general, steal counts should be
933       * high enough to keep threads busy, but low enough to avoid
934       * overhead and contention across threads.
935 +     *
936       * @return the number of steals
937       */
938      public long getStealCount() {
# Line 913 | Line 940 | public class ForkJoinPool extends Abstra
940      }
941  
942      /**
943 <     * Accumulate steal count from a worker. Call only
944 <     * when worker known to be idle.
943 >     * Accumulates steal count from a worker.
944 >     * Call only when worker known to be idle.
945       */
946      private void updateStealCount(ForkJoinWorkerThread w) {
947          int sc = w.getAndClearStealCount();
# Line 929 | Line 956 | public class ForkJoinPool extends Abstra
956       * an approximation, obtained by iterating across all threads in
957       * the pool. This method may be useful for tuning task
958       * granularities.
959 +     *
960       * @return the number of queued tasks
961       */
962      public long getQueuedTaskCount() {
# Line 948 | Line 976 | public class ForkJoinPool extends Abstra
976       * Returns an estimate of the number tasks submitted to this pool
977       * that have not yet begun executing. This method takes time
978       * proportional to the number of submissions.
979 +     *
980       * @return the number of queued submissions
981       */
982      public int getQueuedSubmissionCount() {
# Line 957 | Line 986 | public class ForkJoinPool extends Abstra
986      /**
987       * Returns true if there are any tasks submitted to this pool
988       * that have not yet begun executing.
989 +     *
990       * @return {@code true} if there are any queued submissions
991       */
992      public boolean hasQueuedSubmissions() {
# Line 967 | Line 997 | public class ForkJoinPool extends Abstra
997       * Removes and returns the next unexecuted submission if one is
998       * available.  This method may be useful in extensions to this
999       * class that re-assign work in systems with multiple pools.
1000 +     *
1001       * @return the next submission, or null if none
1002       */
1003      protected ForkJoinTask<?> pollSubmission() {
# Line 986 | Line 1017 | public class ForkJoinPool extends Abstra
1017       * exception is thrown.  The behavior of this operation is
1018       * undefined if the specified collection is modified while the
1019       * operation is in progress.
1020 +     *
1021       * @param c the collection to transfer elements into
1022       * @return the number of elements transferred
1023       */
# Line 1046 | Line 1078 | public class ForkJoinPool extends Abstra
1078       * Invocation has no additional effect if already shut down.
1079       * Tasks that are in the process of being submitted concurrently
1080       * during the course of this method may or may not be rejected.
1081 +     *
1082       * @throws SecurityException if a security manager exists and
1083       *         the caller is not permitted to modify threads
1084       *         because it does not hold {@link
1085 <     *         java.lang.RuntimePermission}{@code ("modifyThread")},
1085 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
1086       */
1087      public void shutdown() {
1088          checkPermission();
# Line 1067 | Line 1100 | public class ForkJoinPool extends Abstra
1100       * upon termination, so always returns an empty list. However, you
1101       * can use method {@code drainTasksTo} before invoking this
1102       * method to transfer unexecuted tasks to another collection.
1103 +     *
1104       * @return an empty list
1105       * @throws SecurityException if a security manager exists and
1106       *         the caller is not permitted to modify threads
1107       *         because it does not hold {@link
1108 <     *         java.lang.RuntimePermission}{@code ("modifyThread")},
1108 >     *         java.lang.RuntimePermission}{@code ("modifyThread")}
1109       */
1110      public List<Runnable> shutdownNow() {
1111          checkPermission();
# Line 1139 | Line 1173 | public class ForkJoinPool extends Abstra
1173      // Shutdown and termination support
1174  
1175      /**
1176 <     * Callback from terminating worker. Null out the corresponding
1177 <     * workers slot, and if terminating, try to terminate, else try to
1178 <     * shrink workers array.
1176 >     * Callback from terminating worker. Nulls out the corresponding
1177 >     * workers slot, and if terminating, tries to terminate; else
1178 >     * tries to shrink workers array.
1179 >     *
1180       * @param w the worker
1181       */
1182      final void workerTerminated(ForkJoinWorkerThread w) {
# Line 1172 | Line 1207 | public class ForkJoinPool extends Abstra
1207      }
1208  
1209      /**
1210 <     * Initiate termination.
1210 >     * Initiates termination.
1211       */
1212      private void terminate() {
1213          if (transitionRunStateTo(TERMINATING)) {
# Line 1349 | Line 1384 | public class ForkJoinPool extends Abstra
1384       * Ensures that no thread is waiting for count to advance from the
1385       * current value of eventCount read on entry to this method, by
1386       * releasing waiting threads if necessary.
1387 +     *
1388       * @return the count
1389       */
1390      final long ensureSync() {
# Line 1370 | Line 1406 | public class ForkJoinPool extends Abstra
1406       */
1407      private void signalIdleWorkers() {
1408          long c;
1409 <        do;while (!casEventCount(c = eventCount, c+1));
1409 >        do {} while (!casEventCount(c = eventCount, c+1));
1410          ensureSync();
1411      }
1412  
# Line 1394 | Line 1430 | public class ForkJoinPool extends Abstra
1430       * Waits until event count advances from last value held by
1431       * caller, or if excess threads, caller is resumed as spare, or
1432       * caller or pool is terminating. Updates caller's event on exit.
1433 +     *
1434       * @param w the calling worker thread
1435       */
1436      final void sync(ForkJoinWorkerThread w) {
# Line 1424 | Line 1461 | public class ForkJoinPool extends Abstra
1461       * Returns true if worker waiting on sync can proceed:
1462       *  - on signal (thread == null)
1463       *  - on event count advance (winning race to notify vs signaller)
1464 <     *  - on Interrupt
1464 >     *  - on interrupt
1465       *  - if the first queued node, we find work available
1466       * If node was not signalled and event count not advanced on exit,
1467       * then we also help advance event count.
1468 +     *
1469       * @return true if node can be released
1470       */
1471      final boolean syncIsReleasable(WaitQueueNode node) {
# Line 1468 | Line 1506 | public class ForkJoinPool extends Abstra
1506       * spare thread when one is about to block (and remove or
1507       * suspend it later when unblocked -- see suspendIfSpare).
1508       * However, implementing this idea requires coping with
1509 <     * several problems: We have imperfect information about the
1509 >     * several problems: we have imperfect information about the
1510       * states of threads. Some count updates can and usually do
1511       * lag run state changes, despite arrangements to keep them
1512       * accurate (for example, when possible, updating counts
# Line 1491 | Line 1529 | public class ForkJoinPool extends Abstra
1529       * target counts, else create only to avoid starvation
1530       * @return true if joinMe known to be done
1531       */
1532 <    final boolean preJoin(ForkJoinTask<?> joinMe, boolean maintainParallelism) {
1532 >    final boolean preJoin(ForkJoinTask<?> joinMe,
1533 >                          boolean maintainParallelism) {
1534          maintainParallelism &= maintainsParallelism; // overrride
1535          boolean dec = false;  // true when running count decremented
1536          while (spareStack == null || !tryResumeSpare(dec)) {
1537              int counts = workerCounts;
1538 <            if (dec || (dec = casWorkerCounts(counts, --counts))) { // CAS cheat
1538 >            if (dec || (dec = casWorkerCounts(counts, --counts))) {
1539 >                // CAS cheat
1540                  if (!needSpare(counts, maintainParallelism))
1541                      break;
1542                  if (joinMe.status < 0)
# Line 1511 | Line 1551 | public class ForkJoinPool extends Abstra
1551      /**
1552       * Same idea as preJoin
1553       */
1554 <    final boolean preBlock(ManagedBlocker blocker, boolean maintainParallelism){
1554 >    final boolean preBlock(ManagedBlocker blocker,
1555 >                           boolean maintainParallelism) {
1556          maintainParallelism &= maintainsParallelism;
1557          boolean dec = false;
1558          while (spareStack == null || !tryResumeSpare(dec)) {
# Line 1535 | Line 1576 | public class ForkJoinPool extends Abstra
1576       * there is apparently some work to do.  This self-limiting rule
1577       * means that the more threads that have already been added, the
1578       * less parallelism we will tolerate before adding another.
1579 +     *
1580       * @param counts current worker counts
1581       * @param maintainParallelism try to maintain parallelism
1582       */
# Line 1554 | Line 1596 | public class ForkJoinPool extends Abstra
1596      /**
1597       * Adds a spare worker if lock available and no more than the
1598       * expected numbers of threads exist.
1599 +     *
1600       * @return true if successful
1601       */
1602      private boolean tryAddSpare(int expectedCounts) {
# Line 1613 | Line 1656 | public class ForkJoinPool extends Abstra
1656       * the same WaitQueueNodes as barriers.  They are resumed mainly
1657       * in preJoin, but are also woken on pool events that require all
1658       * threads to check run state.
1659 +     *
1660       * @param w the caller
1661       */
1662      private boolean suspendIfSpare(ForkJoinWorkerThread w) {
# Line 1623 | Line 1667 | public class ForkJoinPool extends Abstra
1667                  node = new WaitQueueNode(0, w);
1668              if (casWorkerCounts(s, s-1)) { // representation-dependent
1669                  // push onto stack
1670 <                do;while (!casSpareStack(node.next = spareStack, node));
1670 >                do {} while (!casSpareStack(node.next = spareStack, node));
1671                  // block until released by resumeSpare
1672                  node.awaitSpareRelease();
1673                  return true;
# Line 1634 | Line 1678 | public class ForkJoinPool extends Abstra
1678  
1679      /**
1680       * Tries to pop and resume a spare thread.
1681 +     *
1682       * @param updateCount if true, increment running count on success
1683       * @return true if successful
1684       */
# Line 1652 | Line 1697 | public class ForkJoinPool extends Abstra
1697  
1698      /**
1699       * Pops and resumes all spare threads. Same idea as ensureSync.
1700 +     *
1701       * @return true if any spares released
1702       */
1703      private boolean resumeAllSpares() {
# Line 1695 | Line 1741 | public class ForkJoinPool extends Abstra
1741       * Interface for extending managed parallelism for tasks running
1742       * in ForkJoinPools. A ManagedBlocker provides two methods.
1743       * Method {@code isReleasable} must return true if blocking is not
1744 <     * necessary. Method {@code block} blocks the current thread
1745 <     * if necessary (perhaps internally invoking isReleasable before
1746 <     * actually blocking.).
1744 >     * necessary. Method {@code block} blocks the current thread if
1745 >     * necessary (perhaps internally invoking {@code isReleasable}
1746 >     * before actually blocking.).
1747 >     *
1748       * <p>For example, here is a ManagedBlocker based on a
1749       * ReentrantLock:
1750 <     * <pre>
1751 <     *   class ManagedLocker implements ManagedBlocker {
1752 <     *     final ReentrantLock lock;
1753 <     *     boolean hasLock = false;
1754 <     *     ManagedLocker(ReentrantLock lock) { this.lock = lock; }
1755 <     *     public boolean block() {
1756 <     *        if (!hasLock)
1757 <     *           lock.lock();
1758 <     *        return true;
1759 <     *     }
1760 <     *     public boolean isReleasable() {
1761 <     *        return hasLock || (hasLock = lock.tryLock());
1715 <     *     }
1750 >     *  <pre> {@code
1751 >     * class ManagedLocker implements ManagedBlocker {
1752 >     *   final ReentrantLock lock;
1753 >     *   boolean hasLock = false;
1754 >     *   ManagedLocker(ReentrantLock lock) { this.lock = lock; }
1755 >     *   public boolean block() {
1756 >     *     if (!hasLock)
1757 >     *       lock.lock();
1758 >     *     return true;
1759 >     *   }
1760 >     *   public boolean isReleasable() {
1761 >     *     return hasLock || (hasLock = lock.tryLock());
1762       *   }
1763 <     * </pre>
1763 >     * }}</pre>
1764       */
1765      public static interface ManagedBlocker {
1766          /**
1767           * Possibly blocks the current thread, for example waiting for
1768           * a lock or condition.
1769 +         *
1770           * @return true if no additional blocking is necessary (i.e.,
1771           * if isReleasable would return true)
1772           * @throws InterruptedException if interrupted while waiting
1773 <         * (the method is not required to do so, but is allowed to).
1773 >         * (the method is not required to do so, but is allowed to)
1774           */
1775          boolean block() throws InterruptedException;
1776  
# Line 1740 | Line 1787 | public class ForkJoinPool extends Abstra
1787       * while the current thread is blocked.  If
1788       * {@code maintainParallelism} is true and the pool supports
1789       * it ({@link #getMaintainsParallelism}), this method attempts to
1790 <     * maintain the pool's nominal parallelism. Otherwise if activates
1790 >     * maintain the pool's nominal parallelism. Otherwise it activates
1791       * a thread only if necessary to avoid complete starvation. This
1792       * option may be preferable when blockages use timeouts, or are
1793       * almost always brief.
1794       *
1795       * <p> If the caller is not a ForkJoinTask, this method is behaviorally
1796       * equivalent to
1797 <     * <pre>
1798 <     *   while (!blocker.isReleasable())
1799 <     *      if (blocker.block())
1800 <     *         return;
1801 <     * </pre>
1797 >     *  <pre> {@code
1798 >     * while (!blocker.isReleasable())
1799 >     *   if (blocker.block())
1800 >     *     return;
1801 >     * }</pre>
1802       * If the caller is a ForkJoinTask, then the pool may first
1803       * be expanded to ensure parallelism, and later adjusted.
1804       *
# Line 1766 | Line 1813 | public class ForkJoinPool extends Abstra
1813                                      boolean maintainParallelism)
1814          throws InterruptedException {
1815          Thread t = Thread.currentThread();
1816 <        ForkJoinPool pool = (t instanceof ForkJoinWorkerThread?
1817 <                             ((ForkJoinWorkerThread)t).pool : null);
1816 >        ForkJoinPool pool = ((t instanceof ForkJoinWorkerThread) ?
1817 >                             ((ForkJoinWorkerThread) t).pool : null);
1818          if (!blocker.isReleasable()) {
1819              try {
1820                  if (pool == null ||
# Line 1782 | Line 1829 | public class ForkJoinPool extends Abstra
1829  
1830      private static void awaitBlocker(ManagedBlocker blocker)
1831          throws InterruptedException {
1832 <        do;while (!blocker.isReleasable() && !blocker.block());
1832 >        do {} while (!blocker.isReleasable() && !blocker.block());
1833      }
1834  
1835      // AbstractExecutorService overrides
1836  
1837      protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
1838 <        return new AdaptedRunnable(runnable, value);
1838 >        return new AdaptedRunnable<T>(runnable, value);
1839      }
1840  
1841      protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
1842 <        return new AdaptedCallable(callable);
1842 >        return new AdaptedCallable<T>(callable);
1843      }
1844  
1845  
1846 <    // Temporary Unsafe mechanics for preliminary release
1847 <    private static Unsafe getUnsafe() throws Throwable {
1846 >    // Unsafe mechanics for jsr166y 3rd party package.
1847 >    private static sun.misc.Unsafe getUnsafe() {
1848          try {
1849 <            return Unsafe.getUnsafe();
1849 >            return sun.misc.Unsafe.getUnsafe();
1850          } catch (SecurityException se) {
1851              try {
1852                  return java.security.AccessController.doPrivileged
1853 <                    (new java.security.PrivilegedExceptionAction<Unsafe>() {
1854 <                        public Unsafe run() throws Exception {
1855 <                            return getUnsafePrivileged();
1853 >                    (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
1854 >                        public sun.misc.Unsafe run() throws Exception {
1855 >                            return getUnsafeByReflection();
1856                          }});
1857              } catch (java.security.PrivilegedActionException e) {
1858 <                throw e.getCause();
1858 >                throw new RuntimeException("Could not initialize intrinsics",
1859 >                                           e.getCause());
1860              }
1861          }
1862      }
1863  
1864 <    private static Unsafe getUnsafePrivileged()
1864 >    private static sun.misc.Unsafe getUnsafeByReflection()
1865              throws NoSuchFieldException, IllegalAccessException {
1866 <        Field f = Unsafe.class.getDeclaredField("theUnsafe");
1866 >        java.lang.reflect.Field f =
1867 >            sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
1868          f.setAccessible(true);
1869 <        return (Unsafe) f.get(null);
1821 <    }
1822 <
1823 <    private static long fieldOffset(String fieldName)
1824 <            throws NoSuchFieldException {
1825 <        return UNSAFE.objectFieldOffset
1826 <            (ForkJoinPool.class.getDeclaredField(fieldName));
1869 >        return (sun.misc.Unsafe) f.get(null);
1870      }
1871  
1872 <    static final Unsafe UNSAFE;
1830 <    static final long eventCountOffset;
1831 <    static final long workerCountsOffset;
1832 <    static final long runControlOffset;
1833 <    static final long syncStackOffset;
1834 <    static final long spareStackOffset;
1835 <
1836 <    static {
1872 >    private static long fieldOffset(String fieldName, Class<?> klazz) {
1873          try {
1874 <            UNSAFE = getUnsafe();
1875 <            eventCountOffset = fieldOffset("eventCount");
1876 <            workerCountsOffset = fieldOffset("workerCounts");
1877 <            runControlOffset = fieldOffset("runControl");
1878 <            syncStackOffset = fieldOffset("syncStack");
1879 <            spareStackOffset = fieldOffset("spareStack");
1844 <        } catch (Throwable e) {
1845 <            throw new RuntimeException("Could not initialize intrinsics", e);
1874 >            return UNSAFE.objectFieldOffset(klazz.getDeclaredField(fieldName));
1875 >        } catch (NoSuchFieldException e) {
1876 >            // Convert Exception to Error
1877 >            NoSuchFieldError error = new NoSuchFieldError(fieldName);
1878 >            error.initCause(e);
1879 >            throw error;
1880          }
1881      }
1882  
1883 +    private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1884 +    static final long eventCountOffset =
1885 +        fieldOffset("eventCount", ForkJoinPool.class);
1886 +    static final long workerCountsOffset =
1887 +        fieldOffset("workerCounts", ForkJoinPool.class);
1888 +    static final long runControlOffset =
1889 +        fieldOffset("runControl", ForkJoinPool.class);
1890 +    static final long syncStackOffset =
1891 +        fieldOffset("syncStack",ForkJoinPool.class);
1892 +    static final long spareStackOffset =
1893 +        fieldOffset("spareStack", ForkJoinPool.class);
1894 +
1895      private boolean casEventCount(long cmp, long val) {
1896          return UNSAFE.compareAndSwapLong(this, eventCountOffset, cmp, val);
1897      }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines