Example usage for java.util.concurrent Future cancel

List of usage examples for java.util.concurrent Future cancel

Introduction

In this page you can find the example usage for java.util.concurrent Future cancel.

Prototype

boolean cancel(boolean mayInterruptIfRunning);

Source Link

Document

Attempts to cancel execution of this task.

Usage

From source file:yarnkit.appmaster.ApplicationMaster.java

@Override
public int run(String[] args) throws Exception {
    Configuration jobConf = getConf();

    YarnkitConfig appConf = getApplicationConfigFile(jobConf);
    ApplicationMasterParameters params = getApplicationMasterParameters(appConf, jobConf);
    ApplicationMasterService appmaster = new ApplicationMasterService(params);

    // First, start auxiliary service
    List<Future<?>> services = runAuxiliaryServices(appConf, jobConf);
    // Then, launch ApplicationMaster
    appmaster.startAndWait();/*from   w  w  w  .j  a v a2 s  . com*/

    while (appmaster.hasRunningContainers()) {
        Thread.sleep(1000);
    }

    for (Future<?> f : services) {
        f.cancel(true);
    }
    appmaster.stopAndWait();
    return 0;
}

From source file:io.cloudslang.content.utilities.util.ProcessExecutor.java

private void stopProcess(Process process, Future<ProcessResponseEntity> futureResult) {
    futureResult.cancel(true);
    process.destroy();/*from ww w  . j  a va 2s .  co  m*/

    closeQuietly(process.getInputStream());
    closeQuietly(process.getErrorStream());
}

From source file:com.alibaba.otter.shared.arbitrate.demo.servcie.ExtractServiceDemo.java

public void destory(Long pipelineId) {
    if (!threads.containsKey(pipelineId)) {
        throw new IllegalArgumentException("pipeline is not exist!");
    }/* w w  w.  ja v a 2 s.  com*/

    Future future = threads.get(pipelineId);
    future.cancel(true);
}

From source file:com.eucalyptus.blockstorage.TGTWrapper.java

/**
 * executeTGTs the specified tgt command in a separate process. 
 * A {@link DirectStorageInfo#timeoutInMillis timeout} is enforced on 
 * the process using {@link java.util.concurrent.ExecutorService ExecutorService} 
 * framework. If the process does not complete with in the timeout, it is cancelled.
 * /*w w  w  .  jav  a2  s  .  c o m*/
 * @param command
 * @param timeout
 * @return CommandOutput
 * @throws EucalyptusCloudException
 */
private static CommandOutput execute(@Nonnull String[] command, @Nonnull Long timeout)
        throws EucalyptusCloudException, CallTimeoutException {
    try {
        Integer returnValue = -999999;
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(command);
        StreamConsumer error = new StreamConsumer(process.getErrorStream());
        StreamConsumer output = new StreamConsumer(process.getInputStream());
        error.start();
        output.start();
        Callable<Integer> processMonitor = new ProcessMonitor(process);
        Future<Integer> processController = getExecutorWithInit().submit(processMonitor);
        try {
            returnValue = processController.get(timeout, TimeUnit.MILLISECONDS);
        } catch (TimeoutException tex) {
            String commandStr = buildCommand(command);
            LOG.error(commandStr + " timed out. Cancelling the process, logging a fault and exceptioning out");
            processController.cancel(true);
            Faults.forComponent(Storage.class).havingId(TGT_HOSED).withVar("component", "Storage Controller")
                    .withVar("timeout", Long.toString(timeout)).log();
            throw new CallTimeoutException("No response from the command " + commandStr
                    + ". Process timed out after waiting for " + timeout + " milliseconds");
        }
        output.join();
        error.join();
        LOG.debug("TGTWrapper executed: " + JOINER.join(command) + "\n return=" + returnValue + "\n stdout="
                + output.getReturnValue() + "\n stderr=" + error.getReturnValue());
        return new CommandOutput(returnValue, output.getReturnValue(), error.getReturnValue());
    } catch (CallTimeoutException e) {
        throw e;
    } catch (Exception ex) {
        throw new EucalyptusCloudException(ex);
    }
}

From source file:com.chingo247.structureapi.plan.document.PlanDocumentManager.java

