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

Comparing jsr166/src/jsr166y/ForkJoinTask.java (file contents):
Revision 1.86 by dl, Mon Feb 20 18:20:06 2012 UTC vs.
Revision 1.90 by dl, Sat Apr 21 11:45:20 2012 UTC

# Line 5 | Line 5
5   */
6  
7   package jsr166y;
8 +
9   import java.io.Serializable;
10   import java.util.Collection;
11   import java.util.List;
# Line 70 | Line 71 | import java.lang.reflect.Constructor;
71   * but doing do requires three further considerations: (1) Completion
72   * of few if any <em>other</em> tasks should be dependent on a task
73   * that blocks on external synchronization or IO. Event-style async
74 < * tasks that are never joined often fall into this category.  (2) To
75 < * minimize resource impact, tasks should be small; ideally performing
76 < * only the (possibly) blocking action. (3) Unless the {@link
74 > * tasks that are never joined (for example, those subclassing {@link
75 > * CountedCompleter}) often fall into this category.  (2) To minimize
76 > * resource impact, tasks should be small; ideally performing only the
77 > * (possibly) blocking action. (3) Unless the {@link
78   * ForkJoinPool.ManagedBlocker} API is used, or the number of possibly
79   * blocked tasks is known to be less than the pool's {@link
80   * ForkJoinPool#getParallelism} level, the pool cannot guarantee that
# Line 115 | Line 117 | import java.lang.reflect.Constructor;
117   * <p>The ForkJoinTask class is not usually directly subclassed.
118   * Instead, you subclass one of the abstract classes that support a
119   * particular style of fork/join processing, typically {@link
120 < * RecursiveAction} for computations that do not return results, or
121 < * {@link RecursiveTask} for those that do.  Normally, a concrete
122 < * ForkJoinTask subclass declares fields comprising its parameters,
123 < * established in a constructor, and then defines a {@code compute}
124 < * method that somehow uses the control methods supplied by this base
125 < * class. While these methods have {@code public} access (to allow
126 < * instances of different task subclasses to call each other's
127 < * methods), some of them may only be called from within other
128 < * ForkJoinTasks (as may be determined using method {@link
129 < * #inForkJoinPool}).  Attempts to invoke them in other contexts
130 < * result in exceptions or errors, possibly including
131 < * {@code ClassCastException}.
120 > * RecursiveAction} for most computations that do not return results,
121 > * {@link RecursiveTask} for those that do, and {@link
122 > * CountedCompleter} for those in which completed actions trigger
123 > * other actions.  Normally, a concrete ForkJoinTask subclass declares
124 > * fields comprising its parameters, established in a constructor, and
125 > * then defines a {@code compute} method that somehow uses the control
126 > * methods supplied by this base class. While these methods have
127 > * {@code public} access (to allow instances of different task
128 > * subclasses to call each other's methods), some of them may only be
129 > * called from within other ForkJoinTasks (as may be determined using
130 > * method {@link #inForkJoinPool}).  Attempts to invoke them in other
131 > * contexts result in exceptions or errors, possibly including {@code
132 > * ClassCastException}.
133   *
134   * <p>Method {@link #join} and its variants are appropriate for use
135   * only when completion dependencies are acyclic; that is, the
# Line 137 | Line 140 | import java.lang.reflect.Constructor;
140   * {@link Phaser}, {@link #helpQuiesce}, and {@link #complete}) that
141   * may be of use in constructing custom subclasses for problems that
142   * are not statically structured as DAGs. To support such usages a
143 < * ForkJoinTask may be atomically <em>marked</em> using {@link
144 < * #markForkJoinTask} and checked for marking using {@link
145 < * #isMarkedForkJoinTask}. The ForkJoinTask implementation does not
146 < * use these {@code protected} methods or marks for any purpose, but
147 < * they may be of use in the construction of specialized subclasses.
148 < * For example, parallel graph traversals can use the supplied methods
149 < * to avoid revisiting nodes/tasks that have already been processed.
150 < * Also, completion based designs can use them to record that one
151 < * subtask has completed. (Method names for marking are bulky in part
152 < * to encourage definition of methods that reflect their usage
150 < * patterns.)
143 > * ForkJoinTask may be atomically <em>tagged</em> with a {@code short}
144 > * value using {@link #setForkJoinTaskTag} or {@link
145 > * #compareAndSetForkJoinTaskTag} and checked using {@link
146 > * #getForkJoinTaskTag}. The ForkJoinTask implementation does not use
147 > * these {@code protected} methods or tags for any purpose, but they
148 > * may be of use in the construction of specialized subclasses.  For
149 > * example, parallel graph traversals can use the supplied methods to
150 > * avoid revisiting nodes/tasks that have already been processed.
151 > * (Method names for tagging are bulky in part to encourage definition
152 > * of methods that reflect their usage patterns.)
153   *
154   * <p>Most base support methods are {@code final}, to prevent
155   * overriding of implementations that are intrinsically tied to the
# Line 213 | Line 215 | public abstract class ForkJoinTask<V> im
215       * thin-lock techniques, so use some odd coding idioms that tend
216       * to avoid them, mainly by arranging that every synchronized
217       * block performs a wait, notifyAll or both.
218 +     *
219 +     * These control bits occupy only (some of) the upper half (16
220 +     * bits) of status field. The lower bits are used for user-defined
221 +     * tags.
222       */
223  
224      /** The run status of this task */
# Line 221 | Line 227 | public abstract class ForkJoinTask<V> im
227      static final int NORMAL      = 0xf0000000;  // must be negative
228      static final int CANCELLED   = 0xc0000000;  // must be < NORMAL
229      static final int EXCEPTIONAL = 0x80000000;  // must be < CANCELLED
230 <    static final int SIGNAL      = 0x00000001;
231 <    static final int MARKED      = 0x00000002;
230 >    static final int SIGNAL      = 0x00010000;  // must be >= 1 << 16
231 >    static final int SMASK       = 0x0000ffff;  // short bits for tags
232  
233      /**
234       * Marks completion and wakes up threads waiting to join this
235 <     * task. A specialization for NORMAL completion is in method
230 <     * doExec.
235 >     * task.
236       *
237       * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
238       * @return completion status on exit
# Line 237 | Line 242 | public abstract class ForkJoinTask<V> im
242              if ((s = status) < 0)
243                  return s;
244              if (U.compareAndSwapInt(this, STATUS, s, s | completion)) {
245 <                if ((s & SIGNAL) != 0)
245 >                if ((s >>> 16) != 0)
246                      synchronized (this) { notifyAll(); }
247                  return completion;
248              }
# Line 259 | Line 264 | public abstract class ForkJoinTask<V> im
264              } catch (Throwable rex) {
265                  return setExceptionalCompletion(rex);
266              }
267 <            while ((s = status) >= 0 && completed) {
268 <                if (U.compareAndSwapInt(this, STATUS, s, s | NORMAL)) {
264 <                    if ((s & SIGNAL) != 0)
265 <                        synchronized (this) { notifyAll(); }
266 <                    return NORMAL;
267 <                }
268 <            }
267 >            if (completed)
268 >                s = setCompletion(NORMAL);
269          }
270          return s;
271      }
272  
273      /**
274 <     * Tries to set SIGNAL status. Used by ForkJoinPool. Other
275 <     * variants are directly incorporated into externalAwaitDone etc.
274 >     * Tries to set SIGNAL status unless already completed. Used by
275 >     * ForkJoinPool. Other variants are directly incorporated into
276 >     * externalAwaitDone etc.
277       *
278       * @return true if successful
279       */
280      final boolean trySetSignal() {
281 <        int s;
282 <        return U.compareAndSwapInt(this, STATUS, s = status, s | SIGNAL);
281 >        int s = status;
282 >        return s >= 0 && U.compareAndSwapInt(this, STATUS, s, s | SIGNAL);
283      }
284  
285      /**
# Line 328 | Line 329 | public abstract class ForkJoinTask<V> im
329          return s;
330      }
331  
331
332      /**
333       * Implementation for join, get, quietlyJoin. Directly handles
334       * only cases of already-completed, external wait, and
# Line 412 | Line 412 | public abstract class ForkJoinTask<V> im
412      }
413  
414      /**
415 <     * Records exception and sets exceptional completion.
415 >     * Records exception and sets status.
416       *
417       * @return status on exit
418       */
419 <    private int setExceptionalCompletion(Throwable ex) {
420 <        int h = System.identityHashCode(this);
421 <        final ReentrantLock lock = exceptionTableLock;
422 <        lock.lock();
423 <        try {
424 <            expungeStaleExceptions();
425 <            ExceptionNode[] t = exceptionTable;
426 <            int i = h & (t.length - 1);
427 <            for (ExceptionNode e = t[i]; ; e = e.next) {
428 <                if (e == null) {
429 <                    t[i] = new ExceptionNode(this, ex, t[i]);
430 <                    break;
419 >    final int recordExceptionalCompletion(Throwable ex) {
420 >        int s;
421 >        if ((s = status) >= 0) {
422 >            int h = System.identityHashCode(this);
423 >            final ReentrantLock lock = exceptionTableLock;
424 >            lock.lock();
425 >            try {
426 >                expungeStaleExceptions();
427 >                ExceptionNode[] t = exceptionTable;
428 >                int i = h & (t.length - 1);
429 >                for (ExceptionNode e = t[i]; ; e = e.next) {
430 >                    if (e == null) {
431 >                        t[i] = new ExceptionNode(this, ex, t[i]);
432 >                        break;
433 >                    }
434 >                    if (e.get() == this) // already present
435 >                        break;
436                  }
437 <                if (e.get() == this) // already present
438 <                    break;
437 >            } finally {
438 >                lock.unlock();
439              }
440 <        } finally {
436 <            lock.unlock();
440 >            s = setCompletion(EXCEPTIONAL);
441          }
442 <        return setCompletion(EXCEPTIONAL);
442 >        return s;
443 >    }
444 >
445 >    /**
446 >     * Records exception and possibly propagates
447 >     *
448 >     * @return status on exit
449 >     */
450 >    private int setExceptionalCompletion(Throwable ex) {
451 >        int s = recordExceptionalCompletion(ex);
452 >        if ((s & DONE_MASK) == EXCEPTIONAL)
453 >            internalPropagateException(ex);
454 >        return s;
455 >    }
456 >
457 >    /**
458 >     * Hook for exception propagation support for tasks with completers.
459 >     */
460 >    void internalPropagateException(Throwable ex) {
461      }
462  
463      /**
# Line 517 | Line 539 | public abstract class ForkJoinTask<V> im
539          Throwable ex;
540          if (e == null || (ex = e.ex) == null)
541              return null;
542 <        if (e.thrower != Thread.currentThread().getId()) {
542 >        if (false && e.thrower != Thread.currentThread().getId()) {
543              Class<? extends Throwable> ec = ex.getClass();
544              try {
545                  Constructor<?> noArgCtor = null;
# Line 907 | Line 929 | public abstract class ForkJoinTask<V> im
929      }
930  
931      /**
932 +     * Completes this task normally without setting a value. The most
933 +     * recent value established by {@link #setRawResult} (or {@code
934 +     * null} by default) will be returned as the result of subsequent
935 +     * invocations of {@code join} and related operations.
936 +     *
937 +     * @since 1.8
938 +     */
939 +    public final void quietlyComplete() {
940 +        setCompletion(NORMAL);
941 +    }
942 +
943 +    /**
944       * Waits if necessary for the computation to complete, and then
945       * retrieves its result.
946       *
# Line 1225 | Line 1259 | public abstract class ForkJoinTask<V> im
1259      protected abstract void setRawResult(V value);
1260  
1261      /**
1262 <     * Immediately performs the base action of this task.  This method
1263 <     * is designed to support extensions, and should not in general be
1264 <     * called otherwise. The return value controls whether this task
1265 <     * is considered to be done normally. It may return false in
1262 >     * Immediately performs the base action of this task and returns
1263 >     * true if, upon return from this method, this task is guaranteed
1264 >     * to have completed normally. This method may return false
1265 >     * otherwise, to indicate that this task is not necessarily
1266 >     * complete (or is not known to be complete), for example in
1267       * asynchronous actions that require explicit invocations of
1268 <     * {@link #complete} to become joinable. It may also throw an
1269 <     * (unchecked) exception to indicate abnormal exit.
1268 >     * completion methods. This method may also throw an (unchecked)
1269 >     * exception to indicate abnormal exit. This method is designed to
1270 >     * support extensions, and should not in general be called
1271 >     * otherwise.
1272       *
1273 <     * @return {@code true} if completed normally
1273 >     * @return {@code true} if this task is known to have completed normally
1274       */
1275      protected abstract boolean exec();
1276  
# Line 1302 | Line 1339 | public abstract class ForkJoinTask<V> im
1339          return wt.pool.nextTaskFor(wt.workQueue);
1340      }
1341  
1342 <    // Mark-bit operations
1342 >    // tag operations
1343  
1344      /**
1345 <     * Returns true if this task is marked.
1345 >     * Returns the tag for this task.
1346       *
1347 <     * @return true if this task is marked
1347 >     * @return the tag for this task
1348       * @since 1.8
1349       */
1350 <    public final boolean isMarkedForkJoinTask() {
1351 <        return (status & MARKED) != 0;
1350 >    public final short getForkJoinTaskTag() {
1351 >        return (short)status;
1352      }
1353  
1354      /**
1355 <     * Atomically sets the mark on this task.
1355 >     * Atomically sets the tag value for this task.
1356       *
1357 <     * @return true if this task was previously unmarked
1357 >     * @param tag the tag value
1358 >     * @return the previous value of the tag
1359       * @since 1.8
1360       */
1361 <    public final boolean markForkJoinTask() {
1361 >    public final short setForkJoinTaskTag(short tag) {
1362          for (int s;;) {
1363 <            if (((s = status) & MARKED) != 0)
1364 <                return false;
1365 <            if (U.compareAndSwapInt(this, STATUS, s, s | MARKED))
1328 <                return true;
1363 >            if (U.compareAndSwapInt(this, STATUS, s = status,
1364 >                                    (s & ~SMASK) | (tag & SMASK)))
1365 >                return (short)s;
1366          }
1367      }
1368  
1369      /**
1370 <     * Atomically clears the mark on this task.
1370 >     * Atomically conditionally sets the tag value for this task.
1371 >     * Among other applications, tags can be used as visit markers
1372 >     * in tasks operating on graphs, as in methods that check: {@code
1373 >     * if (task.compareAndSetForkJoinTaskTag((short)0, (short)1))}
1374 >     * before processing, otherwise exiting because the node has
1375 >     * already been visited.
1376       *
1377 <     * @return true if this task was previously marked
1377 >     * @param e the expected tag value
1378 >     * @param tag the new tag value
1379 >     * @return true if successful; i.e., the current value was
1380 >     * equal to e and is now tag.
1381       * @since 1.8
1382       */
1383 <    public final boolean unmarkForkJoinTask() {
1383 >    public final boolean compareAndSetForkJoinTaskTag(short e, short tag) {
1384          for (int s;;) {
1385 <            if (((s = status) & MARKED) == 0)
1385 >            if ((short)(s = status) != e)
1386                  return false;
1387 <            if (U.compareAndSwapInt(this, STATUS, s, s & ~MARKED))
1387 >            if (U.compareAndSwapInt(this, STATUS, s,
1388 >                                    (s & ~SMASK) | (tag & SMASK)))
1389                  return true;
1390          }
1391      }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines