Sends a cancel signal and blocks and waits until the task is cancelled, completed, or failed, or
if the timeout has expired.
@return true if task did not start or was cancelled, false if task failed or completed
437055
public boolean cancel(final boolean mayInterruptIfRunning, final long timeout, final TimeUnit unit)
      throws TimeoutException {
    return cancel(mayInterruptIfRunning, Optional.of(timeout), Optional.of(unit));
  }
52018
def cancel(self):
        
        with self._condition:
            if self._state in [RUNNING, FINISHED]:
                return False

            if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
                return True

            self._state = CANCELLED
            self._condition.notify_all()

        self._invoke_callbacks()
        return True
256141
public final void cancel(CancelException reason) {
		if (cancelling != null)
			return;
		if (reason == null) reason = new CancelException("No reason given");
		cancelling = reason;
		if (TaskScheduler.cancel(this)) {
			status = Task.STATUS_DONE;
			result.cancelled(reason);
			return;
		}
		if (manager.remove(this)) {
			status = Task.STATUS_DONE;
			result.cancelled(reason);
			return;
		}
		if (status == Task.STATUS_NOT_STARTED) {
			status = Task.STATUS_DONE;
			result.cancelled(reason);
			return;
		}
	}
1212520
def wait(self, timeout=None):
    

    tbegin = _get_timeout_begin(timeout)
    with self._lock:
      while self._queue or self._running:
        remainder = _get_timeout_remainder(tbegin, timeout)
        if remainder is not None and remainder <= 0.0:
          return False  # timeout
        self._lock.wait(remainder)
      if self._shutdown:
        for worker in self._workers:
          worker.join()
    return True
273420
protected boolean confirmShutdown() {
        if (!isShuttingDown()) {
            return false;
        }

        if (!inEventLoop()) {
            throw new IllegalStateException("must be invoked from an event loop");
        }

        cancelScheduledTasks();

        if (gracefulShutdownStartTime == 0) {
            gracefulShutdownStartTime = ScheduledFutureTask.nanoTime();
        }

        if (runAllTasks() || runShutdownHooks()) {
            if (isShutdown()) {
                // Executor shut down - no new tasks anymore.
                return true;
            }

            // There were tasks in the queue. Wait a little bit more until no tasks are queued for the quiet period or
            // terminate if the quiet period is 0.
            // See https://github.com/netty/netty/issues/4241
            if (gracefulShutdownQuietPeriod == 0) {
                return true;
            }
            wakeup(true);
            return false;
        }

        final long nanoTime = ScheduledFutureTask.nanoTime();

        if (isShutdown() || nanoTime - gracefulShutdownStartTime > gracefulShutdownTimeout) {
            return true;
        }

        if (nanoTime - lastExecutionTime <= gracefulShutdownQuietPeriod) {
            // Check if any tasks were added to the queue every 100ms.
            // TODO: Change the behavior of takeTask() so that it returns on timeout.
            wakeup(true);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // Ignore
            }

            return false;
        }

        // No tasks were added for last quiet period - hopefully safe to shut down.
        // (Hopefully because we really cannot make a guarantee that there will be no execute() calls by a user.)
        return true;
    }
890846
protected boolean taskCanceled() {
        boolean cancel = canceled;
        if (!cancel) {
            for (K parent = getParent(); !cancel && parent != null; parent = parent.getParent())
                cancel = parent.canceled;
        }

        return cancel;
    }
154932
@Override
    public boolean cancel(boolean mayInterruptIfRunning) {
        if (m_isDone == true) {
            return false;
        }
        m_isDone = true;

        if (m_pendingException != null) {
            return false;
        }

        m_cancelResult = m_schedFuture.cancel(false);

        if ((m_cancelResult != true) || (m_defaultFuture != null)) {
            // Push the cancel call to the Default Executor Future if it has progressed that far.
            try {
                this.m_coordinationLatch.await();
            } catch (InterruptedException ie) {
                // Try to proceed.
            }

            if (m_defaultFuture != null) {
                m_cancelResult = m_defaultFuture.cancel(mayInterruptIfRunning);
            }
        }

        if (m_cancelResult == true) {
            m_pendingException = new CancellationException();
            m_scheduledExecutorQueue.remove(this);
        }

        // Let get() finish
        this.m_coordinationLatch.countDown();

        return m_cancelResult;
    }
