CompletableFuture упрощенный пользовательский пример - PullRequest
0 голосов
/ 23 ноября 2018

Может ли кто-нибудь объяснить первоисточник CompletableFuture простыми способами?В частности, что происходит в timedGet (длинные нанос)?Это ссылка на исходный код https://github.com/frohoff/jdk8u-jdk/blob/master/src/share/classes/java/util/concurrent/CompletableFuture.java

Как CompletableFuture следит за выполнением потока и истекает время ожидания?

1 Ответ

0 голосов
/ 23 ноября 2018

Я не возьму на себя объяснение всего CompletableFuture, поскольку он имеет длину около 2 КБ, но я определенно могу объяснить 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;
       }
   }
}
...