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:org.midonet.mmdpctl.Mmdpctl.java

public int execute(Command<? extends Result> command, OutputStream stream) {
    PrintStream out = new PrintStream(stream);
    OvsDatapathConnection connection;//from w  ww  .  j  a  v  a2  s  .c o  m
    try {
        connection = DatapathClient.createConnection();
    } catch (Exception e) {
        log.error("Could not connect to netlink: {}", e);
        return -1;
    }

    Future<? extends Result> resultFuture = command.execute(connection);

    try {
        Result result = null;
        // if the user supplied a timeout make add it to the Future.get()
        if (timeout > 0) {
            result = resultFuture.get(timeout, TimeUnit.SECONDS);
        } else {
            result = resultFuture.get();
        }

        // display result on screen.
        result.printResult(out);
    } catch (TimeoutException e) {
        System.out.println("Didn't get result in time. Aborting");
        resultFuture.cancel(true);
        return -1;
    } catch (Exception e) {
        log.error("Error while retrieving the datapath: {}", e);
        return -1;
    }

    return 0;
}

From source file:cn.caimatou.canting.utils.http.asynchttp.AsyncHttpClient.java

/**
 * Cancels any pending (or potentially active) requests associated with the
 * passed Context.// w ww  .j ava  2 s. co  m
 * <p>
 * <b>Note:</b> This will only affect requests which were created with a non-null
 * android Context. This method is intended to be used in the onDestroy
 * method of your android activities to destroy all requests which are no
 * longer required.
 *
 * @param context the android Context instance associated to the request.
 * @param mayInterruptIfRunning specifies if active requests should be cancelled along with pending requests.
 */
public void cancelRequests(Context context, boolean mayInterruptIfRunning) {
    List<WeakReference<Future<?>>> requestList = requestMap.get(context);
    if (requestList != null) {
        for (WeakReference<Future<?>> requestRef : requestList) {
            Future<?> request = requestRef.get();
            if (request != null) {
                request.cancel(mayInterruptIfRunning);
            }
        }
    }
    requestMap.remove(context);
}

From source file:com.thoughtworks.go.buildsession.ExecCommandExecutor.java

private int executeCommandLine(final BuildSession buildSession, final CommandLine commandLine) {
    final AtomicInteger exitCode = new AtomicInteger(-1);
    final CountDownLatch canceledOrDone = new CountDownLatch(1);
    buildSession.submitRunnable(new Runnable() {
        @Override//from   ww w.  java  2 s. c o m
        public void run() {
            try {
                exitCode.set(commandLine.run(buildSession.processOutputStreamConsumer(), null));
            } catch (CommandLineException e) {
                LOG.error("Command failed", e);
                String message = format(
                        "Error happened while attempting to execute '%s'. \nPlease make sure [%s] can be executed on this agent.\n",
                        commandLine.toStringForDisplay(), commandLine.getExecutable());
                String path = System.getenv("PATH");
                buildSession.println(message);
                buildSession.println(format("[Debug Information] Environment variable PATH: %s", path));
                LOG.error(format("[Command Line] %s. Path: %s", message, path));
            } finally {
                canceledOrDone.countDown();
            }
        }
    });

    Future<?> cancelMonitor = buildSession.submitRunnable(new Runnable() {
        @Override
        public void run() {
            try {
                buildSession.waitUntilCanceled();
            } catch (InterruptedException e) {
                // ignore
            } finally {
                canceledOrDone.countDown();
            }
        }
    });

    try {
        canceledOrDone.await();
    } catch (InterruptedException e) {
        LOG.error("Building thread interrupted", e);
    }
    cancelMonitor.cancel(true);
    return exitCode.get();
}

From source file:fr.inria.wimmics.coresetimer.CoreseTimer.java

