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.openhab.io.neeo.internal.NeeoUtil.java

/**
 * Cancels the specified {@link Future}//w ww .j a v a2 s.  c o m
 *
 * @param future a possibly null future. If null, no action is done
 */
static void cancel(@Nullable Future<?> future) {
    if (future != null) {
        future.cancel(true);
    }
}

From source file:mase.conillon.ConillonMasterProblem.java

public static void runWithTimeout(Runnable runnable, long timeout, TimeUnit timeUnit) throws Exception {
    final ExecutorService executor = Executors.newSingleThreadExecutor();
    final Future future = executor.submit(runnable);
    executor.shutdown(); // This does not cancel the already-scheduled task.
    try {/*from   www .  j  av a2  s.  c o m*/
        future.get(timeout, timeUnit);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        future.cancel(true);
        throw e;
    }
}

From source file:mase.conillon.ConillonMasterProblem.java

public static <T> T runWithTimeout(Callable<T> callable, long timeout, TimeUnit timeUnit) throws Exception {
    final ExecutorService executor = Executors.newSingleThreadExecutor();
    final Future<T> future = executor.submit(callable);
    executor.shutdown(); // This does not cancel the already-scheduled task.
    try {/*from ww w .j a va  2 s  . co  m*/
        return future.get(timeout, timeUnit);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        future.cancel(true);
        throw e;
    }
}

From source file:com.android.tools.idea.uibuilder.handlers.ui.AppBarConfigurationDialog.java

@Nullable
private static Future<?> cancel(@Nullable Future<?> future) {
    if (future != null) {
        future.cancel(true);
    }// w  ww .j a  v a2  s .  c  o  m
    return null;
}

From source file:org.wisdom.test.http.HttpClientHelper.java

/**
 * Emits an asynchronous request./*from w ww.  ja v  a  2  s. c o m*/
 *
 * @param request       the request
 * @param responseClass the response class
 * @param callback      the completion callback
 * @param <T>           the type of the expected result
 * @return the future to retrieve the result
 */
public static <T> Future<HttpResponse<T>> requestAsync(HttpRequest request, final Class<T> responseClass,
        Callback<T> callback) {
    HttpUriRequest requestObj = prepareRequest(request);

    CloseableHttpAsyncClient asyncHttpClient = ClientFactory.getAsyncHttpClient();
    if (!asyncHttpClient.isRunning()) {
        asyncHttpClient.start();
    }

    final Future<org.apache.http.HttpResponse> future = asyncHttpClient.execute(requestObj,
            prepareCallback(responseClass, callback));

    return new Future<HttpResponse<T>>() {

        /**
         * Cancels the request.
         *
         * @param mayInterruptIfRunning whether or not we need to interrupt the request.
         * @return {@literal true} if the task is successfully canceled.
         */
        public boolean cancel(boolean mayInterruptIfRunning) {
            return future.cancel(mayInterruptIfRunning);
        }

        /**
         * @return whether the future is cancelled.
         */
        public boolean isCancelled() {
            return future.isCancelled();
        }

        /**
         * @return whether the result is available.
         */
        public boolean isDone() {
            return future.isDone();
        }

        /**
         * Gets the result.
         * @return the response.
         * @throws InterruptedException if the request is interrupted.
         * @throws ExecutionException if the request fails.
         */
        public HttpResponse<T> get() throws InterruptedException, ExecutionException {
            org.apache.http.HttpResponse httpResponse = future.get();
            return new HttpResponse<>(httpResponse, responseClass);
        }

        /**
         * Gets the result.
         * @param timeout timeout configuration
         * @param unit unit timeout
         * @return the response.
         * @throws InterruptedException if the request is interrupted.
         * @throws ExecutionException if the request fails.
         * @throws TimeoutException if the set time out is reached before the completion of the request.
         */
        public HttpResponse<T> get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            org.apache.http.HttpResponse httpResponse = future.get(timeout * TimeUtils.TIME_FACTOR, unit);
            return new HttpResponse<>(httpResponse, responseClass);
        }
    };
}

From source file:org.eclipse.mylyn.commons.http.HttpUtil.java

/**
 * @since 3.6/*from  w  w  w .ja v a  2  s .c  o m*/
 */
