This method should be used instead of {@link #delayedValue(CompletionStage, Object)} when a
{@link InvocationFinallyFunction} is used to properly handle the exception if any is present.
@param stage
@param syncValue
@param throwable
@return
778841
public static Object delayedValue(CompletionStage<Void> stage, Object syncValue, Throwable throwable) {
      if (throwable == null) {
         return delayedValue(stage, syncValue);
      }
      if (stage != null) {
         CompletableFuture<?> future = stage.toCompletableFuture();
         if (!future.isDone() || future.isCompletedExceptionally()) {
            return asyncValue(
                  stage.handle((ignore, t) -> {
                     if (t != null) {
                        throwable.addSuppressed(t);
                     }
                     return null;
                  }).thenCompose(ignore -> CompletableFutures.completedExceptionFuture(throwable))
            );
         }
      }
      return new SimpleAsyncInvocationStage(throwable);
   }
393668
@Override
	public CompletableFuture<Acknowledge> triggerCheckpoint(
			ExecutionAttemptID executionAttemptID,
			long checkpointId,
			long checkpointTimestamp,
			CheckpointOptions checkpointOptions,
			boolean advanceToEndOfEventTime) {
		log.debug("Trigger checkpoint {}@{} for {}.", checkpointId, checkpointTimestamp, executionAttemptID);

		final CheckpointType checkpointType = checkpointOptions.getCheckpointType();
		if (advanceToEndOfEventTime && !(checkpointType.isSynchronous() && checkpointType.isSavepoint())) {
			throw new IllegalArgumentException("Only synchronous savepoints are allowed to advance the watermark to MAX.");
		}

		final Task task = taskSlotTable.getTask(executionAttemptID);

		if (task != null) {
			task.triggerCheckpointBarrier(checkpointId, checkpointTimestamp, checkpointOptions, advanceToEndOfEventTime);

			return CompletableFuture.completedFuture(Acknowledge.get());
		} else {
			final String message = "TaskManager received a checkpoint request for unknown task " + executionAttemptID + '.';

			log.debug(message);
			return FutureUtils.completedExceptionally(new CheckpointException(message));
		}
	}
749262
static ContinuableFuture<Void> executeOnUiThread(final Try.Runnable<? extends Exception> action, final long delay) {
        return execute(new FutureTask<Void>(FN.toCallable(action)), _UI_EXECUTOR, delay);
    }
584480
private <R, U> CompletionStage<U> doApplyToEitherAsync(
            CompletionStage<? extends R> first,
            CompletionStage<? extends R> second,
            Function<? super R, U> fn,
            Executor executor) {
    	CompletableCompletionStage<R> nextStage = newCompletableCompletionStage();

        // only the first result is accepted by completion stage,
        // the other one is ignored
        BiConsumer<R, Throwable> action = completeHandler(nextStage);
        first.whenComplete(action);
        second.whenComplete(action);

        return nextStage.thenApplyAsync(fn, executor);
    }
1073044
@Override
    public final synchronized void beforeCompletion()
                    throws RemoteException
    {
        final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
        if (isTraceOn && tc.isEntryEnabled())
            Tr.entry(tc, "beforeCompletion: " + StateStrs[state]);

        if (removed) {
            if (isTraceOn && tc.isEntryEnabled())
                Tr.exit(tc, "beforeCompletion: removed");
            return;
        }

        switch (state)
        {
        // These are the "normal" commit points
            case TX_METHOD_READY:

                setState(COMMITTING_OUTSIDE_METHOD);

                // Session Synchronization BeforeCompletion needs to be called if either
                // the annotation (or XML) was specified or the bean implemented
                // the interface and a global transaction is active.        F743-25855
                if (ivBeforeCompletion != null || sessionSync != null)
                {
                    ContainerTx tx = container.getActiveContainerTx();

                    // SessionSynchronization beforeCompletion is only called for
                    // global transactions that are NOT being rolledback... and
                    // it is skipped if a remove method (@Remove) was called.    390657
                    if ((tx != null) &&
                        (tx.isTransactionGlobal()) &&
                        (!tx.getRollbackOnly()) &&
                        (tx.ivRemoveBeanO != this)) // 390657
                    {
                        EJBThreadData threadData = EJSContainer.getThreadData();

                        threadData.pushContexts(this);
                        try
                        {
                            if (ivBeforeCompletion != null) {
                                invokeSessionSynchMethod(ivBeforeCompletion, null);
                            } else {
                                sessionSync.beforeCompletion();
                            }
                        } finally
                        {
                            threadData.popContexts();
                        }
                    }
                }

                break;

            // Could happen during async rollback (i.e. a second thread is
            // rolling back the tran, as the current thread is committing it.
            case IN_METHOD:
            case METHOD_READY:
            case AFTER_COMPLETION: // d159152
            case DESTROYED:
                if (isTraceOn && tc.isEntryEnabled())
                    Tr.exit(tc, "beforeCompletion: asynch rollback: " + getStateName(state));
                return;

            default:

                throw new InvalidBeanOStateException(getStateName(state),
                                "TX_METHOD_READY | TX_IN_METHOD | " +
                                                "METHOD_READY | DESTROYED");

        }

        if (isTraceOn && tc.isEntryEnabled())
            Tr.exit(tc, "beforeCompletion: " + getStateName(state));
    }
1247734
private CompletableFuture<Void> completeCache(ByteString cacheName) throws Throwable {
      TxState state = globalTxTable.getState(new CacheXid(cacheName, xid));
      HotRodServer.CacheInfo cacheInfo =
         server.getCacheInfo(cacheName.toString(), header.getVersion(), header.getMessageId(), true);
      AdvancedCache<?, ?> cache = server.cache(cacheInfo, header, subject);
      RpcManager rpcManager = cache.getRpcManager();
      if (rpcManager == null || rpcManager.getAddress().equals(state.getOriginator())) {
         if (isTraceEnabled()) {
            log().tracef("[%s] Completing local executed transaction.", xid);
         }
         return asyncCompleteLocalTransaction(cache, state.getTimeout());
      } else if (rpcManager.getMembers().contains(state.getOriginator())) {
         if (isTraceEnabled()) {
            log().tracef("[%s] Forward remotely executed transaction to %s.", xid, state.getOriginator());
         }
         return forwardCompleteCommand(cacheName, rpcManager, state);
      } else {
         if (isTraceEnabled()) {
            log().tracef("[%s] Originator, %s, left the cluster.", xid, state.getOriginator());
         }
         return completeWithRemoteCommand(cache, rpcManager, state);
      }
   }
358467
public void deliverAsyncException(Throwable e)
   {
      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "deliverAsyncException", e);

      if (proxyQueue != null)
      {
         proxyQueue.deliverException(e);
      }
      else
      {
         if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "** Odd - we are not async?!");
      }

      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "deliverAsyncException");
   }
