33 |
|
* <p>A "main" {@code ForkJoinTask} begins execution when it is |
34 |
|
* explicitly submitted to a {@link ForkJoinPool}, or, if not already |
35 |
|
* engaged in a ForkJoin computation, commenced in the {@link |
36 |
< |
* ForkJoinPool#commonPool} via {@link #fork}, {@link #invoke}, or |
36 |
> |
* ForkJoinPool#commonPool()} via {@link #fork}, {@link #invoke}, or |
37 |
|
* related methods. Once started, it will usually in turn start other |
38 |
|
* subtasks. As indicated by the name of this class, many programs |
39 |
|
* using {@code ForkJoinTask} employ only methods {@link #fork} and |
55 |
|
* minimize other blocking synchronization apart from joining other |
56 |
|
* tasks or using synchronizers such as Phasers that are advertised to |
57 |
|
* cooperate with fork/join scheduling. Subdividable tasks should also |
58 |
< |
* not perform blocking IO, and should ideally access variables that |
58 |
> |
* not perform blocking I/O, and should ideally access variables that |
59 |
|
* are completely independent of those accessed by other running |
60 |
|
* tasks. These guidelines are loosely enforced by not permitting |
61 |
|
* checked exceptions such as {@code IOExceptions} to be |
73 |
|
* <p>It is possible to define and use ForkJoinTasks that may block, |
74 |
|
* but doing do requires three further considerations: (1) Completion |
75 |
|
* of few if any <em>other</em> tasks should be dependent on a task |
76 |
< |
* that blocks on external synchronization or IO. Event-style async |
76 |
> |
* that blocks on external synchronization or I/O. Event-style async |
77 |
|
* tasks that are never joined (for example, those subclassing {@link |
78 |
|
* CountedCompleter}) often fall into this category. (2) To minimize |
79 |
|
* resource impact, tasks should be small; ideally performing only the |
134 |
|
* (DAG). Otherwise, executions may encounter a form of deadlock as |
135 |
|
* tasks cyclically wait for each other. However, this framework |
136 |
|
* supports other methods and techniques (for example the use of |
137 |
< |
* {@link Phaser}, {@link #helpQuiesce}, and {@link #complete}) that |
137 |
> |
* {@link java.util.concurrent.Phaser}, {@link #helpQuiesce}, and |
138 |
> |
* {@link #complete}) that |
139 |
|
* may be of use in constructing custom subclasses for problems that |
140 |
|
* are not statically structured as DAGs. To support such usages a |
141 |
|
* ForkJoinTask may be atomically <em>tagged</em> with a {@code short} |
286 |
|
*/ |
287 |
|
private int externalAwaitDone() { |
288 |
|
int s; |
289 |
+ |
ForkJoinPool.externalHelpJoin(this); |
290 |
|
boolean interrupted = false; |
291 |
< |
if ((s = status) >= 0 && ForkJoinPool.tryUnsubmitFromCommonPool(this)) |
290 |
< |
s = doExec(); |
291 |
< |
while (s >= 0) { |
291 |
> |
while ((s = status) >= 0) { |
292 |
|
if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) { |
293 |
|
synchronized (this) { |
294 |
|
if (status >= 0) { |
302 |
|
notifyAll(); |
303 |
|
} |
304 |
|
} |
305 |
– |
s = status; |
305 |
|
} |
306 |
|
if (interrupted) |
307 |
|
Thread.currentThread().interrupt(); |
312 |
|
* Blocks a non-worker-thread until completion or interruption. |
313 |
|
*/ |
314 |
|
private int externalInterruptibleAwaitDone() throws InterruptedException { |
315 |
+ |
int s; |
316 |
|
if (Thread.interrupted()) |
317 |
|
throw new InterruptedException(); |
318 |
< |
int s; |
319 |
< |
if ((s = status) >= 0 && ForkJoinPool.tryUnsubmitFromCommonPool(this)) |
320 |
< |
s = doExec(); |
321 |
< |
while (s >= 0) { |
318 |
> |
ForkJoinPool.externalHelpJoin(this); |
319 |
> |
while ((s = status) >= 0) { |
320 |
|
if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) { |
321 |
|
synchronized (this) { |
322 |
|
if (status >= 0) |
325 |
|
notifyAll(); |
326 |
|
} |
327 |
|
} |
330 |
– |
s = status; |
328 |
|
} |
329 |
|
return s; |
330 |
|
} |
331 |
|
|
332 |
+ |
|
333 |
|
/** |
334 |
|
* Implementation for join, get, quietlyJoin. Directly handles |
335 |
|
* only cases of already-completed, external wait, and |
436 |
|
} |
437 |
|
|
438 |
|
/** |
439 |
< |
* Records exception and possibly propagates |
439 |
> |
* Records exception and possibly propagates. |
440 |
|
* |
441 |
|
* @return status on exit |
442 |
|
*/ |
599 |
|
} |
600 |
|
|
601 |
|
/** |
602 |
+ |
* A version of "sneaky throw" to relay exceptions |
603 |
+ |
*/ |
604 |
+ |
static void rethrow(final Throwable ex) { |
605 |
+ |
if (ex != null) { |
606 |
+ |
if (ex instanceof Error) |
607 |
+ |
throw (Error)ex; |
608 |
+ |
if (ex instanceof RuntimeException) |
609 |
+ |
throw (RuntimeException)ex; |
610 |
+ |
ForkJoinTask.<RuntimeException>uncheckedThrow(ex); |
611 |
+ |
} |
612 |
+ |
} |
613 |
+ |
|
614 |
+ |
/** |
615 |
+ |
* The sneaky part of sneaky throw, relying on generics |
616 |
+ |
* limitations to evade compiler complaints about rethrowing |
617 |
+ |
* unchecked exceptions |
618 |
+ |
*/ |
619 |
+ |
@SuppressWarnings("unchecked") static <T extends Throwable> |
620 |
+ |
void uncheckedThrow(Throwable t) throws T { |
621 |
+ |
if (t != null) |
622 |
+ |
throw (T)t; // rely on vacuous cast |
623 |
+ |
} |
624 |
+ |
|
625 |
+ |
/** |
626 |
|
* Throws exception, if any, associated with the given status. |
627 |
|
*/ |
628 |
|
private void reportException(int s) { |
629 |
< |
Throwable ex = ((s == CANCELLED) ? new CancellationException() : |
630 |
< |
(s == EXCEPTIONAL) ? getThrowableException() : |
631 |
< |
null); |
632 |
< |
if (ex != null) |
611 |
< |
U.throwException(ex); |
629 |
> |
if (s == CANCELLED) |
630 |
> |
throw new CancellationException(); |
631 |
> |
if (s == EXCEPTIONAL) |
632 |
> |
rethrow(getThrowableException()); |
633 |
|
} |
634 |
|
|
635 |
|
// public methods |
637 |
|
/** |
638 |
|
* Arranges to asynchronously execute this task in the pool the |
639 |
|
* current task is running in, if applicable, or using the {@link |
640 |
< |
* ForkJoinPool#commonPool} if not {@link #inForkJoinPool}. While |
640 |
> |
* ForkJoinPool#commonPool()} if not {@link #inForkJoinPool}. While |
641 |
|
* it is not necessarily enforced, it is a usage error to fork a |
642 |
|
* task more than once unless it has completed and been |
643 |
|
* reinitialized. Subsequent modifications to the state of this |
654 |
|
if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) |
655 |
|
((ForkJoinWorkerThread)t).workQueue.push(this); |
656 |
|
else |
657 |
< |
ForkJoinPool.submitToCommonPool(this); |
657 |
> |
ForkJoinPool.common.externalPush(this); |
658 |
|
return this; |
659 |
|
} |
660 |
|
|
756 |
|
} |
757 |
|
} |
758 |
|
if (ex != null) |
759 |
< |
U.throwException(ex); |
759 |
> |
rethrow(ex); |
760 |
|
} |
761 |
|
|
762 |
|
/** |
807 |
|
} |
808 |
|
} |
809 |
|
if (ex != null) |
810 |
< |
U.throwException(ex); |
810 |
> |
rethrow(ex); |
811 |
|
return tasks; |
812 |
|
} |
813 |
|
|
980 |
|
if (Thread.interrupted()) |
981 |
|
throw new InterruptedException(); |
982 |
|
// Messy in part because we measure in nanosecs, but wait in millisecs |
983 |
< |
int s; long ns, ms; |
984 |
< |
if ((s = status) >= 0 && (ns = unit.toNanos(timeout)) > 0L) { |
983 |
> |
int s; long ms; |
984 |
> |
long ns = unit.toNanos(timeout); |
985 |
> |
if ((s = status) >= 0 && ns > 0L) { |
986 |
|
long deadline = System.nanoTime() + ns; |
987 |
|
ForkJoinPool p = null; |
988 |
|
ForkJoinPool.WorkQueue w = null; |
991 |
|
ForkJoinWorkerThread wt = (ForkJoinWorkerThread)t; |
992 |
|
p = wt.pool; |
993 |
|
w = wt.workQueue; |
994 |
< |
s = p.helpJoinOnce(w, this); // no retries on failure |
994 |
> |
p.helpJoinOnce(w, this); // no retries on failure |
995 |
|
} |
996 |
+ |
else |
997 |
+ |
ForkJoinPool.externalHelpJoin(this); |
998 |
|
boolean canBlock = false; |
999 |
|
boolean interrupted = false; |
1000 |
|
try { |
1001 |
|
while ((s = status) >= 0) { |
1002 |
< |
if (w != null && w.runState < 0) |
1002 |
> |
if (w != null && w.qlock < 0) |
1003 |
|
cancelIgnoringExceptions(this); |
1004 |
|
else if (!canBlock) { |
1005 |
< |
if (p == null || p.tryCompensate(this, null)) |
1005 |
> |
if (p == null || p.tryCompensate()) |
1006 |
|
canBlock = true; |
1007 |
|
} |
1008 |
|
else { |
1078 |
|
wt.pool.helpQuiescePool(wt.workQueue); |
1079 |
|
} |
1080 |
|
else |
1081 |
< |
ForkJoinPool.externalHelpQuiescePool(); |
1081 |
> |
ForkJoinPool.quiesceCommonPool(); |
1082 |
|
} |
1083 |
|
|
1084 |
|
/** |
1141 |
|
*/ |
1142 |
|
public boolean tryUnfork() { |
1143 |
|
Thread t; |
1144 |
< |
return ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ? |
1145 |
< |
((ForkJoinWorkerThread)t).workQueue.tryUnpush(this) : |
1146 |
< |
ForkJoinPool.tryUnsubmitFromCommonPool(this); |
1144 |
> |
return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ? |
1145 |
> |
((ForkJoinWorkerThread)t).workQueue.tryUnpush(this) : |
1146 |
> |
ForkJoinPool.tryExternalUnpush(this)); |
1147 |
|
} |
1148 |
|
|
1149 |
|
/** |
1155 |
|
* @return the number of tasks |
1156 |
|
*/ |
1157 |
|
public static int getQueuedTaskCount() { |
1158 |
< |
Thread t; |
1159 |
< |
return ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ? |
1160 |
< |
((ForkJoinWorkerThread)t).workQueue.queueSize() : |
1161 |
< |
ForkJoinPool.getEstimatedSubmitterQueueLength(); |
1158 |
> |
Thread t; ForkJoinPool.WorkQueue q; |
1159 |
> |
if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) |
1160 |
> |
q = ((ForkJoinWorkerThread)t).workQueue; |
1161 |
> |
else |
1162 |
> |
q = ForkJoinPool.commonSubmitterQueue(); |
1163 |
> |
return (q == null) ? 0 : q.queueSize(); |
1164 |
|
} |
1165 |
|
|
1166 |
|
/** |
1177 |
|
* @return the surplus number of tasks, which may be negative |
1178 |
|
*/ |
1179 |
|
public static int getSurplusQueuedTaskCount() { |
1180 |
< |
/* |
1155 |
< |
* The aim of this method is to return a cheap heuristic guide |
1156 |
< |
* for task partitioning when programmers, frameworks, tools, |
1157 |
< |
* or languages have little or no idea about task granularity. |
1158 |
< |
* In essence by offering this method, we ask users only about |
1159 |
< |
* tradeoffs in overhead vs expected throughput and its |
1160 |
< |
* variance, rather than how finely to partition tasks. |
1161 |
< |
* |
1162 |
< |
* In a steady state strict (tree-structured) computation, |
1163 |
< |
* each thread makes available for stealing enough tasks for |
1164 |
< |
* other threads to remain active. Inductively, if all threads |
1165 |
< |
* play by the same rules, each thread should make available |
1166 |
< |
* only a constant number of tasks. |
1167 |
< |
* |
1168 |
< |
* The minimum useful constant is just 1. But using a value of |
1169 |
< |
* 1 would require immediate replenishment upon each steal to |
1170 |
< |
* maintain enough tasks, which is infeasible. Further, |
1171 |
< |
* partitionings/granularities of offered tasks should |
1172 |
< |
* minimize steal rates, which in general means that threads |
1173 |
< |
* nearer the top of computation tree should generate more |
1174 |
< |
* than those nearer the bottom. In perfect steady state, each |
1175 |
< |
* thread is at approximately the same level of computation |
1176 |
< |
* tree. However, producing extra tasks amortizes the |
1177 |
< |
* uncertainty of progress and diffusion assumptions. |
1178 |
< |
* |
1179 |
< |
* So, users will want to use values larger, but not much |
1180 |
< |
* larger than 1 to both smooth over transient shortages and |
1181 |
< |
* hedge against uneven progress; as traded off against the |
1182 |
< |
* cost of extra task overhead. We leave the user to pick a |
1183 |
< |
* threshold value to compare with the results of this call to |
1184 |
< |
* guide decisions, but recommend values such as 3. |
1185 |
< |
* |
1186 |
< |
* When all threads are active, it is on average OK to |
1187 |
< |
* estimate surplus strictly locally. In steady-state, if one |
1188 |
< |
* thread is maintaining say 2 surplus tasks, then so are |
1189 |
< |
* others. So we can just use estimated queue length. |
1190 |
< |
* However, this strategy alone leads to serious mis-estimates |
1191 |
< |
* in some non-steady-state conditions (ramp-up, ramp-down, |
1192 |
< |
* other stalls). We can detect many of these by further |
1193 |
< |
* considering the number of "idle" threads, that are known to |
1194 |
< |
* have zero queued tasks, so compensate by a factor of |
1195 |
< |
* (#idle/#active) threads. |
1196 |
< |
*/ |
1197 |
< |
Thread t; ForkJoinWorkerThread wt; |
1198 |
< |
return ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ? |
1199 |
< |
(wt = (ForkJoinWorkerThread)t).workQueue.queueSize() - wt.pool.idlePerActive() : |
1200 |
< |
0; |
1180 |
> |
return ForkJoinPool.getSurplusQueuedTaskCount(); |
1181 |
|
} |
1182 |
|
|
1183 |
|
// Extension methods |
1221 |
|
/** |
1222 |
|
* Returns, but does not unschedule or execute, a task queued by |
1223 |
|
* the current thread but not yet executed, if one is immediately |
1224 |
< |
* available and the current thread is operating in a |
1225 |
< |
* ForkJoinPool. There is no guarantee that this task will |
1226 |
< |
* actually be polled or executed next. Conversely, this method |
1227 |
< |
* may return null even if a task exists but cannot be accessed |
1248 |
< |
* without contention with other threads. This method is designed |
1224 |
> |
* available. There is no guarantee that this task will actually |
1225 |
> |
* be polled or executed next. Conversely, this method may return |
1226 |
> |
* null even if a task exists but cannot be accessed without |
1227 |
> |
* contention with other threads. This method is designed |
1228 |
|
* primarily to support extensions, and is unlikely to be useful |
1229 |
|
* otherwise. |
1230 |
|
* |
1231 |
|
* @return the next task, or {@code null} if none are available |
1232 |
|
*/ |
1233 |
|
protected static ForkJoinTask<?> peekNextLocalTask() { |
1234 |
< |
Thread t; |
1235 |
< |
return ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ? |
1236 |
< |
((ForkJoinWorkerThread)t).workQueue.peek() : |
1237 |
< |
null; |
1234 |
> |
Thread t; ForkJoinPool.WorkQueue q; |
1235 |
> |
if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) |
1236 |
> |
q = ((ForkJoinWorkerThread)t).workQueue; |
1237 |
> |
else |
1238 |
> |
q = ForkJoinPool.commonSubmitterQueue(); |
1239 |
> |
return (q == null) ? null : q.peek(); |
1240 |
|
} |
1241 |
|
|
1242 |
|
/** |
1461 |
|
// Unsafe mechanics |
1462 |
|
private static final sun.misc.Unsafe U; |
1463 |
|
private static final long STATUS; |
1464 |
+ |
|
1465 |
|
static { |
1466 |
|
exceptionTableLock = new ReentrantLock(); |
1467 |
|
exceptionTableRefQueue = new ReferenceQueue<Object>(); |
1468 |
|
exceptionTable = new ExceptionNode[EXCEPTION_MAP_CAPACITY]; |
1469 |
|
try { |
1470 |
|
U = getUnsafe(); |
1471 |
+ |
Class<?> k = ForkJoinTask.class; |
1472 |
|
STATUS = U.objectFieldOffset |
1473 |
< |
(ForkJoinTask.class.getDeclaredField("status")); |
1473 |
> |
(k.getDeclaredField("status")); |
1474 |
|
} catch (Exception e) { |
1475 |
|
throw new Error(e); |
1476 |
|
} |
1486 |
|
private static sun.misc.Unsafe getUnsafe() { |
1487 |
|
try { |
1488 |
|
return sun.misc.Unsafe.getUnsafe(); |
1489 |
< |
} catch (SecurityException se) { |
1490 |
< |
try { |
1491 |
< |
return java.security.AccessController.doPrivileged |
1492 |
< |
(new java.security |
1493 |
< |
.PrivilegedExceptionAction<sun.misc.Unsafe>() { |
1494 |
< |
public sun.misc.Unsafe run() throws Exception { |
1495 |
< |
java.lang.reflect.Field f = sun.misc |
1496 |
< |
.Unsafe.class.getDeclaredField("theUnsafe"); |
1497 |
< |
f.setAccessible(true); |
1498 |
< |
return (sun.misc.Unsafe) f.get(null); |
1499 |
< |
}}); |
1500 |
< |
} catch (java.security.PrivilegedActionException e) { |
1501 |
< |
throw new RuntimeException("Could not initialize intrinsics", |
1502 |
< |
e.getCause()); |
1503 |
< |
} |
1489 |
> |
} catch (SecurityException tryReflectionInstead) {} |
1490 |
> |
try { |
1491 |
> |
return java.security.AccessController.doPrivileged |
1492 |
> |
(new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() { |
1493 |
> |
public sun.misc.Unsafe run() throws Exception { |
1494 |
> |
Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class; |
1495 |
> |
for (java.lang.reflect.Field f : k.getDeclaredFields()) { |
1496 |
> |
f.setAccessible(true); |
1497 |
> |
Object x = f.get(null); |
1498 |
> |
if (k.isInstance(x)) |
1499 |
> |
return k.cast(x); |
1500 |
> |
} |
1501 |
> |
throw new NoSuchFieldError("the Unsafe"); |
1502 |
> |
}}); |
1503 |
> |
} catch (java.security.PrivilegedActionException e) { |
1504 |
> |
throw new RuntimeException("Could not initialize intrinsics", |
1505 |
> |
e.getCause()); |
1506 |
|
} |
1507 |
|
} |
1508 |
|
} |