public CoreseTimer run() throws ClassNotFoundException, IllegalAccessException, InstantiationException,
        IOException, LoadException {
    LOGGER.entering(CoreseTimer.class.getName(), "run");
    assert (initialized);

    // Loading the nq data in corese, then applying several times the query.
    LOGGER.log(Level.INFO, "beginning with input #{0}", test.getInput());
    // require to have a brand new adapter for each new input set.
    adapter = (CoreseAdapter) Class.forName(adapterName).newInstance();

    String inputFileName = "";
    switch (mode) {
    case MEMORY: {
        inputFileName += test.getInput();
        adapter.preProcessing(inputFileName, true);
        break;/*w ww.java2 s  . c o  m*/
    }
    case DB: {
        inputFileName += test.getInputDb();
        System.setProperty("fr.inria.corese.tinkerpop.dbinput", inputFileName);
        adapter.preProcessing(inputFileName, false);
        break;
    }
    }

    String query = test.getRequest();
    LOGGER.log(Level.INFO, "processing nbQuery #{0}", query);
    stats = new DescriptiveStatistics();
    statsMemory = new DescriptiveStatistics();
    int nbCycles = test.getMeasuredCycles() + test.getWarmupCycles();
    boolean measured = true;
    for (int i = 0; i < nbCycles; i++) {
        LOGGER.log(Level.INFO, "iteration #{0}", i);
        System.gc();
        final long startTime = System.currentTimeMillis();
        LOGGER.log(Level.INFO, "before query");

        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<?> future = executor.submit(new Runnable() {
            @Override
            public void run() {
                adapter.execQuery(query);
            }
        });

        try {
            future.get(1, TimeUnit.HOURS);
            measured = true;
        } catch (InterruptedException | TimeoutException e) {
            future.cancel(true);
            measured = false;
            LOGGER.log(Level.WARNING, "Terminated!");
        } catch (ExecutionException ex) {
            Logger.getLogger(CoreseTimer.class.getName()).log(Level.SEVERE, null, ex);
        }
        executor.shutdownNow();

        LOGGER.log(Level.INFO, "after query");
        final long endTime = System.currentTimeMillis();
        long delta = endTime - startTime;
        long memoryUsage = getMemoryUsage();
        LOGGER.info(String.format("elapsed time = %d ms", delta));
        LOGGER.info(String.format("used memory = %d bytes", memoryUsage));
        if (i >= test.getWarmupCycles()) {
            if (!measured) {
                while (i < nbCycles) {
                    stats.addValue(-100);
                    statsMemory.addValue(memoryUsage);
                    i++;
                }
            } else {
                stats.addValue(delta);
                statsMemory.addValue(memoryUsage);
            }
        }
    }
    adapter.saveResults(test.getOutputPath());
    mappings = adapter.getMappings();
    adapter.postProcessing();
    LOGGER.exiting(CoreseTimer.class.getName(), "run");
    return this;
}

From source file:org.apache.syncope.core.provisioning.java.ConnectorFacadeProxy.java

@Override
public void validate() {
    Future<String> future = asyncFacade.test(connector);
    try {/* w  w  w  .ja  v  a  2s. c o  m*/
        future.get(connInstance.getConnRequestTimeout(), TimeUnit.SECONDS);
    } catch (java.util.concurrent.TimeoutException e) {
        future.cancel(true);
        throw new TimeoutException("Request timeout");
    } catch (Exception e) {
        LOG.error("Connector request execution failure", e);
        if (e.getCause() instanceof RuntimeException) {
            throw (RuntimeException) e.getCause();
        } else {
            throw new IllegalArgumentException(e.getCause());
        }
    }
}

From source file:org.apache.syncope.core.provisioning.java.ConnectorFacadeProxy.java

@Override
public void test() {
    Future<String> future = asyncFacade.test(connector);
    try {/*from   ww w .ja  v a2 s  . com*/
        future.get(connInstance.getConnRequestTimeout(), TimeUnit.SECONDS);
    } catch (java.util.concurrent.TimeoutException e) {
        future.cancel(true);
        throw new TimeoutException("Request timeout");
    } catch (Exception e) {
        LOG.error("Connector request execution failure", e);
        if (e.getCause() instanceof RuntimeException) {
            throw (RuntimeException) e.getCause();
        } else {
            throw new IllegalArgumentException(e.getCause());
        }
    }
}

From source file:com.phodev.http.tools.ConnectionHelper.java

/**
 * ?/* w  w  w.ja v a2s  . c om*/
 * 
 * @param reqFingerprint
 * @return
 */