865101
public <T extends Throwable> T throwing(Level level, T throwable) {
        if (instanceofLAL) {
            ((LocationAwareLogger) logger).log(THROWING_MARKER, FQCN, level.level, "throwing", null, throwable);
        }
        return throwable;
    }
1081391
public void throwValue(Local<? extends Throwable> toThrow) {
        addInstruction(new ThrowingInsn(Rops.THROW, sourcePosition,
                RegisterSpecList.make(toThrow.spec()), catches));
    }
672214
public static void afterCompletion(TransactionImpl tran, int status, int syncLevel) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.entry(tc, "afterCompletion", new Object[] { tran, status, syncLevel });

        if (syncLevel >= 0) {
            final ArrayList syncs = _syncLevels.get(syncLevel);

            if (syncs != null) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                    Tr.debug(tc, "syncs.length=" + syncs.size());

                final int localID = (int) tran.getLocalTID();
                final byte[] globalID = tran.getTID();
                // d281425 - status maybe committed, unknown or rolledback
                final boolean committed = !(status == Status.STATUS_ROLLEDBACK); // @281425C
                final int numSyncs = syncs.size();

                for (int s = 0; s < numSyncs; s++) {
                    try {
                        ((SynchronizationCallback) syncs.get(s)).afterCompletion(localID, globalID, committed);
                    } catch (Throwable t) {
                        // No FFDC needed
                        Tr.error(tc, "WTRN0074_SYNCHRONIZATION_EXCEPTION", new Object[] { "afterCompletion", syncs.get(s), t });
                        // absorb and allow other afterCompletions to run.
                    }
                }
            } else if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                Tr.debug(tc, "syncs is null");
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.exit(tc, "afterCompletion");
    }
1226344
public synchronized boolean waitForFinish() throws Throwable {
    while (!done && exception == null) {
      wait();
    }
    if (exception != null) {
      throw exception;
    }
    return done;
  }
