Java Code Examples for java.util.concurrent.Future#isCancelled()

The following examples show how to use java.util.concurrent.Future#isCancelled() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: Bats   File: DataList.java    License: Apache License 2.0 6 votes vote down vote up
private void moreDataAvailable()
{
  final Future<?> future = this.future;
  if (future == null || future.isDone() || future.isCancelled()) {
    // Do not schedule a new task if there is an existing one that is still running or is waiting in the queue
    this.future = autoFlushExecutor.submit(this);
  } else {
    synchronized (this) {
      if (this.future == null) {
        // future is set to null before run() exists, no need to check whether future isDone() or isCancelled()
        this.future = autoFlushExecutor.submit(this);
      } else {
        isMoreDataAvailable = true;
      }
    }
  }
}
 
Example 2
Source Project: Java-9-Cookbook   File: Chapter07Concurrency03.java    License: MIT License 6 votes vote down vote up
private static void printResults(List<Future<Result>> futures, int timeoutSec) {
    System.out.println("Results from futures:");
    if (futures == null || futures.size() == 0) {
        System.out.println("No results. Futures" + (futures == null ? " = null" : ".size()=0"));
    } else {
        for (Future<Result> future : futures) {
            try {
                if (future.isCancelled()) {
                    System.out.println("Worker is cancelled.");
                } else {
                    Result result = future.get(timeoutSec, TimeUnit.SECONDS);
                    System.out.println("Worker " + result.getWorkerName() + " slept "
                            + result.getSleepSec() + " sec. Result = " + result.getResult());
                }
            } catch (Exception ex) {
                System.out.println("Caught while getting result: " + ex.getClass().getName());
            }
        }
    }
}
 
Example 3
@Override
protected void afterExecute(final Runnable r, Throwable t) {
    super.afterExecute(r, t);
    if (t == null && r instanceof Future<?>) {
        try {
            final Future<?> future = (Future<?>) r;
            if (future.isDone() && !future.isCancelled()) {
                future.get();
            }
        } catch (final CancellationException ce) {
            t = ce;
        } catch (final ExecutionException ee) {
            t = ee.getCause();
        } catch (final InterruptedException ie) {
            Thread.currentThread().interrupt();
        }
    }
    if (t != null) {
        t.printStackTrace();
    }
}
 
Example 4
Source Project: paraflow   File: ProcessPipeline.java    License: Apache License 2.0 6 votes vote down vote up
void start()
{
    for (Processor processor : processors) {
        for (int i = 0; i < processor.getParallelism(); i++) {
            RunningProcessor runningProcessor = new RunningProcessor(processor);
            futures.add(executorService.submit(runningProcessor));
            runningProcessors.add(runningProcessor);
        }
    }
    logger.info("Loading pipeline started.");
    int finishedProcessors = 0;
    while (finishedProcessors < futures.size()) {
        for (Future future : futures) {
            if (future.isDone() || future.isCancelled()) {
                try {
                    future.get();
                }
                catch (InterruptedException | ExecutionException e) {
                    // todo deal with execution exceptions
                    e.printStackTrace();
                }
                finishedProcessors++;
            }
        }
    }
}
 
Example 5
Source Project: phoebus   File: ExecutableScan.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/** Abort scan
 *  @param previous Previous state from `prepareAbort()`
 */
public void doAbort(final ScanState previous)
{
    if (previous.isDone())
        return;
    logger.log(Level.INFO, "Abort " + this + " (" + previous + ")");

    // Interrupt, except when already aborted, failed, ..
    // to prevent interruption when in the middle of updating scan state PVs
    final Future<Object> save = future.orElse(null);
    if (save != null  &&  ! save.isCancelled())
    {
        final boolean interrupt = previous == ScanState.Idle    ||
                                  previous == ScanState.Running ||
                                  previous == ScanState.Paused;
        save.cancel(interrupt);
        if (interrupt)
            logger.log(Level.INFO, "Interrupted " + this);
        else
            logger.log(Level.INFO, "Cancelled " + this);
    }
    synchronized (this)
    {
        notifyAll();
    }
}
 
