Example usage for java.util.concurrent Future isCancelled

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

Introduction

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

Prototype

boolean isCancelled();

Source Link

Document

Returns true if this task was cancelled before it completed normally.

Usage

From source file:eu.europa.ec.fisheries.uvms.plugins.ais.service.AisService.java

@PreDestroy
public void destroy() {
    if (connection != null) {
        connection.close();/*ww  w.  ja  v  a 2 s  .com*/
    }
    Iterator<Future<Long>> processIterator = processes.iterator();
    while (processIterator.hasNext()) {
        Future<Long> process = processIterator.next();
        if (process.isDone() || process.isCancelled()) {
            processIterator.remove();
        } else {
            process.cancel(true);
        }
    }
}

From source file:com.company.project.service.TaskSchedulerService.java

@Scheduled(fixedRate = 60000)
public void schedulerFixedRate() {
    System.out.println("schedulerFixedRate. Current time is :: " + new Date());

    // spring managed thread
    TaskExample taskExample = new TaskExample();
    taskExample.setName("Thread 1");
    taskExecutor.execute(taskExample);//from   www.  j  a v a2  s  .  c  o m

    asyncMethod();

    taskExample = new TaskExample();
    taskExample.setName("Thread 2");
    taskExecutor.execute(taskExample);

    taskExample = new TaskExample();
    taskExample.setName("Thread 3");
    Future future = taskExecutor.submit(taskExample);
    System.out.println("Thread 3 future.isCancelled() :: " + future.isCancelled());
    System.out.println("Thread 3 future.isDone() :: " + future.isDone());
    while (!future.isDone()) {
        try {
            Thread.sleep(1000);
        } catch (Exception e) {
        }
    }
    System.out.println("Thread 3 future.isDone() :: " + future.isDone()); // future.isDone() = true

    AsyncTask asyncTask = new AsyncTask();
    asyncTask.doAsyncTask();
}

From source file:eu.europa.ec.fisheries.uvms.plugins.ais.service.AisService.java

@Schedule(minute = "*/1", hour = "*", persistent = false)
public void connectAndRetrive() {
    if (!startUp.isEnabled()) {
        return;//  w ww  .j a va 2 s.co  m
    }
    if (connection != null && !connection.isOpen()) {
        String host = startUp.getSetting("HOST");
        int port = Integer.parseInt(startUp.getSetting("PORT"));
        String username = startUp.getSetting("USERNAME");
        String password = startUp.getSetting("PASSWORD");

        connection.open(host, port, username, password);
    }

    if (connection != null && connection.isOpen()) {
        Iterator<Future<Long>> processIterator = processes.iterator();
        while (processIterator.hasNext()) {
            Future<Long> process = processIterator.next();
            if (process.isDone() || process.isCancelled()) {
                processIterator.remove();
            }
        }
        List<String> sentences = connection.getSentences();
        Future<Long> process = processService.processMessages(sentences);
        processes.add(process);
        LOG.info("Got {} sentences from AIS RA. Currently running {} parallel threads", sentences.size(),
                processes.size());
    }
}

From source file:com.ejisto.modules.executor.TaskManager.java

private ExecutionState getExecutionState(Future<?> future) {
    if (future.isCancelled()) {
        return ExecutionState.CANCELED;
    }/*from  w  ww .  java2  s .  c  o m*/
    if (future.isDone()) {
        return ExecutionState.DONE;
    }
    return ExecutionState.RUNNING;
}

From source file:com.creactiviti.piper.core.Worker.java

/**
 * Handle the execution of a {@link TaskExecution}. Implementors
 * are expected to execute the task asynchronously. 
 * /* w  ww .  j a  va 2  s . c  o m*/
 * @param aTask
 *          The task to execute.
 */