1291835
@GwtIncompatible static <T> T invokeAnyImpl(
      ListeningExecutorService executorService,
      Collection<? extends Callable<T>> tasks,
      boolean timed,
      long timeout,
      TimeUnit unit)
      throws InterruptedException, ExecutionException, TimeoutException {
    checkNotNull(executorService);
    checkNotNull(unit);
    int ntasks = tasks.size();
    checkArgument(ntasks > 0);
    List<Future<T>> futures = Lists.newArrayListWithCapacity(ntasks);
    BlockingQueue<Future<T>> futureQueue = Queues.newLinkedBlockingQueue();
    long timeoutNanos = unit.toNanos(timeout);

    // For efficiency, especially in executors with limited
    // parallelism, check to see if previously submitted tasks are
    // done before submitting more of them. This interleaving
    // plus the exception mechanics account for messiness of main
    // loop.

    try {
      // Record exceptions so that if we fail to obtain any
      // result, we can throw the last exception we got.
      ExecutionException ee = null;
      long lastTime = timed ? System.nanoTime() : 0;
      Iterator<? extends Callable<T>> it = tasks.iterator();

      futures.add(submitAndAddQueueListener(executorService, it.next(), futureQueue));
      --ntasks;
      int active = 1;

      while (true) {
        Future<T> f = futureQueue.poll();
        if (f == null) {
          if (ntasks > 0) {
            --ntasks;
            futures.add(submitAndAddQueueListener(executorService, it.next(), futureQueue));
            ++active;
          } else if (active == 0) {
            break;
          } else if (timed) {
            f = futureQueue.poll(timeoutNanos, TimeUnit.NANOSECONDS);
            if (f == null) {
              throw new TimeoutException();
            }
            long now = System.nanoTime();
            timeoutNanos -= now - lastTime;
            lastTime = now;
          } else {
            f = futureQueue.take();
          }
        }
        if (f != null) {
          --active;
          try {
            return f.get();
          } catch (ExecutionException eex) {
            ee = eex;
          } catch (RuntimeException rex) {
            ee = new ExecutionException(rex);
          }
        }
      }

      if (ee == null) {
        ee = new ExecutionException(null);
      }
      throw ee;
    } finally {
      for (Future<T> f : futures) {
        f.cancel(true);
      }
    }
  }
123177
public static Throwable getFailed(CompletionStage<?> stage) {
    CompletableFuture<?> future = stage.toCompletableFuture();
    Preconditions.checkArgument(future.isCompletedExceptionally());
    try {
      future.get();
      throw new AssertionError("future should be failed");
    } catch (InterruptedException e) {
      throw new AssertionError("Unexpected error", e);
    } catch (ExecutionException e) {
      return e.getCause();
    }
  }
676938
private static Object getFutureValue(ListenableFuture<?> future) {
    Object valueToSet;
    if (future instanceof TrustedFuture) {
      // Break encapsulation for TrustedFuture instances since we know that subclasses cannot
      // override .get() (since it is final) and therefore this is equivalent to calling .get()
      // and unpacking the exceptions like we do below (just much faster because it is a single
      // field read instead of a read, several branches and possibly creating exceptions).
      return ((AbstractFuture<?>) future).value;
    } else {
      // Otherwise calculate valueToSet by calling .get()
      try {
        Object v = getDone(future);
        valueToSet = v == null ? NULL : v;
      } catch (ExecutionException exception) {
        valueToSet = new Failure(exception.getCause());
      } catch (CancellationException cancellation) {
        valueToSet = new Cancellation(false, cancellation);
      } catch (Throwable t) {
        valueToSet = new Failure(t);
      }
    }
    return valueToSet;
  }
1231869
public static void invokeOnError(AsyncMethodCallback<?> callback, Throwable cause) {
        requireNonNull(callback, "callback");
        requireNonNull(cause, "cause");
        if (cause instanceof Exception) {
            callback.onError((Exception) cause);
        } else {
            callback.onError(new CompletionException(cause.toString(), cause));
        }
    }
896604
@Override
	public CompletableFuture<?> releaseSlot(@Nullable Throwable cause) {
		if (!isCanceled()) {
			final CompletableFuture<?> terminationFuture;

			if (payload != null) {
				// trigger the failure of the slot payload
				payload.fail(cause != null ? cause : new FlinkException("TaskManager was lost/killed: " + getTaskManagerLocation()));

				// wait for the termination of the payload before releasing the slot
				terminationFuture = payload.getTerminalStateFuture();
			} else {
				terminationFuture = CompletableFuture.completedFuture(null);
			}

			terminationFuture.whenComplete(
				(Object ignored, Throwable throwable) -> {
					// release directly (if we are directly allocated),
					// otherwise release through the parent shared slot
					if (getParent() == null) {
						// we have to give back the slot to the owning instance
						if (markCancelled()) {
							try {
								getOwner().returnLogicalSlot(this);
								releaseFuture.complete(null);
							} catch (Exception e) {
								releaseFuture.completeExceptionally(e);
							}
						}
					} else {
						// we have to ask our parent to dispose us
						getParent().releaseChild(this);

						releaseFuture.complete(null);
					}
				});
		}

		return releaseFuture;
	}
1322053
public ISynchronizationPoint<Exception> closeElement(ElementContext ctx) {
		ISynchronizationPoint<Exception> next = next();
		do {
			if (!next.isUnblocked()) break;
			if (next.hasError()) return next;
			if (Type.END_ELEMENT.equals(event.type)) {
				if (event.context.getFirst() == ctx)
					return next;
			}
			next = next();
		} while (true);
		SynchronizationPoint<Exception> result = new SynchronizationPoint<>();
		ISynchronizationPoint<Exception> n = next;
		next.listenInline(() -> {
			if (!check(n, result)) return;
			if (Type.END_ELEMENT.equals(event.type)) {
				if (event.context.getFirst() == ctx) {
					result.unblock();
					return;
				}
			}
			new ParsingTask(() -> { closeElement(ctx).listenInline(result); }).start();
		}, result);
		return result;
	}