有人可以用简单的方式解释CompletableFuture的原始来源吗?特别是在timedGet(long nanos)中会发生什么?这是源代码链接https://github.com/frohoff/jdk8u-jdk/blob/master/src/share/classes/java/util/concurrent/CompletableFuture.java
CompletableFuture如何监视线程的执行并超时?
答案 0 :(得分:1)
我不会自己解释整个CompletableFuture,因为它大约有2K行,但是我绝对会解释timedGet()
请注意,我们在这里讨论的是OpenJDK,OracleJDK有点不同。
在肉部分之前进行一些检查,之后进行一些清理。我要离开他们。
long d = System.nanoTime() + nanos;
// Arguments are interruptible, nanos, deadline
Signaller q = new Signaller(true, nanos, d == 0L ? 1L : d); // avoid 0
boolean queued = false;
// We wait until we get the result
// If it's already there, we simply return it
while ((r = result) == null) {
// So, the result is not there
// If it's the first time we run this loop, or we didn't manage to push signaller on the stacked queued=false
if (!queued)
queued = tryPushStack(q);
// Something interrupted us. It could be either thread interrupt or timeout
else if (q.interruptControl < 0 || q.nanos <= 0L) {
q.thread = null;
cleanStack();
if (q.interruptControl < 0)
return null;
throw new TimeoutException();
}
else if (q.thread != null && result == null) {
try {
// Waits for q, without blocking the thread
ForkJoinPool.managedBlock(q);
} catch (InterruptedException ie) {
q.interruptControl = -1;
}
}
}