Example 6
private static void demo1_Executor1() {
    System.out.println();
    int shutdownDelaySec = 1;
    ExecutorService execService = Executors.newSingleThreadExecutor();
    Runnable runnable = () -> System.out.println("Worker One did the job.");
    execService.execute(runnable);
    runnable = () -> System.out.println("Worker Two did the job.");
    Future future = execService.submit(runnable);
    try {
        execService.shutdown();
        execService.awaitTermination(shutdownDelaySec, TimeUnit.SECONDS);
    } catch (Exception ex) {
        System.out.println("Caught around execService.awaitTermination(): " + ex.getClass().getName());
    } finally {
        if (!execService.isTerminated()) {
            if (future != null && !future.isDone() && !future.isCancelled()) {
                System.out.println("Cancelling the task...");
                future.cancel(true);
            }
        }
        List<Runnable> l = execService.shutdownNow();
        System.out.println(l.size() + " tasks were waiting to be executed. Service stopped.");
    }
}
 
Example 7
private static void shutdownAndCancelTask(ExecutorService execService, int shutdownDelaySec, String name, Future future) {
    try {
        execService.shutdown();
        System.out.println("Waiting for " + shutdownDelaySec + " sec before shutting down service...");
        execService.awaitTermination(shutdownDelaySec, TimeUnit.SECONDS);
    } catch (Exception ex) {
        System.out.println("Caught around execService.awaitTermination(): " + ex.getClass().getName());
    } finally {
        if (!execService.isTerminated()) {
            System.out.println("Terminating remaining running tasks...");
            if (future != null && !future.isDone() && !future.isCancelled()) {
                System.out.println("Cancelling task " + name + "...");
                future.cancel(true);
            }
        }
        System.out.println("Calling execService.shutdownNow()...");
        List<Runnable> l = execService.shutdownNow();
        System.out.println(l.size() + " tasks were waiting to be executed. Service stopped.");
    }
}
 
Example 8
Source Project: Java-9-Cookbook   File: Chapter07Concurrency03.java    License: MIT License 6 votes vote down vote up
private static void shutdownAndCancelTasks(ExecutorService execService, int shutdownDelaySec, List<Future<Result>> futures) {
    try {
        execService.shutdown();
        System.out.println("Waiting for " + shutdownDelaySec + " sec before shutting down service...");
        execService.awaitTermination(shutdownDelaySec, TimeUnit.SECONDS);
    } catch (Exception ex) {
        System.out.println("Caught around execService.awaitTermination(): " + ex.getClass().getName());
    } finally {
        if (!execService.isTerminated()) {
            System.out.println("Terminating remaining running tasks...");
            for (Future<Result> future : futures) {
                if (future.isDone() && !future.isCancelled()) {
                    System.out.println("Cancelling task...");
                    future.cancel(true);
                }
            }
        }
        System.out.println("Calling execService.shutdownNow()...");
        List<Runnable> l = execService.shutdownNow();
        System.out.println(l.size() + " tasks were waiting to be executed. Service stopped.");
    }
}
 
Example 9
Source Project: Java-9-Cookbook   File: Chapter07Concurrency03.java    License: MIT License 6 votes vote down vote up
private static void shutdownAndCancelTask(ExecutorService execService, int shutdownDelaySec, String name, Future future) {
    try {
        execService.shutdown();
        System.out.println("Waiting for " + shutdownDelaySec + " sec before shutting down service...");
        execService.awaitTermination(shutdownDelaySec, TimeUnit.SECONDS);
    } catch (Exception ex) {
        System.out.println("Caught around execService.awaitTermination(): " + ex.getClass().getName());
    } finally {
        if (!execService.isTerminated()) {
            System.out.println("Terminating remaining running tasks...");
            if (future != null && !future.isDone() && !future.isCancelled()) {
                System.out.println("Cancelling task " + name + "...");
                future.cancel(true);
            }
        }
        System.out.println("Calling execService.shutdownNow()...");
        List<Runnable> l = execService.shutdownNow();
        System.out.println(l.size() + " tasks were waiting to be executed. Service stopped.");
    }
}
 
