本文整理了Java中java.util.concurrent.Future.cancel()
方法的一些代码示例,展示了Future.cancel()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Future.cancel()
方法的具体详情如下:
包路径:java.util.concurrent.Future
类名称:Future
方法名:cancel
[英]Attempts to cancel execution of this task. This attempt will fail if the task has already completed, has already been cancelled, or could not be cancelled for some other reason. If successful, and this task has not started when cancel is called, this task should never run. If the task has already started, then the mayInterruptIfRunning parameter determines whether the thread executing this task should be interrupted in an attempt to stop the task.
After this method returns, subsequent calls to #isDone will always return true. Subsequent calls to #isCancelledwill always return true if this method returned true.
[中]试图取消此任务的执行。如果任务已完成、已取消或由于其他原因无法取消,则此尝试将失败。如果成功,并且调用cancel时此任务尚未启动,则此任务不应运行。如果任务已经启动,则MayInterruptFrunning参数确定执行此任务的线程是否应该中断以尝试停止任务。
此方法返回后,对#isDone的后续调用将始终返回true。如果此方法返回true,则对#iscancelled的后续调用将始终返回true。
代码示例来源:origin: apache/ignite
/**
* Stops the process.
*/
public synchronized void stop() {
if (fut != null && !fut.isDone())
fut.cancel(true);
}
代码示例来源:origin: Netflix/eureka
/* visible for testing */ boolean doWarmUp() {
Future future = null;
try {
future = threadPoolExecutor.submit(updateTask);
future.get(warmUpTimeoutMs, TimeUnit.MILLISECONDS); // block until done or timeout
return true;
} catch (Exception e) {
logger.warn("Best effort warm up failed", e);
} finally {
if (future != null) {
future.cancel(true);
}
}
return false;
}
代码示例来源:origin: google/guava
@Override
public void runWithTimeout(Runnable runnable, long timeoutDuration, TimeUnit timeoutUnit)
throws TimeoutException, InterruptedException {
checkNotNull(runnable);
checkNotNull(timeoutUnit);
checkPositiveTimeout(timeoutDuration);
Future<?> future = executor.submit(runnable);
try {
future.get(timeoutDuration, timeoutUnit);
} catch (InterruptedException | TimeoutException e) {
future.cancel(true /* mayInterruptIfRunning */);
throw e;
} catch (ExecutionException e) {
wrapAndThrowRuntimeExecutionExceptionOrError(e.getCause());
throw new AssertionError();
}
}
代码示例来源:origin: apache/activemq
final String[] signature = strings;
Future<Object> task = executor.submit(new Callable<Object>() {
return task.get(timeout, TimeUnit.MILLISECONDS);
} catch (ExecutionException e) {
if (e.getCause() instanceof MBeanException) {
throw new MBeanException(e);
} finally {
if (!task.isDone()) {
task.cancel(true);
代码示例来源:origin: google/guava
Iterator<? extends Callable<T>> it = tasks.iterator();
futures.add(submitAndAddQueueListener(executorService, it.next(), futureQueue));
--ntasks;
int active = 1;
if (ntasks > 0) {
--ntasks;
futures.add(submitAndAddQueueListener(executorService, it.next(), futureQueue));
++active;
} else if (active == 0) {
--active;
try {
return f.get();
} catch (ExecutionException eex) {
ee = eex;
} finally {
for (Future<T> f : futures) {
f.cancel(true);
代码示例来源:origin: debezium/debezium
Semaphore latch = new Semaphore(0);
Metronome metronome = Metronome.sleeper(50, TimeUnit.MILLISECONDS, Clock.SYSTEM);
Future<?> result = executorService.submit(() -> {
while (!Thread.interrupted()) {
for(;;) {
List<ReplicationMessage> message = new ArrayList<>();
stream.readPending(x -> message.add(x));
if (message.isEmpty()) {
break;
result.cancel(true);
fail("expected " + expectedMessages + " messages, but read only " + actualMessages.size());
代码示例来源:origin: stackoverflow.com
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new Task());
System.out.println("Started..");
System.out.println(future.get(3, TimeUnit.SECONDS));
System.out.println("Finished!");
} catch (TimeoutException e) {
future.cancel(true);
System.out.println("Terminated!");
代码示例来源:origin: apache/incubator-gobblin
if (fork.get().isSucceeded()) {
if (!fork.get().commit()) {
failedForkIds.add(fork.get().getIndex());
failedForkIds.add(fork.get().getIndex());
if (forkAndFuture.getKey().isPresent() && forkAndFuture.getValue().isPresent()) {
try {
forkAndFuture.getValue().get().cancel(true);
} catch (Throwable t) {
LOG.error(String.format("Failed to cancel Fork \"%s\"", forkAndFuture.getKey().get()), t);
代码示例来源:origin: PipelineAI/pipeline
Future<?> metricsPoller = threadPool.submit(new Runnable() {
@Override
public void run() {
threadPool.submit(new Runnable() {
@Override
public void run() {
metricsPoller.cancel(true);
} catch (InterruptedException ex) {
fail("Timeout on all threads writing percentiles");
System.out.println(p.getMean() + " : " + p.getPercentile(50) + " : " + p.getPercentile(75) + " : " + p.getPercentile(90) + " : " + p.getPercentile(95) + " : " + p.getPercentile(99));
代码示例来源:origin: stackoverflow.com
for (Future<String> f : result) {
try {
parsedValue = f.get();
System.out.println("Return Value - " + parsedValue);
} catch (CancellationException e) {
System.out.println("Cancelled");
parsedValue = "";
f.cancel(true);
}
}
executor.shutdownNow();
代码示例来源:origin: stackoverflow.com
public static void main(String[] args) throws InterruptedException {
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Hello");
}
};
ScheduledFuture<?> scheduledFuture =
scheduledExecutorService.scheduleAtFixedRate(r, 1L, 1L, TimeUnit.SECONDS);
Thread.sleep(5000L);
scheduledFuture.cancel(false);
}
代码示例来源:origin: apache/incubator-druid
private static void checkCombineFutures(List<Future> combineFutures)
{
for (Future future : combineFutures) {
try {
if (!future.isDone()) {
// Cancel futures if close() for the iterator is called early due to some reason (e.g., test failure)
future.cancel(true);
} else {
future.get();
}
}
catch (InterruptedException | CancellationException e) {
throw new QueryInterruptedException(e);
}
catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
}
代码示例来源:origin: google/guava
@Override
public void runUninterruptiblyWithTimeout(
Runnable runnable, long timeoutDuration, TimeUnit timeoutUnit) throws TimeoutException {
checkNotNull(runnable);
checkNotNull(timeoutUnit);
checkPositiveTimeout(timeoutDuration);
Future<?> future = executor.submit(runnable);
try {
Uninterruptibles.getUninterruptibly(future, timeoutDuration, timeoutUnit);
} catch (TimeoutException e) {
future.cancel(true /* mayInterruptIfRunning */);
throw e;
} catch (ExecutionException e) {
wrapAndThrowRuntimeExecutionExceptionOrError(e.getCause());
throw new AssertionError();
}
}
代码示例来源:origin: sarxos/webcam-capture
futures.add(executor.submit(new DeviceOnlineCheck(device, latch)));
if (!latch.await(scanTimeout, TimeUnit.MILLISECONDS)) {
for (Future<IpCamDevice> future : futures) {
if (!future.isDone()) {
future.cancel(true);
if ((device = future.get()) != null) {
online.add(device);
代码示例来源:origin: google/j2objc
Iterator<? extends Callable<T>> it = tasks.iterator();
futures.add(submitAndAddQueueListener(executorService, it.next(), futureQueue));
--ntasks;
int active = 1;
if (ntasks > 0) {
--ntasks;
futures.add(submitAndAddQueueListener(executorService, it.next(), futureQueue));
++active;
} else if (active == 0) {
--active;
try {
return f.get();
} catch (ExecutionException eex) {
ee = eex;
} finally {
for (Future<T> f : futures) {
f.cancel(true);
代码示例来源:origin: wildfly/wildfly
System.out.println("Original Numbers: " +
Arrays.toString(numbers));
if (--futureNumber >= 1) {
Future<ByteBufferStreamable> result2 = completion.take();
completion.submit(new SortingTwoByteCallable(result.get(), result2.get()));
ByteBufferStreamable results = finalValue.get();
System.out.println("Sorted values: " + Arrays.toString(
results.buffer.array()));
System.out.println("Distributed Sort Took: " + Util.printTime(totalDistributed, TimeUnit.NANOSECONDS));
queue.add(executor.submit(runner));
System.out.println("Started Consumer - running " + queue.size() + " consumers");
queue.remove().cancel(true);
System.out.println("Stopped Consumer - running " + queue.size() + " consumers");
代码示例来源:origin: stackoverflow.com
ThreadGroup systemThreadGroup = mainThreadGroup.getParent();
System.out.println("\n" + Thread.currentThread());
systemThreadGroup.list();
System.out.println(selection);
if (gameTask != null) gameTask.cancel(true);
gameTask = gameExecutor.submit(new Runnable() {
public void run() {
play();
代码示例来源:origin: stackoverflow.com
Future<Long> futureResult = service.execute(myCallable);
Long result = null;
try{
result = futureResult.get(5000, TimeUnit.MILLISECONDS);
}catch(TimeoutException e){
System.out.println("Time out after 5 seconds");
futureResult.cancel(true);
}catch(InterruptedException ie){
System.out.println("Error: Interrupted");
}catch(ExecutionException ee){
System.out.println("Error: Execution interrupted");
}
代码示例来源:origin: google/guava
@CanIgnoreReturnValue
@Override
public <T> T callWithTimeout(Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit)
throws TimeoutException, InterruptedException, ExecutionException {
checkNotNull(callable);
checkNotNull(timeoutUnit);
checkPositiveTimeout(timeoutDuration);
Future<T> future = executor.submit(callable);
try {
return future.get(timeoutDuration, timeoutUnit);
} catch (InterruptedException | TimeoutException e) {
future.cancel(true /* mayInterruptIfRunning */);
throw e;
} catch (ExecutionException e) {
wrapAndThrowExecutionExceptionOrError(e.getCause());
throw new AssertionError();
}
}
代码示例来源:origin: stackoverflow.com
import static java.util.concurrent.TimeUnit.*;
class BeeperControl {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() { System.out.println("beep"); }
};
final ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
scheduler.schedule(new Runnable() {
public void run() { beeperHandle.cancel(true); }
}, 60 * 60, SECONDS);
}
}
内容来源于网络,如有侵权,请联系作者删除!