public static <T> T execute(IProgressMonitor monitor, WebRequest<T> request) throws Throwable {
    // check for legacy reasons
    SubMonitor subMonitor = (monitor instanceof SubMonitor) ? (SubMonitor) monitor : SubMonitor.convert(null);

    Future<T> future = CommonsHttpPlugin.getExecutorService().submit(request);
    while (true) {
        if (monitor.isCanceled()) {
            request.abort();

            // wait for executor to finish
            future.cancel(false);
            try {
                if (!future.isCancelled()) {
                    future.get();
                }
            } catch (CancellationException e) {
                // ignore
            } catch (InterruptedException e) {
                // ignore
            } catch (ExecutionException e) {
                // ignore
            }
            throw new OperationCanceledException();
        }

        try {
            return future.get(POLL_INTERVAL, TimeUnit.MILLISECONDS);
        } catch (ExecutionException e) {
            throw e.getCause();
        } catch (TimeoutException ignored) {
        }

        subMonitor.setWorkRemaining(20);
        subMonitor.worked(1);
    }
}

From source file:org.intellij.erlang.rebar.settings.RebarConfigurable.java

@NotNull
private static String restrictedTimeExec(@NotNull String cmd, int timeout) {
    try {//from   w ww .j ava  2s .c  o m
        final Process cmdRunner = Runtime.getRuntime().exec(cmd);
        final ExecutorService singleTreadExecutor = Executors.newSingleThreadExecutor();
        final Future<String> cmdRunnerFuture = singleTreadExecutor.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                cmdRunner.waitFor();
                final BufferedReader outReader = new BufferedReader(
                        new InputStreamReader(cmdRunner.getInputStream()));
                try {
                    final String firstLine = outReader.readLine();
                    return firstLine == null ? "" : firstLine;
                } finally {
                    outReader.close();
                }
            }
        });
        try {
            return cmdRunnerFuture.get(timeout, TimeUnit.MILLISECONDS);
        } catch (Exception e) { // Suppress
        }
        cmdRunnerFuture.cancel(true);
        singleTreadExecutor.shutdown();
    } catch (IOException e) { // Suppress
    }
    return "";
}

From source file:org.blocks4j.reconf.infra.http.layer.SimpleHttpClient.java

private static SimpleHttpResponse execute(CloseableHttpClient httpClient, SimpleHttpRequest request,
        long timeout, TimeUnit timeunit) throws Exception {

    RequestTask task = new RequestTask(httpClient, request);
    Future<SimpleHttpResponse> futureResponse = null;

    try {/*ww w  .  j a  va2s  .co  m*/
        futureResponse = requestExecutor.submit(task);
        return futureResponse.get(timeout, timeunit);

    } catch (TimeoutException e) {
        httpClient.close();
        RequestLine line = request.getRequestLine();
        String method = request.getMethod();

        if (line != null && method != null) {
            throw new TimeoutException(msg.format("error.complete", method.toUpperCase(), line.getUri(),
                    timeout, timeunit.toString().toLowerCase()));

        } else {
            throw new TimeoutException(msg.format("error", timeout, timeunit.toString().toLowerCase()));
        }

    } catch (Exception e) {
        httpClient.close();
        throw e;

    } finally {
        if (futureResponse != null) {
            futureResponse.cancel(true);
        }
    }
}

From source file:org.eclipse.mylyn.commons.net.WebUtil.java

/**
 * @since 3.0/*from   ww w  . j a  va 2  s .  com*/
 */
public static <T> T execute(IProgressMonitor monitor, WebRequest<T> request) throws Throwable {
    // check for legacy reasons
    SubMonitor subMonitor = (monitor instanceof SubMonitor) ? (SubMonitor) monitor : SubMonitor.convert(null);

    Future<T> future = CommonsNetPlugin.getExecutorService().submit(request);
    while (true) {
        if (monitor.isCanceled()) {
            request.abort();

            // wait for executor to finish
            future.cancel(false);
            try {
                if (!future.isCancelled()) {
                    future.get();
                }
            } catch (CancellationException e) {
                // ignore
            } catch (InterruptedException e) {
                // ignore
            } catch (ExecutionException e) {
                // ignore
            }
            throw new OperationCanceledException();
        }

        try {
            return future.get(POLL_INTERVAL, TimeUnit.MILLISECONDS);
        } catch (ExecutionException e) {
            throw e.getCause();
        } catch (TimeoutException ignored) {
        }

        subMonitor.setWorkRemaining(20);
        subMonitor.worked(1);
    }
}

From source file:com.eucalyptus.storage.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.
 * //from  w w  w . java2 s  .c  om
 * @param command
 * @param timeout
 * @return CommandOutput
 * @throws EucalyptusCloudException
 */
private static CommandOutput execute(@NotNull String[] command, @NotNull 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 = service.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);
    }
}