当前位置: 首页>>代码示例>>Java>>正文


Java Future.isCancelled方法代码示例

本文整理汇总了Java中java.util.concurrent.Future.isCancelled方法的典型用法代码示例。如果您正苦于以下问题:Java Future.isCancelled方法的具体用法?Java Future.isCancelled怎么用?Java Future.isCancelled使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.util.concurrent.Future的用法示例。


在下文中一共展示了Future.isCancelled方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: demo1_Executor1

import java.util.concurrent.Future; //导入方法依赖的package包/类
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.");
    }
}
 
开发者ID:PacktPublishing,项目名称:Java-9-Cookbook,代码行数:25,代码来源:Chapter07Concurrency03.java

示例2: printResults

import java.util.concurrent.Future; //导入方法依赖的package包/类
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());
            }
        }
    }
}
 
开发者ID:PacktPublishing,项目名称:Java-9-Cookbook,代码行数:21,代码来源:Chapter07Concurrency03.java

示例3: shutdownAndCancelTasks

import java.util.concurrent.Future; //导入方法依赖的package包/类
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.");
    }
}
 
开发者ID:PacktPublishing,项目名称:Java-9-Cookbook,代码行数:23,代码来源:Chapter07Concurrency03.java

示例4: testInvokeAllTimeout

import java.util.concurrent.Future; //导入方法依赖的package包/类
@Test
public void testInvokeAllTimeout() throws Exception {
  final EDTExecutorService ex = new EDTExecutorService();

  final List<Callable<Character>> tasks =
    new ArrayList<Callable<Character>>();
  for (int i = 0; i < 10; ++i) {
    tasks.add(new Callable<Character>() {
      public Character call() {
        assertTrue(SwingUtilities.isEventDispatchThread());
        return 'x';
      }
    });
  }

  for (Future<Character> f : ex.invokeAll(tasks, 1L, TimeUnit.NANOSECONDS)) {
    if (!f.isCancelled()) assertEquals('x', f.get().charValue());
  }
}
 
开发者ID:ajmath,项目名称:VASSAL-src,代码行数:20,代码来源:EDTExecutorServiceTest.java

示例5: tillStop

import java.util.concurrent.Future; //导入方法依赖的package包/类
@Override
protected void tillStop() {
    Future<?> future = this._future;
    if (future == null
            || future.isCancelled()
            || future.isDone()) {
        return;
    }
    try {
        future.get();
    } catch (CancellationException
            | InterruptedException
            | ExecutionException ex) {
        // ignore
    }
}
 
开发者ID:febit,项目名称:febit,代码行数:17,代码来源:ExecutorServiceTaskExecutorFactory.java

示例6: executeTask

import java.util.concurrent.Future; //导入方法依赖的package包/类
public boolean executeTask(Runnable tsk) {
  Future<?> ret;
  
  try {
    theLock.lock();
    ret = worker.submit(tsk);
  } catch(Throwable t) {
    t.printStackTrace();
    return false;
  } finally {
    theLock.unlock();
  }

  try {
    ret.get();
  } catch (Exception e) {
    e.printStackTrace();
    return false;
  }

  if(ret.isCancelled())
    return false;
  return true;
}
 
开发者ID:twosigma,项目名称:beaker-notebook-archive,代码行数:25,代码来源:BeakerCellExecutor.java

示例7: cancelRequest

import java.util.concurrent.Future; //导入方法依赖的package包/类
/**
 * 取消正在执行的或者正在排队的请求
 *
 * @param requestId
 */
public synchronized void cancelRequest(String requestId) {
    if (TextUtils.isEmpty(requestId)) return;

    List<Future<String>> list = mFutures.get(requestId);
    if (list != null && list.size() > 0) {
        for (Future<String> future : list) {

            Request request = mRequests.remove(future);
            if (request != null) {
                request.setCanceled(true);

                if (request.getCall() != null) {
                    request.getCall().cancel();
                }
            }

            if (future.isDone() || future.isCancelled()) continue;
            future.cancel(true);

        }
        list.clear();
    }

}
 
开发者ID:jessie345,项目名称:RetrofitAppArchitecture,代码行数:30,代码来源:RequestExecutor.java

示例8: leaseConnection

import java.util.concurrent.Future; //导入方法依赖的package包/类
protected HttpClientConnection leaseConnection(
        final Future<CPoolEntry> future,
        final long timeout,
        final TimeUnit tunit) throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException {
    final CPoolEntry entry;
    try {
        entry = future.get(timeout, tunit);
        if (entry == null || future.isCancelled()) {
            throw new InterruptedException();
        }
        Asserts.check(entry.getConnection() != null, "Pool entry with no connection");
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connection leased: " + format(entry) + formatStats(entry.getRoute()));
        }
        return CPoolProxy.newProxy(entry);
    } catch (final TimeoutException ex) {
        throw new ConnectionPoolTimeoutException("Timeout waiting for connection from pool");
    }
}
 