Example 10
Source Project: Java-9-Cookbook   File: Chapter07Concurrency03.java    License: MIT License 6 votes vote down vote up
private static void demo1_Executor1() {
    System.out.println();
    int shutdownDelaySec = 1;
    ExecutorService execService = Executors.newSingleThreadExecutor();
    Runnable runnable = () -> System.out.println("Worker One did the job.");
    execService.execute(runnable);
    runnable = () -> System.out.println("Worker Two did the job.");
    Future future = execService.submit(runnable);
    try {
        execService.shutdown();
        execService.awaitTermination(shutdownDelaySec, TimeUnit.SECONDS);
    } catch (Exception ex) {
        System.out.println("Caught around execService.awaitTermination(): " + ex.getClass().getName());
    } finally {
        if (!execService.isTerminated()) {
            if (future != null && !future.isDone() && !future.isCancelled()) {
                System.out.println("Cancelling the task...");
                future.cancel(true);
            }
        }
        List<Runnable> l = execService.shutdownNow();
        System.out.println(l.size() + " tasks were waiting to be executed. Service stopped.");
    }
}
 
Example 11
public static void demoFutureWithCallable() throws InterruptedException, ExecutionException {
	System.out.println();
	System.out.println("Demo Future with Callable");
	ExecutorService pool = Executors.newCachedThreadPool();

	Future<Pizza> pizzaPickupOrder = pool.submit(() -> {
		System.out.println("   Restaurant> Slicing tomatoes");
		System.out.println("   Restaurant> Chopping onions");
		System.out.println("   Restaurant> Spreading with tomato sauce and sprinkle with toppings");
		System.out.println("   Restaurant> Baking pizza");
		TimeUnit.MILLISECONDS.sleep(300);
		return new Pizza();
	});

	System.out.println("Me: Call my brother");
	TimeUnit.MILLISECONDS.sleep(200);
	System.out.println("Me: Walk the dog");

	// Try this: pizzaPickupOrder.cancel(true);
	if (pizzaPickupOrder.isCancelled()) {
		System.out.println("Me: pizza is cancelled, order something else");
		System.out.println("pizzaPickupOrder.isDone(): " + pizzaPickupOrder.isDone());
	} else if (!pizzaPickupOrder.isDone()) {
		System.out.println("Me: Watch a TV show");
	}
	Pizza pizza = pizzaPickupOrder.get();

	System.out.println("Me: Eat the pizza: " + pizza);

	pool.shutdown();
	System.out.println();
	System.out.println();
}
 
Example 12
Source Project: ProjectStudy   File: AsyncController.java    License: MIT License 5 votes vote down vote up
/**
 * 多个异步执行
 *
 * @param
 * @return java.lang.String
 * @throws
 * @author wliduo[[email protected]]
 * @date 2020/5/20 10:26
 */
@GetMapping("/run3")
public String run3() throws Exception {
    logger.info("run3开始执行");
    long start = System.currentTimeMillis();
    Future<String> future3 = asyncService.task3();
    Future<String> future4 = asyncService.task4();
    // 这样与下面是一样的
    logger.info(future3.get());
    logger.info(future4.get());
    // 先判断是否执行完成
    boolean run3Done = Boolean.FALSE;
    while (true) {
        if (future3.isDone() && future4.isDone()) {
            // 执行完成
            run3Done = Boolean.TRUE;
            break;
        }
        if (future3.isCancelled() || future4.isCancelled()) {
            // 取消情况
            break;
        }
    }
    if (run3Done) {
        logger.info(future3.get());
        logger.info(future4.get());
    } else {
        // 其他异常情况
    }
    long end = System.currentTimeMillis();
    logger.info("run3执行完成,执行时间: {}", end - start);
    return "run3 success";
}
 
Example 13
Source Project: rqueue   File: MessageScheduler.java    License: Apache License 2.0 5 votes vote down vote up
private void waitForRunningQueuesToStop() {
  for (Map.Entry<String, Boolean> runningState : queueRunningState.entrySet()) {
    String queueName = runningState.getKey();
    ScheduledTaskDetail scheduledTaskDetail = queueNameToScheduledTask.get(queueName);
    if (scheduledTaskDetail != null) {
      Future<?> future = scheduledTaskDetail.getFuture();
      boolean completedOrCancelled = future.isCancelled() || future.isDone();
      if (!completedOrCancelled) {
        future.cancel(true);
      }
    }
  }
}
 
Example 14
/**
 * Count the number of active sub tasks.
 */
public synchronized int numActiveSubTasks() {
    int c = 0;
    for (Future<?> f : subTasks) {
        if (!f.isDone() && !f.isCancelled()) {
            c++;
        }
    }
    return c;
}
 