public void handle(TaskExecution aTask) {
    Future<?> future = executors.submit(() -> {
        try {
            long startTime = System.currentTimeMillis();
            logger.debug("Recived task: {}", aTask);
            TaskHandler<?> taskHandler = taskHandlerResolver.resolve(aTask);
            eventPublisher.publishEvent(
                    PiperEvent.of(Events.TASK_STARTED, "taskId", aTask.getId(), "jobId", aTask.getJobId()));
            Object output = taskHandler.handle(aTask);
            SimpleTaskExecution completion = SimpleTaskExecution.createForUpdate(aTask);
            if (output != null) {
                if (completion.getOutput() != null) {
                    TaskExecution evaluated = taskEvaluator.evaluate(completion,
                            new MapContext("execution", new MapContext("output", output)));
                    completion = SimpleTaskExecution.createForUpdate(evaluated);
                } else {
                    completion.setOutput(output);
                }
            }
            completion.setStatus(TaskStatus.COMPLETED);
            completion.setProgress(100);
            completion.setEndTime(new Date());
            completion.setExecutionTime(System.currentTimeMillis() - startTime);
            messenger.send(Queues.COMPLETIONS, completion);
        } catch (InterruptedException e) {
            // ignore
        } catch (Exception e) {
            Future<?> myFuture = taskExecutions.get(aTask.getId());
            if (!myFuture.isCancelled()) {
                handleException(aTask, e);
            }
        } finally {
            taskExecutions.remove(aTask.getId());
        }
    });

    taskExecutions.put(aTask.getId(), future);

    try {
        future.get(calculateTimeout(aTask), TimeUnit.MILLISECONDS);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        handleException(aTask, e);
    } catch (CancellationException e) {
        logger.debug("Cancelled task: {}", aTask.getId());
    }

}

From source file:com.flipkart.poseidon.serviceclients.FutureTaskResultToDomainObjectPromiseWrapper.java

@Override
public boolean isFullfilled() throws IllegalStateException {
    for (Future<TaskResult> future : futureList) {
        if (future.isCancelled()) {
            return false;
        }//  w  w  w.ja  va  2 s.  c o  m
    }
    return true;
}

From source file:com.flipkart.poseidon.serviceclients.FutureTaskResultToDomainObjectPromiseWrapper.java

@Override
public boolean isBroken() throws IllegalStateException {
    for (Future<TaskResult> future : futureList) {
        if (future.isCancelled()) {
            return true;
        }//from  w  w  w .  j  a v a2 s.c o  m
    }
    return false;
}

From source file:com.ejisto.modules.executor.TaskManager.java

private void refreshTasksList() {
    if (!lock.tryLock()) {
        return;//from  w  w w .  j ava  2  s  .  co m
    }
    try {
        registry.entrySet().stream().filter(e -> {
            Future<?> future = e.getValue().getFuture();
            return future.isCancelled() || future.isDone();
        }).collect(toList()).forEach(e -> registry.remove(e.getKey(), e.getValue()));
    } finally {
        lock.unlock();
    }

}

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

@Test(invocationCount = 3)
public void shouldInvokeMultiple() throws ExecutionException, TimeoutException {
    long before = SimpleServlet.counter.get();
    HttpGet req1 = new HttpGet(UrlBuilder.url("localhost", port).append("ping").queryParam("sleep", "10")
            .queryParam("req", "shouldInvokeMultiple_1").build());
    HttpGet req2 = new HttpGet(UrlBuilder.url("localhost", port).append("ping").queryParam("sleep", "10")
            .queryParam("req", "shouldInvokeMultiple_2").build());
    HttpGet req3 = new HttpGet(UrlBuilder.url("localhost", port).append("ping").queryParam("sleep", "3000")
            .queryParam("req", "shouldInvokeMultiple_3").build());
    try {//from w  w  w. ja v  a 2 s .  c om
        List<Future<Boolean>> futures = client.executeMultiple(null, 100, TimeUnit.MILLISECONDS, req1, req2,
                req3);
        int cancelled = 0;
        for (Future<Boolean> future : futures) {
            if (future.isCancelled()) {
                cancelled++;
            } else {
                boolean done = future.isDone();
                if (done) {
                    future.get(1, TimeUnit.MILLISECONDS);
                }

            }
        }
        assertThat(cancelled, is(1));
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    long after = SimpleServlet.counter.get();
    assertThat(after, is(before + 2));
}

From source file:com.amazon.alexa.avs.NotificationManager.java

private void cleanUpIndicatorFutures() {
    synchronized (indicatorFutures) {
        Iterator<Future<?>> it = indicatorFutures.iterator();
        while (it.hasNext()) {
            Future<?> f = it.next();
            if (f.isDone() || f.isCancelled()) {
                it.remove();//  ww w.j av a 2  s  . co m
            }
        }
    }
}