开发者ID:mozilla-mobile,项目名称:FirefoxData-android,代码行数:20,代码来源:PoolingHttpClientConnectionManager.java

示例9: execCancelable

import java.util.concurrent.Future; //导入方法依赖的package包/类
@Nullable
public static <T> T execCancelable(@NotNull final Callable<T> callable) {
  final Future<T> future = ApplicationManager.getApplication().executeOnPooledThread(callable);

  while (!future.isCancelled() && !future.isDone()) {
    ProgressManager.checkCanceled();
    TimeoutUtil.sleep(500);
  }
  T result = null;
  try {
    result = future.get();
  }
  catch (InterruptedException | ExecutionException e) {
    LOG.warn(e.getMessage());
  }
  return result;
}
 
开发者ID:medvector,项目名称:educational-plugin,代码行数:18,代码来源:StudyUtils.java

示例10: handleOneInputDone

import java.util.concurrent.Future; //导入方法依赖的package包/类
/**
 * Handles the input at the given index completing.
 */
private void handleOneInputDone(int index, Future<? extends InputT> future) {
  // The only cases in which this Future should already be done are (a) if it was cancelled or
  // (b) if an input failed and we propagated that immediately because of allMustSucceed.
  checkState(
      allMustSucceed || !isDone() || isCancelled(),
      "Future was done before all dependencies completed");

  try {
    checkState(future.isDone(), "Tried to set value from future which is not done");
    if (allMustSucceed) {
      if (future.isCancelled()) {
        // clear running state prior to cancelling children, this sets our own state but lets
        // the input futures keep running as some of them may be used elsewhere.
        runningState = null;
        cancel(false);
      } else {
        // We always get the result so that we can have fail-fast, even if we don't collect
        InputT result = getDone(future);
        if (collectsValues) {
          collectOneValue(allMustSucceed, index, result);
        }
      }
    } else if (collectsValues && !future.isCancelled()) {
      collectOneValue(allMustSucceed, index, getDone(future));
    }
  } catch (ExecutionException e) {
    handleException(e.getCause());
  } catch (Throwable t) {
    handleException(t);
  }
}
 
开发者ID:paul-hammant,项目名称:googles-monorepo-demo,代码行数:35,代码来源:AggregateFuture.java

示例11: isResultAvailable

import java.util.concurrent.Future; //导入方法依赖的package包/类
public boolean isResultAvailable(final P arg) {
    Future<R> res = cache.get(arg);

    if (res == null) {
        return false;
    }

    return res.isDone() && !res.isCancelled();
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:10,代码来源:TasksCachedProcessor.java

示例12: isCancelled

import java.util.concurrent.Future; //导入方法依赖的package包/类
@Override
public boolean isCancelled() {
	boolean result = false;
	for (Future<Boolean> future : futures) {
		Boolean futureResult = future.isCancelled(); 
		result = result || (futureResult != null ? futureResult : false);			
	}
	return result;
}
 
开发者ID:kefik,项目名称:Pogamut3,代码行数:10,代码来源:CombinedBooleanFuture.java

示例13: cancel

import java.util.concurrent.Future; //导入方法依赖的package包/类
private static void cancel(List<Future<String>> futures) {
    for (Future future : futures) {
        if (!future.isCancelled() && !future.isDone()) {
            future.cancel(true);
        }
    }
}
 
开发者ID:pmohankumar,项目名称:fibers,代码行数:8,代码来源:CompositeFiberCompletionServiceTest.java

示例14: cancel

import java.util.concurrent.Future; //导入方法依赖的package包/类
@Override
public void cancel(Run run) {
	String runId = run.getId();
	Future<?> future = RUNNING.remove(runId);
	if (future == null) {
		return;
	}
	if (future.isDone()) {
		return;
	}
	if (future.isCancelled()) {
		return;
	}
	future.cancel(true);
}
 
开发者ID:Bibliome,项目名称:alvisnlp,代码行数:16,代码来源:ThreadExecutor.java

示例15: cancel

import java.util.concurrent.Future; //导入方法依赖的package包/类
public void cancel() {
    logger.info("canal Futures[{}]", futures.size());
    for (int i = 0; i < futures.size(); i++) {
        Future future = futures.get(i);
        if (!future.isDone() && !future.isCancelled()) {
            future.cancel(true);
        }
    }
}
 
开发者ID:luoyaogui,项目名称:otter-G,代码行数:10,代码来源:ExecutorTemplate.java


注:本文中的java.util.concurrent.Future.isCancelled方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。