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.apache.pulsar.compaction.TwoPhaseCompactor.java

private void scheduleTimeout(CompletableFuture<RawMessage> future) {
    Future<?> timeout = scheduler.schedule(() -> {
        future.completeExceptionally(new TimeoutException("Timeout"));
    }, 10, TimeUnit.SECONDS);/*ww  w .j  a va  2  s .co  m*/
    future.whenComplete((res, exception) -> {
        timeout.cancel(true);
    });
}

From source file:org.apache.http.impl.conn.JMeterPoolingClientConnectionManager.java

@Override
public ClientConnectionRequest requestConnection(final HttpRoute route, final Object state) {
    Args.notNull(route, "HTTP route");
    if (this.log.isDebugEnabled()) {
        this.log.debug("Connection request: " + format(route, state) + formatStats(route));
    }/*w ww  .j ava  2  s.c om*/
    final Future<HttpPoolEntry> future = this.pool.lease(route, state);

    return new ClientConnectionRequest() {
        @Override
        public void abortRequest() {
            future.cancel(true);
        }

        @Override
        public ManagedClientConnection getConnection(final long timeout, final TimeUnit tunit)
                throws InterruptedException, ConnectionPoolTimeoutException {
            return leaseConnection(future, timeout, tunit);
        }

    };

}

From source file:it.geosolutions.tools.io.file.CopyTree.java

/**
 * used internally to cancel all pending calls
 *//*ww  w  .j a  v a  2s.c  o  m*/
private void cancelCopyCalls() {
    // cancel all pending calls
    final Iterator<Future<File>> it = this.works.iterator();
    while (it.hasNext()) {
        Future<File> future = it.next();
        // cancel the call
        future.cancel(true);
    }
}

From source file:org.zenoss.zep.impl.Application.java

private void cancelFuture(Future<?> future) {
    if (future != null) {
        future.cancel(true);
        try {/*from   w  ww. j  av a2  s.co  m*/
            future.get();
        } catch (ExecutionException e) {
            logger.warn("exception", e);
        } catch (InterruptedException e) {
            logger.debug("Interrupted", e);
        } catch (CancellationException e) {
            /* Expected - we just canceled above */
        }
    }
}

From source file:net.ychron.unirestinst.http.HttpClientHelper.java

public <T> Future<HttpResponse<T>> requestAsync(HttpRequest request, final Class<T> responseClass,
        Callback<T> callback) {
    HttpUriRequest requestObj = prepareRequest(request, true);

    CloseableHttpAsyncClient asyncHttpClient = options.getAsyncHttpClient();
    if (!asyncHttpClient.isRunning()) {
        asyncHttpClient.start();//from w w  w.  j  a va  2  s  . co m
        AsyncIdleConnectionMonitorThread asyncIdleConnectionMonitorThread = (AsyncIdleConnectionMonitorThread) options
                .getOption(Option.ASYNC_MONITOR);
        asyncIdleConnectionMonitorThread.start();
    }

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

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

        public boolean cancel(boolean mayInterruptIfRunning) {
            return future.cancel(mayInterruptIfRunning);
        }

        public boolean isCancelled() {
            return future.isCancelled();
        }

        public boolean isDone() {
            return future.isDone();
        }

        public HttpResponse<T> get() throws InterruptedException, ExecutionException {
            org.apache.http.HttpResponse httpResponse = future.get();
            return new HttpResponse<T>(options, httpResponse, responseClass);
        }

        public HttpResponse<T> get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            org.apache.http.HttpResponse httpResponse = future.get(timeout, unit);
            return new HttpResponse<T>(options, httpResponse, responseClass);
        }
    };
}

From source file:org.jboss.windup.decorator.java.decompiler.AsyncDecompilerAdapter.java

@Override
public void decompile(String className, File classLocation, File sourceOutputLocation) {
    DecompilerTask dt = new DecompilerTask(className, classLocation, sourceOutputLocation, decompilerAdapter);
    Future<?> future = executor.submit(dt);
    try {/*from   ww  w .java  2  s  . c o m*/
        Object result = future.get(timeoutSeconds, TimeUnit.SECONDS);
    } catch (TimeoutException ex) {
        LOG.error("Timed out execution of : " + dt.toString());
    } catch (InterruptedException e) {
        LOG.error("Interrupted out execution of : " + dt.toString());
    } catch (ExecutionException e) {
        LOG.error("Execution execution of : " + dt.toString());
    } finally {
        future.cancel(true); // may or may not desire this
    }
}

From source file:com.zuowuxuxi.asihttp.AsyncHttpClient.java

/**
 * Cancels any pending (or potentially active) requests associated with the
 * passed Context.//from   w w  w  .j av  a  2s . c  om
 * <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.
 */
@SuppressWarnings("rawtypes")
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.facebook.presto.jdbc.ApacheQueryHttpClient.java

@Override
public QueryResults execute(URI uri) throws RuntimeException {
    HttpGet request = new HttpGet(uri);
    request.setConfig(requestConfig);/*  w w  w .  j a  v  a 2  s .c  om*/
    request.setHeader(USER_AGENT, userAgent);

    Exception cause = null;
    long start = System.nanoTime();
    long attempts = 0;

    do {
        // back-off on retry
        if (attempts > 0) {
            sleepUninterruptibly(attempts * 100, MILLISECONDS);
        }
        attempts++;

        HttpResponse response;
        Future<HttpResponse> responseFuture = null;
        try {
            responseFuture = httpAsyncClient.execute(request, null);
            response = responseFuture.get();
        } catch (InterruptedException e) {
            try {
                if (responseFuture != null) {
                    responseFuture.cancel(true);
                }
            } finally {
                Thread.currentThread().interrupt();
            }
            throw new RuntimeException("ApacheQueryHttpClient interrupted");
        } catch (ExecutionException e) {
            cause = e;
            continue;
        }

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            return parseResult(request, response);
        }

        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_SERVICE_UNAVAILABLE) {
            throw requestFailedStatus("fetching next", request, response.getStatusLine().getReasonPhrase());
        }
    } while ((System.nanoTime() - start) < MINUTES.toNanos(2) && !isClosed());

    throw new RuntimeException("Error fetching next", cause);
}

From source file:gridool.processors.job.GridJobWorker.java

private void cancelRemainingTasks(final Map<String, Pair<GridTask, List<Future<?>>>> taskMap) {
    for (final Pair<GridTask, List<Future<?>>> entry : taskMap.values()) {
        final List<Future<?>> futures = entry.getSecond();
        assert (futures != null);
        for (final Future<?> future : futures) {
            if (!future.isDone()) {
                // TODO send cancel request
                future.cancel(true);
            }/* ww  w  .  j  av  a 2s  .  com*/
        }
    }
}