Invokes the callable using the given executor, returning a Task to represent the operation.

If you want to cancel the resulting Task throw a {@link java.util.concurrent.CancellationException}
from the callable.
966102
public static <TResult> Task<TResult> call(final Callable<TResult> callable, Executor executor) {
    return call(callable, executor, null);
  }
723723
public void execute(T target) throws Throwable
    {
        try
        {
            for (Invokation invokation : queue)
            {
                invokation.invoke(target);
            }
        }
        catch (InvocationTargetException ex)
        {
            throw ex.getCause();
        }
        catch (ReflectiveOperationException ex)
        {
            throw new RuntimeException(ex);
        }
    }
553589
public V action(Callable<V> callable) throws Exception {
        Exception re;
        RetryState retryState = retryStrategy.getRetryState();
        do {
            try {
                return callable.call();
            } catch (Exception e) {
                re = e;
                if (Thread.interrupted() || isInterruptTransitively(e)) {
                    re = new InterruptedException(e.getMessage());
                    break;
                }
                if (!transientExceptionDetector.isTransient(e)) {
                    break;
                }
            }
            enqueueRetryEvent(new RetryEvent(this, retryState, re));
            retryState.delayRetry();
        } while (retryState.hasRetries());
        throw re;
    }
675253
private <T> T doInvokeAny(Collection<? extends Callable<T>> tasks,
                            boolean timed, long nanos)
        throws InterruptedException, ExecutionException, TimeoutException {
        if (tasks == null)
            throw new NullPointerException();
        int ntasks = tasks.size();
        if (ntasks == 0)
            throw new IllegalArgumentException();
        List<Future<T>> futures= new ArrayList<>(ntasks);
        CompletionService<T> ecs =
            new ExecutionCompletionService<>(this);

        // 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();

            // Start one task for sure; the rest incrementally
            futures.add(ecs.submit(it.next()));
            --ntasks;
            int active = 1;

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

            if (ee == null)
                ee = new ExecutionException() {
                    private static final long serialVersionUID = 200818694545553992L;
                };
            throw ee;

        } finally {
            for (Future<T> f : futures)
                f.cancel(true);
        }
    }
666974
public static <TResult> Task<TResult> callInBackground(Callable<TResult> callable) {
    return call(callable, BACKGROUND_EXECUTOR, null);
  }
883103
@SuppressWarnings("static-method")
	protected <T> Callable<T> createTask(Callable<T> callable) {
		if (callable instanceof JanusCallable<?>) {
			return callable;
		}
		return new JanusCallable<>(callable);
	}
920523
static <T> T runWithRetries(Callable<T> callable) {
    // Use same backoff setting as abort, somewhat arbitrarily.
    Span span = tracer.getCurrentSpan();
    ExponentialBackOff backOff = newBackOff();
    Context context = Context.current();
    int attempt = 0;
    while (true) {
      attempt++;
      try {
        span.addAnnotation(
            "Starting operation",
            ImmutableMap.of("Attempt", AttributeValue.longAttributeValue(attempt)));
        T result = callable.call();
        return result;
      } catch (SpannerException e) {
        if (!e.isRetryable()) {
          throw e;
        }
        logger.log(Level.FINE, "Retryable exception, will sleep and retry", e);
        long delay = e.getRetryDelayInMillis();
        if (delay != -1) {
          backoffSleep(context, delay);
        } else {
          backoffSleep(context, backOff);
        }
      } catch (Exception e) {
        Throwables.throwIfUnchecked(e);
        throw newSpannerException(ErrorCode.INTERNAL, "Unexpected exception thrown", e);
      }
    }
  }
1246594
public<V> Future<V> submit(Callable<V> task)
    {
        Preconditions.checkState(isOpen.get(), "CloseableExecutorService is closed");

        InternalFutureTask<V> futureTask = new InternalFutureTask<V>(new FutureTask<V>(task));
        executorService.execute(futureTask);
        return futureTask;
    }
814207
public void start() throws Throwable
   {
      if (!isExternal)
      {
         executorService = Executors.newSingleThreadExecutor(new IdleThreadFactory());
      }

      shutdown.set(false);
      interval = Long.MAX_VALUE;
      next = Long.MAX_VALUE;

      executorService.execute(new IdleConnectionRemoverRunner());
   }