/**
 * Loads all planDocuments & structureDocuments Multi-Core. Number of cores used is defined by
 * the number of cores available using Runtime.getRuntime.availableProcessors()
 *///from w w  w .  jav a  2  s . co m
@Override
public synchronized void loadDocuments() {

    // Go throug all XML files inside the 'Plans' folder
    Iterator<File> it = FileUtils.iterateFiles(structureAPI.getPlanDataFolder(), new String[] { "xml" }, true);
    final List<Future> tasks = new LinkedList<>();
    while (it.hasNext()) {
        final File planDocFile = it.next();
        tasks.add(executor.submit(new Runnable() {

            @Override
            public void run() {
                try {
                    SAXReader reader = new SAXReader();
                    Document d = reader.read(planDocFile);
                    // If the RootElement is not 'StructurePlan', skip it
                    if (!isStructurePlan(d)) {
                        return;
                    }
                    List<Element> elements = d.getRootElement().elements();

                    // Form plan document
                    PlanDocument planDocument = new PlanDocument(PlanDocumentManager.this, planDocFile);
                    for (Element pluginElement : elements) {
                        planDocument.putPluginElement(pluginElement.getName(), new PlanDocumentPluginElement(
                                pluginElement.getName(), planDocument, pluginElement));
                    }
                    // Save the document
                    PlanDocumentManager.this.put(planDocument.getRelativePath(), planDocument);
                } catch (DocumentException ex) {
                    Logger.getLogger(PlanDocumentManager.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }));
    }

    // Block until all tasks are done
    for (Future f : tasks) {
        try {
            f.get();
        } catch (InterruptedException | ExecutionException ex) {
            Logger.getLogger(PlanDocumentManager.class.getName()).log(Level.SEVERE, null, ex);
            for (Future fu : tasks) {
                fu.cancel(true);
            }
        }
    }
}

From source file:com.mesosphere.dcos.cassandra.executor.tasks.RestoreSnapshot.java

@Override
public void stop(Future<?> future) {
    future.cancel(true);
}

From source file:com.alibaba.otter.node.etl.common.task.GlobalTask.java

public void shutdown() {
    running = false;/*w ww . j av  a2s  . c  om*/
    interrupt();

    List<Future> cancelFutures = new ArrayList<Future>();
    for (Map.Entry<Long, Future> entry : pendingFuture.entrySet()) {
        if (!entry.getValue().isDone()) {
            logger.warn("WARN ## Task future processId[{}] canceled!", entry.getKey());
            cancelFutures.add(entry.getValue());
        }
    }

    for (Future future : cancelFutures) {
        future.cancel(true);
    }
    pendingFuture.clear();
}

From source file:com.jhkt.playgroundArena.shared.tasks.common.TaskQueues.java

public void cancelQueuedFutureTask(String taskName) {
    Future<Void> task = _queuedTasks.get(taskName);
    task.cancel(true);
    _queuedTasks.remove(taskName);//from   w  w w  .j av a 2  s.  c o  m
}

From source file:org.springframework.web.context.request.async.CallableInterceptorChain.java

private void cancelTask() {
    Future<?> future = this.taskFuture;
    if (future != null) {
        try {/*  w  ww . ja  v a  2 s .co  m*/
            future.cancel(true);
        } catch (Throwable ex) {
            // Ignore
        }
    }
}

From source file:com.mirth.connect.server.util.javascript.JavaScriptUtil.java

public static <T> T execute(JavaScriptTask<T> task) throws JavaScriptExecutorException, InterruptedException {
    Future<T> future = executor.submit(task);

    try {//from www . j  av  a  2  s  .c o m
        return future.get();
    } catch (ExecutionException e) {
        throw new JavaScriptExecutorException(e.getCause());
    } catch (InterruptedException e) {
        // synchronize with JavaScriptTask.executeScript() so that it will not initialize the context while we are halting the task
        synchronized (task) {
            future.cancel(true);
            Context context = task.getContext();

            if (context != null && context instanceof MirthContext) {
                ((MirthContext) context).setRunning(false);
            }
        }

        // TODO wait for the task thread to complete before exiting?
        Thread.currentThread().interrupt();
        throw e;
    }
}