Runs a continuation when a task completes successfully, forwarding along
{@link java.lang.Exception}s or cancellation.
497856
public <TContinuationResult> Task<TContinuationResult> onSuccessTask(
      final Continuation<TResult, Task<TContinuationResult>> continuation,
      CancellationToken ct) {
    return onSuccessTask(continuation, IMMEDIATE_EXECUTOR, ct);
  }
120004
public <T> T execute(Task<T> task) {
        synchronized(task) {
            task.reset();
            // add it to the tail
            taskList.add(task);

            // invoke the execution
            lock.activate();

            // wait for the completion
            try {
            	while (!task.isDone()) {
            		task.wait();
            	}
            } catch (InterruptedException e) {
                task.exception = e; // we got interrupted, so task.result will be invalid! 
            }

            if(task.exception!=null) {
                Throwable e = task.exception;
                task.exception = null;
                throw new ExecutionException(e);
            } else {
                T r = task.result;
                task.result = null;
                return r;
            }
        }
    }
878203
@Override
	public CompletableFuture<Void> onStop() {
		log.info("Stopping TaskExecutor {}.", getAddress());

		Throwable throwable = null;

		if (resourceManagerConnection != null) {
			resourceManagerConnection.close();
		}

		for (JobManagerConnection jobManagerConnection : jobManagerConnections.values()) {
			try {
				disassociateFromJobManager(jobManagerConnection, new FlinkException("The TaskExecutor is shutting down."));
			} catch (Throwable t) {
				throwable = ExceptionUtils.firstOrSuppressed(t, throwable);
			}
		}

		jobManagerHeartbeatManager.stop();

		resourceManagerHeartbeatManager.stop();

		try {
			stopTaskExecutorServices();
		} catch (Exception e) {
			throwable = ExceptionUtils.firstOrSuppressed(e, throwable);
		}

		if (throwable != null) {
			return FutureUtils.completedExceptionally(new FlinkException("Error while shutting the TaskExecutor down.", throwable));
		} else {
			log.info("Stopped TaskExecutor {}.", getAddress());
			return CompletableFuture.completedFuture(null);
		}
	}
758932
public Task<Void> continueWhile(Callable<Boolean> predicate,
      Continuation<Void, Task<Void>> continuation) {
    return continueWhile(predicate, continuation, IMMEDIATE_EXECUTOR, null);
  }
1106193
protected synchronized void postTaskExecution() {
		if (stopped) {
			// Stopped, so don't count the task(s) as done.
			// (worker threads call this method even if the task was not really executed.)
			return;
		}
		tasksDoneCount++;
		int percentageComplete = tasksDoneCount * 100 / tasksTotalCount;

		// Compute the progress and notify the listeners
		this.notifyListenersSpiderProgress(percentageComplete, tasksDoneCount, tasksTotalCount - tasksDoneCount);

		// Check for ending conditions
		if (tasksDoneCount == tasksTotalCount && initialized) {
			this.complete();
		}
	}
962749
public void doRecovery() {

//        Attempts to stop all actively executing tasks, halts the
//        processing of waiting tasks, and returns a list of the tasks
//        that were awaiting execution.
//
//        This method does not wait for actively executing tasks to
//        terminate.
//
//        There are no guarantees beyond best-effort attempts to stop
//        processing actively executing tasks.  For example, typical
//        implementations will cancel via {@link Thread#interrupt}, so any
//        task that fails to respond to interrupts may never terminate.
        try {
            synchronized (this) {
                executorService.shutdownNow(); //shutting down current running threads
                threadPoolVersion++;           //updating the thread pool version to a new one - so current running threads will exit
                logger.warn(
                        "Worker is in doRecovery(). Cleaning state and cancelling running tasks. It may take up to 30 seconds...");
            }

            boolean finished = executorService.awaitTermination(30, TimeUnit.SECONDS);

            if (finished) {
                logger.warn("Worker succeeded to cancel running tasks during doRecovery().");
            } else {
                logger.warn("Not all running tasks responded to cancel.");
            }
        } catch (InterruptedException ex) {/*ignore*/}

        mapOfRunningTasks.clear();

        //Make new executor
        executorService = new ThreadPoolExecutor(numberOfThreads,
                numberOfThreads,
                Long.MAX_VALUE, TimeUnit.NANOSECONDS,
                inBuffer,
                new WorkerThreadFactory((threadPoolVersion) + "_WorkerExecutionThread"));
    }
453007
public Result proceed() throws Exception {
        if (iterator == null) {
            iterator = chain.listIterator();
        }
        if (!iterator.hasNext()) {
            throw new IllegalStateException("Reached the end of the chain without result.");
        }
        Filter filter = iterator.next();
        return filter.call(route, this);
    }