1135710
public static <TError extends Exception> void waitUnblockedWithError(Collection<AsyncWork<?,TError>> tasks) throws TError, CancelException {
		for (AsyncWork<?,TError> t : tasks)
			t.blockResult(0);
	}
247019
@Override public final boolean cancel( boolean mayInterruptIfRunning ) {
    boolean did = false;
    synchronized(this) {        // Install the answer under lock
      if( !isCancelled() ) {
        did = true;             // Did cancel (was not cancelled already)
        _target.taskRemove(_tasknum);
        _target = null;         // Flag as canceled
//        UDPTimeOutThread.PENDING.remove(this);
      }
      notifyAll();              // notify in any case
    }
    return did;
  }
585780
public synchronized boolean removeTaskFromWaitQ(ParallelTask taskTobeRemoved) {
        boolean removed = false;
        for (ParallelTask task : waitQ) {
            if (task.getTaskId() == taskTobeRemoved.getTaskId()) {

                task.setState(ParallelTaskState.COMPLETED_WITH_ERROR);
                task.getTaskErrorMetas().add(
                        new TaskErrorMeta(TaskErrorType.USER_CANCELED, "NA"));
                logger.info(
                        "task {} removed from wait q. This task has been marked as USER CANCELED.",
                        task.getTaskId());
                removed = true;
            }
        }

        return removed;
    }
385490
private boolean pauseIfRetryNeeded(int retries) {
        if (retries >= connection.getMaxErrorRetry()) {
            return false;
        }
        long delay = (long) (Math.random() * Math.pow(4, retries) * 125);
        try {
            Thread.sleep(delay);
        } catch (Exception e) {
            throw MwsUtl.wrap(e);
        }
        return true;
    }
861898
public boolean await(final Date deadline) throws InterruptedException {
	this.lock.lock();
	try {
	  if (this.cancelled) {
		throw new InterruptedException("Operation interrupted");
	  }
	  boolean success = false;
	  if (deadline != null) {
		success = this.condition.awaitUntil(deadline);
	  } else {
		this.condition.await();
		success = true;
	  }
	  if (this.cancelled) {
		throw new InterruptedException("Operation interrupted");
	  }
	  return success;
	} finally {
	  this.lock.unlock();
	}

  }
417530
def _do_wait(self, timeout):
        

        if self._cancelled:
            raise CancelledError()

        if not self._done:
            self._wait = True
            
            self._sigint = pyev.Signal(signal.SIGINT, self.loop, lambda watcher, events: self._cancel(), None)
            self._sigint.start()

            if timeout and timeout > 0.0:
                self._timer = pyev.Timer(timeout, 0.0, self.loop,
                                         self._clear_wait, None)
                self._timer.start()

            while self._wait and not self._done and not self._cancelled:
                self.loop.start(pyev.EVRUN_ONCE)

        if self._cancelled:
            raise CancelledError()
        elif not self._done:
            raise TimeoutError()
