java.util.concurrent.TimeoutException类的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(9.0k)|赞(0)|评价(0)|浏览(357)

本文整理了Java中java.util.concurrent.TimeoutException类的一些代码示例,展示了TimeoutException类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。TimeoutException类的具体详情如下:
包路径:java.util.concurrent.TimeoutException
类名称:TimeoutException

TimeoutException介绍

[英]Exception thrown when a blocking operation times out. Blocking operations for which a timeout is specified need a means to indicate that the timeout has occurred. For many such operations it is possible to return a value that indicates timeout; when that is not possible or desirable then TimeoutException should be declared and thrown.
[中]阻止操作超时时引发异常。指定了超时的阻塞操作需要一种方法来指示超时已经发生。对于许多这样的操作,可以返回一个指示超时的值;当这不可能或不可取时,应该声明并抛出TimeoutException。

代码示例

代码示例来源:origin: google/guava

List<Future<T>> futures = Lists.newArrayListWithCapacity(ntasks);
BlockingQueue<Future<T>> futureQueue = Queues.newLinkedBlockingQueue();
long timeoutNanos = unit.toNanos(timeout);
  Future<T> f = futureQueue.poll();
  if (f == null) {
   if (ntasks > 0) {
    break;
   } else if (timed) {
    f = futureQueue.poll(timeoutNanos, TimeUnit.NANOSECONDS);
    if (f == null) {
     throw new TimeoutException();
    lastTime = now;
   } else {
    f = futureQueue.take();
  ee = new ExecutionException(null);
  f.cancel(true);

代码示例来源:origin: alibaba/nacos

try {
  if (f != null) {
    sampleResults = f.get(500, TimeUnit.MILLISECONDS);
    if (sampleResults != null) {
      collectionResult.add(sampleResults);
    f.cancel(true);
      .getMessage());
LogUtil.defaultLog.warn(
  "get task result with ExecutionException: {} ", e
    .getMessage());

代码示例来源:origin: sarxos/webcam-capture

Future<List<Webcam>> future = executor.submit(discovery);
executor.shutdown();
  executor.awaitTermination(timeout, tunit);
  if (future.isDone()) {
    webcams = future.get();
  } else {
    future.cancel(true);
  throw new TimeoutException(String.format("Webcams discovery timeout (%d ms) has been exceeded", timeout));

代码示例来源:origin: linkedin/indextank-engine

Future<T> future = executor.submit(new Callable<T>() {
  @Override
  public T call() throws Exception {
executor.shutdown();
  completed = executor.awaitTermination(timeout, unit);
} catch (InterruptedException e) {
  future.cancel(true);
  executor.shutdownNow();
  throw e;
  return future.get();
} else {
  future.cancel(true);
  executor.shutdownNow();
  throw new TimeoutException("Timed out");

代码示例来源:origin: Alluxio/alluxio

List<Future<T>> pending = new ArrayList<>();
for (Callable<T> c : callables) {
 pending.add(service.submit(c));
 while (it.hasNext()) {
  Future<T> future = it.next();
  if (future.isDone()) {
    future.get();
   } catch (InterruptedException e) {
  throw new TimeoutException(
    String.format("Timed out after %dms", timeoutMs - remainingMs));
service.shutdownNow();

代码示例来源:origin: org.eclipse.jetty/jetty-util

@Override
public C get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException
{
  if (!_latch.await(timeout,unit))
    throw new TimeoutException();
  if (_cause==COMPLETED)
    return _result;
  if (_cause instanceof TimeoutException)
    throw (TimeoutException)_cause;
  if (_cause instanceof CancellationException)
    throw (CancellationException) new CancellationException().initCause(_cause);
  throw new ExecutionException(_cause);
}

代码示例来源:origin: apache/incubator-pinot

protected IntermediateResultsBlock getNextBlock() {
 int numOperators = _operators.size();
 CountDownLatch operatorLatch = new CountDownLatch(numOperators);
 ConcurrentHashMap<String, Object[]> resultsMap = new ConcurrentHashMap<>();
 AtomicInteger numGroups = new AtomicInteger();
 for (int i = 0; i < numOperators; i++) {
  int index = i;
  futures[i] = _executorService.submit(new TraceRunnable() {
   @SuppressWarnings("unchecked")
   @Override
  boolean opCompleted = operatorLatch.await(_timeOutMs, TimeUnit.MILLISECONDS);
  if (!opCompleted) {
   return new IntermediateResultsBlock(new TimeoutException(errorMessage));
   if (!future.isDone()) {
    future.cancel(true);

代码示例来源:origin: neo4j/neo4j

for ( int i = 0; i < concurrencyLevel; i++ )
  futures[i] = EXECUTOR_SERVICE.submit( planRunner );
long deadlineMillis = System.currentTimeMillis() + unit.toMillis( timeout );
long now;
try
    if ( deadlineMillis < now )
      throw new TimeoutException();
    future.get( deadlineMillis - now, TimeUnit.MILLISECONDS );
      future.get( 10, TimeUnit.SECONDS );
      future.cancel( true );

代码示例来源:origin: h2oai/h2o-2

if ((s = status) >= 0 && (ns = unit.toNanos(timeout)) > 0L) {
  long deadline = System.nanoTime() + ns;
  ForkJoinPool p = null;
        if ((ms = TimeUnit.NANOSECONDS.toMillis(ns)) > 0L &&
          U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
          synchronized (this) {
  Throwable ex;
  if (s == CANCELLED)
    throw new CancellationException();
  if (s != EXCEPTIONAL)
    throw new TimeoutException();
  if ((ex = getThrowableException()) != null)
    throw new ExecutionException(ex);

代码示例来源:origin: neo4j/neo4j

@Override
  public T get( long timeout, TimeUnit unit ) throws InterruptedException, TimeoutException
  {
    if ( !guardedByLatch.await( timeout, unit ) )
    {
      throw new TimeoutException( jobDescription + " didn't complete within " +
          timeout + " " + unit );
    }
    return supplier.get();
  }
};

代码示例来源:origin: apache/ignite

/**
 * @throws Exception Thrown in case of test failure.
 */
@Test
public void testSubmitWithFutureTimeout() throws Exception {
  Ignite ignite = G.ignite(getTestIgniteInstanceName());
  ExecutorService srvc = createExecutorService(ignite);
  Future<Integer> fut = srvc.submit(new TestCallable<>(3000)); // Just sleep for 3 seconds.
  boolean ok = true;
  try {
    fut.get(1, TimeUnit.SECONDS);
    ok = false;
  }
  catch (TimeoutException e) {
    info("Task timeout elapsed: " + e.getMessage());
  }
  assert ok : "Timeout must be thrown.";
  srvc.shutdown();
}

代码示例来源:origin: Atmosphere/atmosphere

@Override
  public E get(long l, TimeUnit tu) throws InterruptedException, ExecutionException, TimeoutException {

    if (innerFuture != null) {
      return (E) innerFuture.get(l, tu);
    }

    boolean isSuccessful = latch.await(l, tu);
    if (!isSuccessful) {
      throw new TimeoutException();
    }
    return msg;
  }
}

代码示例来源:origin: stanfordnlp/CoreNLP

completedAnnotationFuture = corenlpExecutor.submit(() -> {
 pipeline.annotate(ann);
 return ann;
 timeoutMilliseconds = StanfordCoreNLPServer.this.timeoutMilliseconds;
completedAnnotation = completedAnnotationFuture.get(timeoutMilliseconds, TimeUnit.MILLISECONDS);
e.printStackTrace();
 completedAnnotationFuture.cancel(true);
 completedAnnotationFuture.cancel(true);

代码示例来源:origin: wildfly/wildfly

f = ecs.poll(nanos, TimeUnit.NANOSECONDS);
    if (f == null)
      throw new TimeoutException();
    long now = System.nanoTime();
    nanos -= now - lastTime;
  --active;
  try {
    return f.get();
  } catch (InterruptedException ie) {
    throw ie;
    ee = eex;
  } catch (RuntimeException rex) {
    ee = new ExecutionException(rex);
ee = new ExecutionException() {
  private static final long serialVersionUID = 200818694545553992L;
};
f.cancel(true);

代码示例来源:origin: HubSpot/Singularity

public static <T> CompletableFuture<T> executeWithTimeout(Callable<T> callable,
                             ExecutorService executorService,
                             HashedWheelTimer timer,
                             long timeout,
                             TimeUnit timeUnit) {
 CompletableFuture<T> future = new CompletableFuture<>();
 AtomicReference<Timeout> timeoutRef = new AtomicReference<>();
 Future<Void> underlying = executorService.submit(() -> {
  if (future.complete(callable.call())) {
   Timeout timeout1 = timeoutRef.get();
   if (timeout1 != null) {
    timeout1.cancel();
   }
  }
  return null;
 });
 timeoutRef.set(timer.newTimeout((ignored) -> {
  if (!future.isDone()) {
   if (future.completeExceptionally(new TimeoutException())) {
    underlying.cancel(true);
   }
  }
 }, timeout, timeUnit));
 return future;
}

代码示例来源:origin: alipay/sofa-rpc

context.setFuture(null);
  return future.get(timeout, TimeUnit.MILLISECONDS);
} catch (TimeoutException ex) {
  if (!future.isDone()) {
    throw new SofaTimeOutException("Future is not done when timeout.", ex);
  } else {
    throw new SofaTimeOutException(ex.getMessage(), ex);
  Throwable cause = ex.getCause();
  if (cause instanceof SofaRpcException) {
    throw (SofaRpcException) cause;

代码示例来源:origin: apache/cloudstack

final Future<Integer> processFuture = executor.submit(new Callable<Integer>() {
  @Override
  public Integer call() throws Exception {
  retVal = processFuture.get(timeOut.getStandardSeconds(), TimeUnit.SECONDS);
} catch (ExecutionException e) {
  retVal = -2;
  stdError = e.getMessage();
  if (LOG.isTraceEnabled()) {
    LOG.trace("Failed to complete the requested command due to execution error: " + e.getMessage());
  stdError = "Operation timed out, aborted";
  if (LOG.isTraceEnabled()) {
    LOG.trace("Failed to complete the requested command within timeout: " + e.getMessage());

代码示例来源:origin: apache/kafka

R await(long timeout, TimeUnit unit)
      throws InterruptedException, ExecutionException, TimeoutException {
    long startMs = System.currentTimeMillis();
    long waitTimeMs = unit.toMillis(timeout);
    long delta = 0;
    synchronized (this) {
      while (true) {
        if (exception != null)
          wrapAndThrow(exception);
        if (done)
          return value;
        if (delta >= waitTimeMs) {
          throw new TimeoutException();
        }
        this.wait(waitTimeMs - delta);
        delta = System.currentTimeMillis() - startMs;
      }
    }
  }
}

代码示例来源:origin: apache/incubator-gobblin

@Override
 public RecordMetadata get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
  boolean occurred = this.latch.await(timeout, unit);
  if (!occurred) {
   throw new TimeoutException("Timeout after waiting for " + TimeUnit.MILLISECONDS.convert(timeout, unit));
  }
  return new RecordMetadata(this.offset);
 }
}

代码示例来源:origin: apache/avro

@Override
public T get(long timeout, TimeUnit unit)
  throws InterruptedException, ExecutionException, TimeoutException {
 if (latch.await(timeout, unit)) {
  if (error != null) {
   throw new ExecutionException(error);
  }
  return result;
 } else {
  throw new TimeoutException();
 }
}

相关文章