Example 15
/**
 * Count the number of active sub tasks.
 */
public synchronized int numActiveSubTasks() {
    int c = 0;
    for (Future<?> f : subTasks) {
        if (!f.isDone() && !f.isCancelled()) {
            c++;
        }
    }
    return c;
}
 
Example 16
void assertCancelled(Future<?> future) throws Exception {
    if (!future.isDone())
        throw new AssertionError("not done");
    if (!future.isCancelled())
        throw new AssertionError("not cancelled");
    try {
        future.get(LONG_DELAY_MS, MILLISECONDS);
        throw new AssertionError("should throw CancellationException");
    } catch (CancellationException success) {}
}
 
Example 17
Source Project: java-unified-sdk   File: QCloudUploader.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void interruptImmediately() {
  super.interruptImmediately();

  if (tasks != null && tasks.length > 0) {
    synchronized (tasks) {
      for (int index = 0; index < tasks.length; index++) {
        Future task = tasks[index];
        if (task != null && !task.isDone() && !task.isCancelled()) {
          task.cancel(true);
        }
      }
    }
  }
}
 
Example 18
Source Project: sailfish-core   File: AsyncScriptRunner.java    License: Apache License 2.0 5 votes vote down vote up
private void resultScript(Map<Long, Future<Exception>> runningScriptMap) throws InterruptedException {
	Iterator<Entry<Long, Future<Exception>>> iterator = runningScriptMap.entrySet().iterator();

	while (iterator.hasNext()) {
		Entry<Long, Future<Exception>> scriptFeature = iterator.next();
		Future<Exception> future = scriptFeature.getValue();

		if (future.isDone()) {
			iterator.remove();
			Long currentTestScript = scriptFeature.getKey();
			TestScriptDescription descr = testScripts.get(currentTestScript);
			unlockServices(descr);

			Throwable result;
			try {
				result = future.get();
			} catch (Exception e) {
				logger.warn("Interrupt of matrix execution, reason : {}", e.getMessage(), e);
				result = e;
			}

			if (future.isCancelled()) {
				descr.scriptInterrupted();
			} else if (result != null) {
				descr.scriptRunFailed(result);
			} else {
				descr.scriptExecuted();
			}
                  onRunFinished(descr);

			logger.info("TestScript {} was executed", currentTestScript);
		}
	}
}
 
Example 19
Source Project: jpeek   File: AsyncReports.java    License: MIT License 4 votes vote down vote up
@Override
public Func<String, Response> apply(final String group,
    final String artifact) throws IOException {
    final Future<Func<String, Response>> future = new IoCheckedBiFunc<>(
        this.cache
    ).apply(group, artifact);
    final Func<String, Response> output;
    if (future.isCancelled()) {
        output = input -> new RsPage(
            new RqFake(),
            "error",
            () -> new IterableOf<>(
                new XeAppend("group", group),
                new XeAppend("artifact", artifact),
                new XeAppend("future", future.toString())
            )
        );
    } else if (future.isDone()) {
        try {
            output = future.get();
        } catch (final InterruptedException | ExecutionException ex) {
            throw new IllegalStateException(ex);
        }
    } else {
        final long msec = System.currentTimeMillis()
            - this.starts.computeIfAbsent(
                String.format("%s:%s", group, artifact),
                s -> System.currentTimeMillis()
            );
        output = input -> new RsWithStatus(
            new RsPage(
                new RqFake(),
                "wait",
                () -> new IterableOf<>(
                    new XeAppend("group", group),
                    new XeAppend("artifact", artifact),
                    new XeAppend("future", future.toString()),
                    new XeAppend("msec", Long.toString(msec)),
                    new XeAppend(
                        "spent",
                        Logger.format("%[ms]s", msec)
                    )
                )
            ),
            HttpURLConnection.HTTP_NOT_FOUND
        );
    }
    return output;
}
 
Example 20
private boolean cancelTimeoutTask(Branch branch) {
    Future timeoutTaskFuture = branch.getTimeoutTaskFuture();
    return Objects.isNull(timeoutTaskFuture)
            || timeoutTaskFuture.isCancelled()
            || timeoutTaskFuture.cancel(false);
}