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.hive.service.cli.operation.SQLOperation.java

private void cleanup(OperationState state) throws HiveSQLException {
    setState(state);/*from   w  w w . ja  v a2s  .  c o m*/
    if (shouldRunAsync()) {
        Future<?> backgroundHandle = getBackgroundHandle();
        if (backgroundHandle != null) {
            backgroundHandle.cancel(true);
        }
    }
    if (driver != null) {
        driver.close();
        driver.destroy();
    }
    driver = null;

    SessionState ss = SessionState.get();
    if (ss.getTmpOutputFile() != null) {
        ss.getTmpOutputFile().delete();
    }
}

From source file:pl.otros.logview.gui.message.update.MessageUpdateUtils.java

public String formatMessageWithTimeLimit(final String s1, final MessageFormatter messageFormatter,
        int timeoutSeconds) {
    String result = s1;//w  ww .  j a  v  a 2  s  .c  o m
    Callable<String> callable = new Callable<String>() {

        @Override
        public String call() throws Exception {
            ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
            try {
                Thread.currentThread().setContextClassLoader(messageFormatter.getClass().getClassLoader());
                if (messageFormatter.formattingNeeded(s1)) {
                    return messageFormatter.format(s1);
                }
            } catch (Throwable e) {
                LOGGER.severe(String.format("Error occurred when using message formatter %s: %s",
                        messageFormatter.getName(), e.getMessage()));
                LOGGER.fine(String.format("Error occurred when using message formatter %s with message\"%s\"",
                        messageFormatter.getName(), StringUtils.left(s1, 1500)));
            } finally {
                Thread.currentThread().setContextClassLoader(contextClassLoader);
            }
            return s1;
        }
    };

    Future<String> submit = executorService.submit(callable);
    try {
        result = submit.get(timeoutSeconds, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
        String msg = String.format("Formatting message with %s takes to long time, skipping this formatter",
                messageFormatter.getName());
        LOGGER.warning(msg);
        submit.cancel(true);
    } catch (Exception e) {
        LOGGER.severe(String.format("Error occurred when using message formatter %s: %s",
                messageFormatter.getName(), e.getMessage()));
        submit.cancel(true);
    }

    return result;
}

From source file:com.alibaba.otter.node.etl.load.loader.db.FileLoadAction.java

/**
 * ? fast-fail /*w ww  .j  a v  a  2  s  .  c o m*/
 */
private void moveFiles(FileLoadContext context, List<FileData> fileDatas, File rootDir) {
    Exception exception = null;
    adjustPoolSize(context);
    ExecutorCompletionService<Exception> executorComplition = new ExecutorCompletionService<Exception>(
            executor);

    List<Future<Exception>> results = new ArrayList<Future<Exception>>();
    for (FileData fileData : fileDatas) {
        Future<Exception> future = executorComplition.submit(new FileLoadWorker(context, rootDir, fileData));
        results.add(future);

        // fast fail
        if (future.isDone()) { // ( CallerRunsPolicy)
            try {
                exception = future.get();
            } catch (Exception e) {
                exception = e;
            }
            if (exception != null) {
                for (Future<Exception> result : results) {
                    if (!result.isDone() && !result.isCancelled()) {
                        result.cancel(true);
                    }
                }
                throw exception instanceof LoadException ? (LoadException) exception
                        : new LoadException(exception);
            }
        }

    }

    int resultSize = results.size();
    int cursor = 0;
    while (cursor < resultSize) {
        try {
            Future<Exception> result = executorComplition.take();
            exception = result.get();
        } catch (Exception e) {
            exception = e;
            break;
        }
        cursor++;
    }

    if (cursor != resultSize) { // ??
        for (Future<Exception> future : results) {
            if (!future.isDone() && !future.isCancelled()) {
                future.cancel(true);
            }
        }

    }

    if (exception != null) {
        throw exception instanceof LoadException ? (LoadException) exception : new LoadException(exception);
    }
}

From source file:com.jillesvangurp.httpclientfuture.HttpClientWithFutureTest.java

@Test
public void shouldCompleteServerSideAfterCancel() throws Exception {
    // this is quite sensitive to timings, therefore we try several requests and then assert that some requests were allowed to complete.
    int completed = 0;
    for (int i = 0; i < 10; i++) {
        long before = SimpleServlet.counter.get();
        Future<Boolean> future = client
                .execute(new HttpGet(UrlBuilder.url("localhost", port).append("ping").queryParam("sleep", "50")
                        .queryParam("req", "shouldCompleteServerSideAfterCancel_" + i).build()));
        // give httpclient some time to get around to firing the request
        Thread.sleep(20);//from  w  w  w .  j  a  v a  2  s  . co m
        future.cancel(true);
        awaitActiveConnectionsFinished();
        // give response handler some time to wrap things up
        Thread.sleep(20);
        long after = SimpleServlet.counter.get();
        completed += after - before;
    }
    assertThat("some requests should have completed, despite the cancel", completed, greaterThan(2));
}

From source file:org.apache.hive.hcatalog.templeton.JobRequestExecutor.java

private void cancelExecutePoolThread(Future<T> future) {
    int retryCount = 0;
    while (retryCount < this.maxTaskCancelRetryCount && !future.isDone()) {
        LOG.info("Task is still executing the job request. Cancelling it with retry count: " + retryCount);
        if (future.cancel(true)) {
            /*/*from  w ww .  j  a  v a  2 s  .  com*/
             * Cancelled the job request and return to client.
             */
            LOG.info("Cancel job request issued successfully.");
            return;
        }

        retryCount++;
        try {
            Thread.sleep(this.maxTaskCancelRetryWaitTimeInMs);
        } catch (InterruptedException e) {
            /*
             * Nothing to do. Just retry.
             */
        }
    }

    LOG.warn("Failed to cancel the job. isCancelled: " + future.isCancelled() + " Retry count: " + retryCount);
}

From source file:org.apache.solr.handler.component.AlfrescoHttpShardHandler.java

@Override
public void cancelAll() {
    for (Future<ShardResponse> future : pending) {
        // TODO: any issues with interrupting?  shouldn't be if
        // there are finally blocks to release connections.
        future.cancel(true);
    }// www .jav  a  2  s.c  o m
}

From source file:com.hippoapp.asyncmvp.http.AsyncHttpClient.java

/**
 * Cancels any pending (or potentially active) requests associated with the
 * passed Context.//  w w  w . jav a2s  . c o m
 * <p>
 * TODO delete under comment <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:pl.otros.logview.gui.message.update.MessageUpdateUtils.java

public Collection<MessageFragmentStyle> colorizeMessageWithTimeLimit(final String message,
        final int messageStartOffset, final MessageColorizer messageColorizer, int timeoutSeconds) {

    Callable<Collection<MessageFragmentStyle>> callable = new Callable<Collection<MessageFragmentStyle>>() {
        @Override//from   www .java 2  s  .c om
        public Collection<MessageFragmentStyle> call() throws Exception {
            Collection<MessageFragmentStyle> list = new ArrayList<MessageFragmentStyle>();
            ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
            try {
                Thread.currentThread().setContextClassLoader(messageColorizer.getClass().getClassLoader());
                if (messageColorizer.colorizingNeeded(message)) {
                    Collection<MessageFragmentStyle> colorize = messageColorizer.colorize(message);
                    for (MessageFragmentStyle messageFragmentStyle : colorize) {
                        messageFragmentStyle.setOffset(messageFragmentStyle.getOffset() + messageStartOffset);
                    }
                    list.addAll(colorize);
                }
            } catch (Throwable e) {
                LOGGER.log(Level.SEVERE, String.format("Error occurred when using message colorizer %s: %s%n%s",
                        messageColorizer.getName(), e.getMessage()), e);
                LOGGER.fine(String.format("Error occurred when using message colorizer %s with message\"%s\"",
                        messageColorizer.getName(), StringUtils.left(message, 1500)));
                e.printStackTrace();
            } finally {
                Thread.currentThread().setContextClassLoader(contextClassLoader);
            }
            return list;
        }
    };

    Future<Collection<MessageFragmentStyle>> submit = executorService.submit(callable);
    try {
        return submit.get(timeoutSeconds, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
        String msg = String.format("Formatting message with %s takes to long time, skipping this formatter",
                messageColorizer.getName());
        LOGGER.warning(msg);
        submit.cancel(true);
    } catch (Exception e) {
        LOGGER.severe(String.format("Error occurred when using message formatter %s: %s",
                messageColorizer.getName(), e.getMessage()));
        submit.cancel(true);
    }
    return new ArrayList<MessageFragmentStyle>(0);
}

From source file:com.orange.clara.cloud.servicedbdumper.integrations.AbstractIntegrationWithRealCfClientTest.java

public boolean isFinishedCreatingService(CloudService cloudService) {

    ExecutorService executor = Executors.newCachedThreadPool();
    Callable<Boolean> task = () -> {
        while (true) {
            CloudService cloudServiceFound = cfClientToPopulate.getService(cloudService.getName());
            if (cloudServiceFound.getCloudServiceLastOperation() == null) {
                return true;
            }//ww w  . jav a2s  .com
            logger.info("State for service '{}' : {}", cloudServiceFound,
                    cloudServiceFound.getCloudServiceLastOperation().getState());
            switch (cloudServiceFound.getCloudServiceLastOperation().getState()) {
            case "succeeded":
                return true;
            case "in progress":
                break;
            case "failed":
            case "internal error":
                return false;
            }
            Thread.sleep(5000L);// we yield the task for 5seconds to let the service do is work (actually, Cloud Controller hit getServiceInstance every 30sec)
        }
    };
    Future<Boolean> future = executor.submit(task);
    try {
        Boolean result = future.get(timeoutCreatingService, TimeUnit.MINUTES);
        return result;
    } catch (Exception ex) {
        ex.printStackTrace();
        future.cancel(true);
        fail("Timeout reached.", ex);
    }
    return false;
}