582761
public Task<Void> continueWhile(final Callable<Boolean> predicate,
      final Continuation<Void, Task<Void>> continuation, final Executor executor,
      final CancellationToken ct) {
    final Capture<Continuation<Void, Task<Void>>> predicateContinuation =
        new Capture<>();
    predicateContinuation.set(new Continuation<Void, Task<Void>>() {
      @Override
      public Task<Void> then(Task<Void> task) throws Exception {
        if (ct != null && ct.isCancellationRequested()) {
          return Task.cancelled();
        }

        if (predicate.call()) {
          return Task.<Void> forResult(null).onSuccessTask(continuation, executor)
              .onSuccessTask(predicateContinuation.get(), executor);
        }
        return Task.forResult(null);
      }
    });
    return makeVoid().continueWithTask(predicateContinuation.get(), executor);
  }
1055515
static ContinuableFuture<Void> execute(final Try.Runnable<? extends Exception> action) {
        return execute(new FutureTask<Void>(FN.toCallable(action)), SERIAL_EXECUTOR);
    }
1144555
@Override
  public void run(BiConsumer<OngoingRequest, RuleMatch<Endpoint>> matchContinuation) {
    try {
      matchAndRun(matchContinuation);
    } catch (Exception e) {
      LOG.error("Exception when handling request", e);
      // ensure that we reply with a server error, if possible
      ongoingRequest.reply(forStatus(INTERNAL_SERVER_ERROR));
    }
  }
1137428
private void continueExecution() {
        //increment task index
        i++;
        
        //submit next if the end of the chain not reached yet
        if (i < task.length && task[i] != null) {
        	scheduler.submit(task[i]);            
        } else if (listener != null) {
            listener.onTermination();
        }
    }
297712
@UnstableApi
    public final void executeAfterEventLoopIteration(Runnable task) {
        ObjectUtil.checkNotNull(task, "task");
        if (isShutdown()) {
            reject();
        }

        if (!tailTasks.offer(task)) {
            reject(task);
        }

        if (wakesUpForTask(task)) {
            wakeup(inEventLoop());
        }
    }
470619
public void waitForTasks() throws IOException {
    // Wait for all submitted tasks to complete
    boolean wasInterrupted = false;
    IOException exception = null;
    for (NamedFuture future : this.futures) {
      try {
        if (wasInterrupted) {
          future.getFuture().cancel(true);
        } else {
          future.getFuture().get();
        }
      } catch (InterruptedException ie) {
        LOGGER.warn("Task was interrupted: " + future.getName());
        wasInterrupted = true;
        if (exception == null) {
          exception = new IOException(ie);
        }
      } catch (ExecutionException ee) {
        LOGGER.warn("Task failed: " + future.getName(), ee.getCause());
        if (exception == null) {
          exception = new IOException(ee.getCause());
        }
      }
    }
    if (wasInterrupted) {
      Thread.currentThread().interrupt();
    }
    if (exception != null && this.failPolicy == FailPolicy.FAIL_ONE_FAIL_ALL) {
      throw exception;
    }

    // clear so that more tasks can be submitted to this ParallelRunner
    futures.clear();
  }
284600
public void run() throws Exception {
    try {

      CountDownLatch countDownLatch = new CountDownLatch(this.tasks);
      for (int i = 0; i < this.tasks; i++) {
        addTask(i, countDownLatch);
      }
      // Wait for the tasks to finish
      countDownLatch.await();
    } finally {
      try {
        // Calling close() will stop metric reporting
        this.context.close();
      } finally {
        this.executor.shutdownNow();
      }
    }
  }
438026
def check_complete(task, out_queue):
    
    logger.debug("Checking if %s is complete", task)
    try:
        is_complete = task.complete()
    except Exception:
        is_complete = TracebackWrapper(traceback.format_exc())
    out_queue.put((task, is_complete))
603661
@Override
    public void afterExecute(final Runnable runnable, final Throwable throwable) {
        super.afterExecute(runnable, throwable);
        if (throwable != null) {
            // Wrap the throwable in an ExecutionException (execute() does not do this)
            interruptionChecker.setExecutionException(new ExecutionException("Uncaught exception", throwable));
            // execute() was called and an uncaught exception or error was thrown
            interruptionChecker.interrupt();
        } else if (/* throwable == null && */ runnable instanceof Future<?>) {
            // submit() was called, so throwable is not set 
            try {
                // This call will not block, since execution has finished
                ((Future<?>) runnable).get();
            } catch (CancellationException | InterruptedException e) {
                // If this thread was cancelled or interrupted, interrupt other threads
                interruptionChecker.interrupt();
            } catch (final ExecutionException e) {
                // Record the exception that was thrown by the thread
                interruptionChecker.setExecutionException(e);
                // Interrupt other threads
                interruptionChecker.interrupt();
            }
        }
    }
1168245
@Override
    protected void afterExecute(Runnable r, Throwable t) {
        super.afterExecute(r, t);
        if (t == null && r instanceof Future<?>) {
            try {
                ((Future<?>) r).get();
            } catch (CancellationException ce) {
                t = ce;
            } catch (ExecutionException ee) {
                t = ee.getCause();
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt(); // ignore/reset
            }
        }
        if (t != null) {
            ARouter.logger.warning(Consts.TAG, "Running task appeared exception! Thread [" + Thread.currentThread().getName() + "], because [" + t.getMessage() + "]\n" + TextUtils.formatStackTrace(t.getStackTrace()));
        }
    }