109461
private void executeTasklet(final ExecutorService commandExecutor,
                              final ConcurrentMap<Integer, Future> futures,
                              final MasterToWorkerRequest masterToWorkerRequest) {
    final CountDownLatch latch = new CountDownLatch(1);
    final TaskletExecutionRequest taskletExecutionRequest = (TaskletExecutionRequest) masterToWorkerRequest;

    // Scheduler Thread: Pass the command to the worker thread pool to be executed
    // Record future to support cancellation.
    futures.put(
        taskletExecutionRequest.getTaskletId(),
        commandExecutor.submit(new Runnable() {
          @Override
          public void run() {
            final WorkerToMasterReports reports;
            final List<WorkerToMasterReport> holder = new ArrayList<>();

            try {
              // Command Executor: Execute the command
              final WorkerToMasterReport workerToMasterReport =
                  new TaskletResultReport(taskletExecutionRequest.getTaskletId(), taskletExecutionRequest.execute());
              holder.add(workerToMasterReport);
            } catch (final InterruptedException ex) {
              // Assumes that user's thread follows convention that cancelled Futures
              // should throw InterruptedException.
              final WorkerToMasterReport workerToMasterReport =
                  new TaskletCancelledReport(taskletExecutionRequest.getTaskletId());
              LOG.log(Level.WARNING, "Tasklet with ID {0} has been cancelled", taskletExecutionRequest.getTaskletId());
              holder.add(workerToMasterReport);
            } catch (Exception e) {
              // Command Executor: Tasklet throws an exception
              final WorkerToMasterReport workerToMasterReport =
                  new TaskletFailureReport(taskletExecutionRequest.getTaskletId(), e);
              holder.add(workerToMasterReport);
            }

            reports = new WorkerToMasterReports(holder);
            workerReports.addLast(kryoUtils.serialize(reports));
            try {
              latch.await();
            } catch (final InterruptedException e) {
              LOG.log(Level.SEVERE, "Cannot wait for Future to be put.");
              throw new RuntimeException(e);
            }
            futures.remove(taskletExecutionRequest.getTaskletId());
            heartBeatTriggerManager.triggerHeartBeat();
          }
        }));

    // Signal that future is put.
    latch.countDown();
  }
231387
private Throwable getResult(FutureTask<Throwable> task, Thread thread) {
        try {
            if (timeout > 0) {
                return task.get(timeout, timeUnit);
            } else {
                return task.get();
            }
        } catch (InterruptedException e) {
            return e; // caller will re-throw; no need to call Thread.interrupt()
        } catch (ExecutionException e) {
            // test failed; have caller re-throw the exception thrown by the test
            return e.getCause();
        } catch (TimeoutException e) {
            return createTimeoutException(thread);
        }
    }
1206455
private void cancelInvokable(AbstractInvokable invokable) {
		// in case of an exception during execution, we still call "cancel()" on the task
		if (invokable != null && invokableHasBeenCanceled.compareAndSet(false, true)) {
			try {
				invokable.cancel();
			}
			catch (Throwable t) {
				LOG.error("Error while canceling task {}.", taskNameWithSubtask, t);
			}
		}
	}
1040101
@Override
    public void execute(Runnable task) {
        // count a new task in process
        tasksInProcess.incrementAndGet();
        try {
            super.execute(task);
        } catch (RuntimeException e) { // specifically handle RejectedExecutionException
            tasksInProcess.decrementAndGet();
            throw e;
        } catch (Error e) {
            tasksInProcess.decrementAndGet();
            throw e;
        }
    }
111123
@Override
	protected Object invoke(DelegatingMethodInvocation<T> methodInvocation) throws Throwable {
		final Split split = stopwatchSource.start(methodInvocation);
		try {
			return methodInvocation.proceed();
		} finally {
			split.stop();
		}
	}
273247
def _invoke(task, args):
	''''''
	kwargs = task.defaults.copy()
	if task.kwargs:
		temp_kwargs, args = getopt.getopt(args, '', task.kwargs)
		temp_kwargs = _opts_to_dict(*temp_kwargs)
		kwargs.update(temp_kwargs)

	if task.args:
		for arg in task.args:
			if not len(args):
				abort(LOCALE['error_wrong_args'], task, len(task.args))
			kwargs.update({arg: args[0]})
			args = args[1:]

	if task.consume:
		task(*args, **kwargs)
		return []
	else:
		task(**kwargs)
		return args
1129558
@Override
	public Object invoke(Object self, Method thisMethod, Method proceed, Object[] args) throws Throwable
	{
		// Get an instance of the implementing class via Guice
		final Object instance = registry.getInjector().getInstance(clazz);

		return thisMethod.invoke(instance, args);
	}
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;
            }
        }
    }