414516
public TaskCancelResult cancelTask() {

		while (true) {

			final ExecutionState previousState = this.executionState.get();

			if (previousState == ExecutionState.CANCELED) {
				return new TaskCancelResult(getID(), AbstractTaskResult.ReturnCode.SUCCESS);
			}

			if (previousState == ExecutionState.FAILED) {
				return new TaskCancelResult(getID(), AbstractTaskResult.ReturnCode.SUCCESS);
			}

			if (previousState == ExecutionState.FINISHED) {
				return new TaskCancelResult(getID(), AbstractTaskResult.ReturnCode.SUCCESS);
			}

			// The vertex has already received a cancel request
			if (previousState == ExecutionState.CANCELING) {
				return new TaskCancelResult(getID(), ReturnCode.SUCCESS);
			}

			// Do not trigger the cancel request when vertex is in state STARTING, this might cause a race between RPC
			// calls.
			if (previousState == ExecutionState.STARTING) {

				this.cancelRequested.set(true);

				// We had a race, so we unset the flag and take care of cancellation ourselves
				if (this.executionState.get() != ExecutionState.STARTING) {
					this.cancelRequested.set(false);
					continue;
				}

				return new TaskCancelResult(getID(), AbstractTaskResult.ReturnCode.SUCCESS);
			}

			// Check if we had a race. If state change is accepted, send cancel request
			if (compareAndUpdateExecutionState(previousState, ExecutionState.CANCELING)) {

				if (this.groupVertex.getStageNumber() != this.executionGraph.getIndexOfCurrentExecutionStage()) {
					// Set to canceled directly
					updateExecutionState(ExecutionState.CANCELED, null);
					return new TaskCancelResult(getID(), AbstractTaskResult.ReturnCode.SUCCESS);
				}

				if (previousState != ExecutionState.RUNNING && previousState != ExecutionState.FINISHING) {
					// Set to canceled directly
					updateExecutionState(ExecutionState.CANCELED, null);
					return new TaskCancelResult(getID(), AbstractTaskResult.ReturnCode.SUCCESS);
				}

				final AllocatedResource ar = this.allocatedResource.get();

				if (ar == null) {
					final TaskCancelResult result = new TaskCancelResult(getID(),
						AbstractTaskResult.ReturnCode.NO_INSTANCE);
					result.setDescription("Assigned instance of vertex " + this.toString() + " is null!");
					return result;
				}

				try {
					return ar.getInstance().cancelTask(this.vertexID);

				} catch (IOException e) {
					final TaskCancelResult result = new TaskCancelResult(getID(),
						AbstractTaskResult.ReturnCode.IPC_ERROR);
					result.setDescription(StringUtils.stringifyException(e));
					return result;
				}
			}
		}
	}
869968
def join(self, timeout=None):
        
        if self._queue.empty():
            # Nothing to wait for...
            return True
        elif timeout is None:
            # Use the original join
            self._queue.join()
            return True
        else:
            # Wait for the condition
            with self._queue.all_tasks_done:
                self._queue.all_tasks_done.wait(timeout)
                return not bool(self._queue.unfinished_tasks)
399309
public boolean waitForActive(long timeout)
  {
    LifecycleState state = getState();

    if (state.isActive()) {
      return true;
    }
    else if (state.isAfterActive()) {
      return false;
    }
    
    // server/1d2j
    long waitEnd = CurrentTime.getCurrentTimeActual() + timeout;

    synchronized (this) {
      while ((state = _state).isBeforeActive()
             && CurrentTime.getCurrentTimeActual() < waitEnd) {
        if (state.isActive()) {
          return true;
        }
        else if (state.isAfterActive()) {
          return false;
        }

        try {
          long delta = waitEnd - CurrentTime.getCurrentTimeActual();
          
          if (delta > 0) {
            wait(delta);
          }
        } catch (InterruptedException e) {
        }
      }
    }
    
    return _state.isActive();
  }
1292986
int await() throws InterruptedException {
        int s = state.get();
        if (s == SUBMITTED || s == RUNNING && thread != Thread.currentThread()) {
            if (s == RUNNING || nsStartBy == nsAcceptBegin - 1) { // already started or no start timeout
                state.acquireSharedInterruptibly(1);
                s = state.get();
            } else { // wait for up to the start timeout, then continue waiting if task has started
                long nsGetBegin = System.nanoTime();
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                    Tr.debug(this, tc, "await start timeout for " + (nsStartBy - nsGetBegin) + "ns");
                state.tryAcquireSharedNanos(1, nsStartBy - nsGetBegin);
                s = state.get();
                if (s == SUBMITTED) { // attempt to abort the task
                    abort(true, new StartTimeoutException(getIdentifier(), getTaskName(), //
                                    System.nanoTime() - nsAcceptBegin, //
                                    nsStartBy - nsAcceptBegin));
                    s = state.get();
                }
                if (s == RUNNING) { // continue waiting
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                        Tr.debug(this, tc, "await completion");
                    state.acquireSharedInterruptibly(1);
                    s = state.get();
                }
            }
        }
        return s;
    }