public boolean cancleRequest(long reqFingerprint) throws RequestEntityNotFoundException {
    RequestEntity request = null;
    synchronized (mRequestRecords) {
        request = mRequestRecords.get(reqFingerprint);
        if (request == null) {
            throw new RequestEntityNotFoundException(reqFingerprint);
        }
        //
        synchronized (request) {
            if (request.isCanceled() && request.isCancelStateSend()) {
                return true;
            }
            Future<?> future = request.getRequestTaskFuture();
            if (future == null) {
                return true;
            }
            request.setCanceled(true);
            //
            try {
                future.cancel(true);
            } catch (Exception e) {
                e.printStackTrace();
                return isReqeustRunning(reqFingerprint);
            }
            tryNotifyCanceled(request);
        }
    }
    return true;
}

From source file:org.frontcache.include.impl.ConcurrentIncludeProcessor.java

/**
 * /*from ww  w  . j  a  va2s .  co m*/
 * @param content
 * @param hostURL
 * @return
 */
public WebResponse processIncludes(WebResponse parentWebResponse, String hostURL,
        Map<String, List<String>> requestHeaders, HttpClient client, RequestContext context,
        int recursionLevel) {
    String contentStr = new String(parentWebResponse.getContent());
    List<IncludeResolutionPlaceholder> includes = parseIncludes(contentStr, hostURL, requestHeaders, client,
            context);

    if (null == includes)
        return parentWebResponse;

    List<Future<IncludeResolutionPlaceholder>> futureList = new ArrayList<Future<IncludeResolutionPlaceholder>>(
            includes.size()); // for sync includes

    for (int i = 0; i < includes.size(); i++) {
        IncludeResolutionPlaceholder inc = includes.get(i);
        inc.includeLevel = "" + recursionLevel + "." + i;

        boolean performInclude = false; // check for client specific include
        if (null == inc.includeClientType) {
            performInclude = true;

        } else if (inc.includeClientType.equalsIgnoreCase(context.getClientType())) {

            // client type specific include
            performInclude = true;
        } else {

            // client type for include and request doesnt match 
            performInclude = false;
        }

        inc.performInclude = performInclude; // save for include resolution

        if (performInclude) {
            if (INCLUDE_TYPE_ASYNC.equals(inc.includeType)) {
                // run concurrent include resolution
                // for Async includes - do NOT wait for response from Origin
                // response from Origin is NOT included to response to client
                // useful for counters - e.g. response totally from cache (fast) and async call to origin 
                executor.submit(inc);
            } else {
                // run concurrent include resolution
                // for Sync includes - wait for response from Origin (until timeout)
                // origin responses are sent to client
                futureList.add(executor.submit(inc));
            }
        } // if (performInclude)
    }

    // processing timeouts for Sync includes 
    boolean timeoutReached = false;
    for (Future<IncludeResolutionPlaceholder> f : futureList) {
        try {
            if (timeoutReached)
                f.get(1, TimeUnit.MILLISECONDS);
            else
                f.get(timeout, TimeUnit.MILLISECONDS);

        } catch (TimeoutException | InterruptedException | ExecutionException e) {
            f.cancel(true);
            timeoutReached = true;
            logger.debug("timeout (" + timeout
                    + ") reached for resolving includes. Some includes may not be resolved ");
        }
    }

    // replace placeholders with content
    WebResponse agregatedWebResponse = replaceIncludePlaceholders(contentStr, includes);

    return agregatedWebResponse;
}

From source file:com.splout.db.qnode.Deployer.java

public StatusMessage cancelDeployment(long version) {
    Future<?> future = runningDeployments.get(version);
    if (future == null) {
        return new StatusMessage(StatusMessage.Status.ERROR,
                "No deployment running for " + version + " found.");
    }/*from w w  w .j a v a  2  s  . c o  m*/
    future.cancel(true);
    return new StatusMessage(StatusMessage.Status.OK,
            "Deployment for version " + version + " being cancelled.");
}

From source file:com.googlecode.jsfFlex.shared.tasks.TaskRunnerImpl.java

public void waitForFutureTask(String taskName) {
    Future<Void> task = _queuedTasks.get(taskName);
    if (task != null) {
        try {//  www.  j av  a  2  s. co m
            _log.info("Waiting for taskName : " + taskName);
            task.get();
            _log.info("Finished waiting for the taskName : " + taskName);
        } catch (ExecutionException executeExcept) {
            _log.error("Execution exception thrown within waitForFutureTask for " + taskName, executeExcept);
        } catch (InterruptedException interruptedExcept) {
            Thread.currentThread().interrupt();
        } finally {
            task.cancel(true);
        }
    }
}