类java.util.concurrent.CancellationException源码实例Demo

下面列出了怎么用java.util.concurrent.CancellationException的API类实例代码及写法,或者点击链接到github查看源代码。

@Test
public void testCancelWithoutInterrupt() throws InterruptedException {
    AsyncBulkheadTask task = newTask();
    
    Future result = bean.serviceAsync(task);
    
    task.assertStarting(result);
    
    result.cancel(false);
    
    task.assertNotInterrupting();
    
    assertTrue(result.isCancelled(), "Task is not cancelled");
    assertTrue(result.isDone(), "Task is not done");
    Exceptions.expect(CancellationException.class, () -> result.get(2, TimeUnit.SECONDS));
    Exceptions.expect(CancellationException.class, () -> result.get());
    
    task.complete();
    
    // Assert result still gives correct values after the task is allowed to complete
    assertTrue(result.isCancelled(), "Task is not cancelled");
    assertTrue(result.isDone(), "Task is not done");
    Exceptions.expect(CancellationException.class, () -> result.get(2, TimeUnit.SECONDS));
    Exceptions.expect(CancellationException.class, () -> result.get());
}
 
源代码2 项目: rsocket-java   文件: RSocketTest.java
void errorFromResponderPublisher(
    TestPublisher<Payload> requesterPublisher,
    AssertSubscriber<Payload> requesterSubscriber,
    TestPublisher<Payload> responderPublisher,
    AssertSubscriber<Payload> responderSubscriber) {
  // ensures that after sending cancel the whole requestChannel is terminated
  responderPublisher.error(EXCEPTION);
  // error should be propagated
  responderSubscriber.assertTerminated().assertError(CancellationException.class);
  requesterSubscriber
      .assertTerminated()
      .assertError(CustomRSocketException.class)
      .assertErrorMessage("test");
  // ensures that cancellation is propagated to the actual upstream
  requesterPublisher.assertWasCancelled();
  requesterPublisher.assertNoSubscribers();
}
 
源代码3 项目: mycore   文件: MCRXMLFunctions.java
/**
 * Checks if the given object is readable to guest user.
 * @param objId MCRObjectID as String
 */
public static boolean isWorldReadable(String objId) {
    if (objId == null || !MCRObjectID.isValid(objId)) {
        return false;
    }
    MCRObjectID mcrObjectID = MCRObjectID.getInstance(objId);
    CompletableFuture<Boolean> permission = MCRAccessManager.checkPermission(
        MCRSystemUserInformation.getGuestInstance(),
        () -> MCRAccessManager.checkPermission(mcrObjectID, MCRAccessManager.PERMISSION_READ));
    try {
        return permission.join();
    } catch (CancellationException | CompletionException e) {
        LOGGER.error("Error while retriving ACL information for Object {}", objId, e);
        return false;
    }
}
 
源代码4 项目: big-c   文件: DFSInputStream.java
private ByteBuffer getFirstToComplete(
    CompletionService<ByteBuffer> hedgedService,
    ArrayList<Future<ByteBuffer>> futures) throws InterruptedException {
  if (futures.isEmpty()) {
    throw new InterruptedException("let's retry");
  }
  Future<ByteBuffer> future = null;
  try {
    future = hedgedService.take();
    ByteBuffer bb = future.get();
    futures.remove(future);
    return bb;
  } catch (ExecutionException e) {
    // already logged in the Callable
    futures.remove(future);
  } catch (CancellationException ce) {
    // already logged in the Callable
    futures.remove(future);
  }

  throw new InterruptedException("let's retry");
}
 
源代码5 项目: streamsupport   文件: CountedCompleterTest.java
/**
 * timed get of a forked task throws exception when task cancelled
 */
public void testCancelledForkTimedGet() throws Exception {
    @SuppressWarnings("serial")
    ForkJoinTask<?> a = new CheckedRecursiveAction() {
        protected void realCompute() throws Exception {
            CCF f = new LCCF(8);
            assertTrue(f.cancel(true));
            assertSame(f, f.fork());
            try {
                f.get(LONG_DELAY_MS, MILLISECONDS);
                shouldThrow();
            } catch (CancellationException success) {
                checkCancelled(f);
            }
        }};
    testInvokeOnPool(mainPool(), a);
}
 
源代码6 项目: etcd-java   文件: GrpcClient.java
public static <T> T waitFor(Future<T> fut, long timeoutMillis) {
    try {
        return timeoutMillis < 0L ? fut.get() : fut.get(timeoutMillis, MILLISECONDS);
    } catch (InterruptedException|CancellationException e) {
        fut.cancel(true);
        if (e instanceof InterruptedException) {
            Thread.currentThread().interrupt();
        }
        throw Status.CANCELLED.withCause(e).asRuntimeException();
    } catch (ExecutionException ee) {
        throw Status.fromThrowable(ee.getCause()).asRuntimeException();
    } catch (TimeoutException te) {
        fut.cancel(true);
        throw Status.DEADLINE_EXCEEDED.withCause(te)
            .withDescription("local timeout of " + timeoutMillis + "ms exceeded")
            .asRuntimeException();
    } catch (RuntimeException rte) {
        fut.cancel(true);
        throw Status.fromThrowable(rte).asRuntimeException();
    }
}
 
源代码7 项目: netbeans   文件: BowerProblemsProvider.java
@Override
public Result get() throws InterruptedException, ExecutionException {
    try {
        getTask().get();
    } catch (CancellationException ex) {
        // cancelled by user
    }
    if (bowerInstallRequired()) {
        synchronized (this) {
            task = null;
        }
        return Result.create(Status.UNRESOLVED);
    }
    fireProblemsChanged();
    return Result.create(Status.RESOLVED);
}
 
源代码8 项目: geowave   文件: AbstractRedisSetWrapper.java
public void flush() {
  batchCmdCounter = 0;
  final RBatch flushBatch = this.currentBatch;
  currentAsync = null;
  currentBatch = null;
  if (flushBatch == null) {
    return;
  }
  try {
    writeSemaphore.acquire();
    flushBatch.executeAsync().handle((r, t) -> {
      writeSemaphore.release();
      if ((t != null) && !(t instanceof CancellationException)) {
        LOGGER.error("Exception in batched write", t);
      }
      return r;
    });
  } catch (final InterruptedException e) {
    LOGGER.warn("async batch write semaphore interrupted", e);
    writeSemaphore.release();
  }
}
 
源代码9 项目: hottub   文件: CompletableFuture.java
/**
 * Reports result using Future.get conventions.
 */
private static <T> T reportGet(Object r)
    throws InterruptedException, ExecutionException {
    if (r == null) // by convention below, null means interrupted
        throw new InterruptedException();
    if (r instanceof AltResult) {
        Throwable x, cause;
        if ((x = ((AltResult)r).ex) == null)
            return null;
        if (x instanceof CancellationException)
            throw (CancellationException)x;
        if ((x instanceof CompletionException) &&
            (cause = x.getCause()) != null)
            x = cause;
        throw new ExecutionException(x);
    }
    @SuppressWarnings("unchecked") T t = (T) r;
    return t;
}
 
源代码10 项目: streamsupport   文件: ForkJoinPool8Test.java
/**
 * join of a forked task throws exception when task cancelled
 */
public void testCancelledForkJoin() {
    @SuppressWarnings("serial")
    RecursiveAction a = new CheckedRecursiveAction() {
        protected void realCompute() {
            FibAction f = new FibAction(8);
            assertTrue(f.cancel(true));
            assertSame(f, f.fork());
            try {
                f.join();
                shouldThrow();
            } catch (CancellationException success) {
                checkCancelled(f);
            }
        }};
    checkInvoke(a);
}
 
源代码11 项目: edslite   文件: WipeFilesTask.java
@Override
public void onCompleted(Result result)
{
       try
	{
           result.getResult();
	}
       catch(CancellationException ignored)
       {

       }
	catch (Throwable e)
	{
           reportError(e);
	}
       finally
	{
           super.onCompleted(result);
	}
}
 
源代码12 项目: xtext-xtend   文件: AnnotationProcessor.java
/**
 * runs the given runnable and another thread in parallel, that sets the timeout property on the compilation unit to true
 * when the given amount of milliseconds have passed by.
 */
private Object runWithCancelIndiciator(final ActiveAnnotationContext ctx, final CancelIndicator cancelIndicator, final Runnable runnable) {
  Object _xblockexpression = null;
  {
    final AtomicBoolean isFinished = new AtomicBoolean(false);
    final Function0<Boolean> _function = () -> {
      return Boolean.valueOf(isFinished.get());
    };
    this.cancellationObserver.monitorUntil(ctx, cancelIndicator, _function);
    Object _xtrycatchfinallyexpression = null;
    try {
      runnable.run();
    } catch (final Throwable _t) {
      if (_t instanceof CancellationException) {
        _xtrycatchfinallyexpression = null;
      } else {
        throw Exceptions.sneakyThrow(_t);
      }
    } finally {
      isFinished.set(true);
    }
    _xblockexpression = _xtrycatchfinallyexpression;
  }
  return _xblockexpression;
}
 
源代码13 项目: Camera2   文件: DeferredManualAutoFocus.java
@Override
public void triggerFocusAndMeterAtPoint(float nx, float ny)
{
    if (mManualAutoFocusFuture.isDone())
    {
        try
        {
            ManualAutoFocus af = mManualAutoFocusFuture.get();
            af.triggerFocusAndMeterAtPoint(nx, ny);
        } catch (InterruptedException | ExecutionException | CancellationException e)
        {
            // If the {@link Future} is not ready, do nothing.
            return;
        }
    }
}
 
源代码14 项目: remixed-dungeon   文件: ReportingExecutor.java
@SneakyThrows
protected void afterExecute(Runnable r, Throwable t) {
    super.afterExecute(r, t);
    if (t == null && r instanceof Future<?>) {
        try {
            Future<?> future = (Future<?>) r;
            if (future.isDone()) {
                future.get();
            }
        } catch (CancellationException ce) {
            t = ce;
        } catch (ExecutionException ee) {
            t = ee.getCause();
        } catch (InterruptedException ie) {
            Thread.currentThread().interrupt();
        }
    }
    if (t != null) {
        throw t;
    }
}
 
源代码15 项目: whiskey   文件: CompletableFuture.java
@Override
public boolean cancel(boolean mayInterruptIfRunning) {

    if (done) return false;

    synchronized(this) {
        if (done) return false;
        cancelled = true;
        done = true;

        final Exception e = new CancellationException();
        for (final Listener<T> listener : listeners) {
            listener.getExecutor().execute(new Runnable() {
                @Override
                public void run() {
                    listener.onError(e);
                }
            });
        }

        notifyAll();
        return true;
    }
}
 
@Override
public ImplicitResponseUrl waitForImplicitResponseUrl() throws IOException {
    lock.lock();
    try {
        while (codeOrToken == null && error == null) {
            gotAuthorizationResponse.awaitUninterruptibly();
        }
        dismissDialog();
        if (error != null) {
            if (TextUtils.equals(ERROR_USER_CANCELLED, error)) {
                throw new CancellationException("User authorization failed (" + error + ")");
            } else {
                throw new IOException("User authorization failed (" + error + ")");
            }
        }
        return implicitResponseUrl;
    } finally {
        lock.unlock();
    }
}
 
源代码17 项目: future-converter   文件: AbstractConverterTest.java
@Test
public void testCancelBeforeConversion() throws ExecutionException, InterruptedException {
    F originalFuture = createRunningFuture();
    originalFuture.cancel(true);

    T convertedFuture = convert(originalFuture);
    assertFalse(convertedFuture.cancel(true));

    try {
        convertedFuture.get();
        fail("Exception expected");
    } catch (CancellationException e) {
        //ok
    }
    assertEquals(true, originalFuture.isDone());
    assertEquals(true, originalFuture.isCancelled());
    assertEquals(true, convertedFuture.isDone());
    assertEquals(true, convertedFuture.isCancelled());
}
 
源代码18 项目: mongodb-async-driver   文件: FutureCallback.java
/**
 * Implementation to get the future's value.
 *
 * @return The value set for the future.
 * @throws CancellationException
 *             If the future was canceled.
 * @throws ExecutionException
 *             If the future failed due to an exception.
 */
private V getValue() throws CancellationException, ExecutionException {
    final int state = getState();
    switch (state) {
    case COMPLETED:
        if (myException != null) {
            throw new ExecutionException(myException);
        }
        return myValue;

    case CANCELED:
    case INTERRUPTED:
        final CancellationException cancellation = new CancellationException(
                "Future was canceled.");
        cancellation.initCause(myException);

        throw cancellation;

    default:
        throw new IllegalStateException("Sync in invalid state: "
                + state);
    }
}
 
源代码19 项目: servicetalk   文件: SingleToCompletionStageTest.java
@Test
public void blockingCancellationBeforeListen() throws Exception {
    CompletionStage<String> stage = source.toCompletionStage();
    CompletableFuture<String> future = stage.toCompletableFuture();
    AtomicReference<Throwable> causeRef = new AtomicReference<>();
    CountDownLatch latch = new CountDownLatch(1);
    future.cancel(true);
    stage.whenComplete((s, t) -> {
        causeRef.set(t);
        latch.countDown();
    });
    assertTrue(latch.await(100, MILLISECONDS));
    assertTrue(future.isCancelled());
    assertTrue(future.isDone());
    thrown.expect(CancellationException.class);
    future.get();
}
 
源代码20 项目: molgenis   文件: ConnectionRetryConfigTest.java
@Test
void testInterruptFailingTries() throws Exception {
  Future<Client> result =
      executorService.submit(
          () -> {
            RetryCallback<Client, RuntimeException> fail =
                c -> {
                  throw new MolgenisDataException();
                };
            return retryTemplate.execute(fail);
          });

  result.cancel(true);
  try {
    result.get(100, TimeUnit.MILLISECONDS);
    fail("Should throw cancellation exception!");
  } catch (CancellationException ignore) {
  }
  assertTrue(result.isDone());
  assertTrue(result.isCancelled());
}
 
源代码21 项目: loom-fiber   文件: Task.java
@Override
@SuppressWarnings("unchecked")
public T await(Duration duration) throws TimeoutException {
	try {
	  virtualThread.join(duration);
	} catch(InterruptedException e) {
		throw new CompletionException(e);
	}
  if (setResultIfNull(CANCELLED)) {
    throw new TimeoutException();
  }
  Object result = this.result;
  if (result == CANCELLED) {
    throw new CancellationException();
  }
  if (result instanceof $$$<?>) {
    throw (($$$<RuntimeException>)result).throwable;
  }
  return (T)result;
}
 
@Test
public void cancelStateThrowsExceptionWhenCallingGet() throws ExecutionException, InterruptedException {
	settableListenableFuture.cancel(true);

	try {
		settableListenableFuture.get();
		fail("Expected CancellationException");
	}
	catch (CancellationException ex) {
		// expected
	}

	assertTrue(settableListenableFuture.isCancelled());
	assertTrue(settableListenableFuture.isDone());
}
 
@Override
public void onSubscribe(Subscription subscription) {
    Objects.requireNonNull(subscription);
    if (subscribed.compareAndSet(false, true)) {
        source.onSubscribe(
                new WrappedSubscription(subscription, () -> future.completeExceptionally(new CancellationException())));
    } else {
        subscription.cancel();
    }
}
 
源代码24 项目: n4js   文件: FutureUtil.java
private static Throwable getCancellation(Throwable e) {
	while (e != null) {
		if (e instanceof OperationCanceledError
				|| e instanceof OperationCanceledException
				|| e instanceof CancellationException) {
			return e;
		}
		e = e.getCause();
	}
	return null;
}
 
源代码25 项目: smarthome   文件: SchedulerImpl.java
@Override
public <T> ScheduledCompletableFuture<T> before(CompletableFuture<T> promise, Duration timeout) {
    final AtomicBoolean done = new AtomicBoolean();
    final Consumer<Runnable> runOnce = runnable -> {
        if (!done.getAndSet(true)) {
            runnable.run();
        }
    };
    final ScheduledCompletableFutureOnce<T> wrappedPromise = new ScheduledCompletableFutureOnce<>();
    Callable<T> callable = () -> {
        wrappedPromise.completeExceptionally(new TimeoutException());
        return null;
    };
    final ScheduledCompletableFutureOnce<T> afterPromise = afterInternal(wrappedPromise, callable, timeout);
    wrappedPromise.exceptionally(e -> {
        if (e instanceof CancellationException) {
            // Also cancel the scheduled timer if returned completable future is cancelled.
            afterPromise.cancel(true);
        }
        return null;
    });

    promise.thenAccept(p -> runOnce.accept(() -> wrappedPromise.complete(p))) //
            .exceptionally(ex -> {
                runOnce.accept(() -> wrappedPromise.completeExceptionally(ex));
                return null;
            });
    return wrappedPromise;
}
 
源代码26 项目: threadly   文件: SettableListenableFutureTest.java
@Test
public void failureFlatMapCancelationExceptionMessageTest() throws InterruptedException, TimeoutException {
  String msg = StringUtils.makeRandomString(5);
  SettableListenableFuture<Void> slf = new CancelMessageTestSettableListenableFuture(msg);
  ListenableFuture<Void> mappedFuture = slf.flatMapFailure(CancellationException.class, 
                                                           (c) -> FutureUtils.immediateFailureFuture(c));
  slf.cancel(false);

  verifyCancelationExceptionMessageOnGet(msg, mappedFuture);
  verifyCancelationExceptionMessageInCallback(msg, mappedFuture);
}
 
源代码27 项目: besu   文件: EthScheduler.java
public <T> CompletableFuture<T> scheduleSyncWorkerTask(
    final Supplier<CompletableFuture<T>> future) {
  final CompletableFuture<T> promise = new CompletableFuture<>();
  final Future<?> workerFuture =
      syncWorkerExecutor.submit(() -> propagateResult(future, promise));
  // If returned promise is cancelled, cancel the worker future
  promise.whenComplete(
      (r, t) -> {
        if (t instanceof CancellationException) {
          workerFuture.cancel(false);
        }
      });
  return promise;
}
 
源代码28 项目: RxJava3-preview   文件: SingleTakeUntilTest.java
@Test
public void otherOnCompletePublisher() {
    PublishProcessor<Integer> pp = PublishProcessor.create();
    PublishProcessor<Integer> source = PublishProcessor.create();

    TestObserver<Integer> ts = takeUntil(single(source, -99), pp)
    .test();

    pp.onComplete();

    ts.assertFailure(CancellationException.class);
}
 
源代码29 项目: netbeans   文件: CommandStopCluster.java
/**
 * Stops cluster.
 * <p/>
 * @param server Payara server entity.
 * @param target Cluster name.
 * @return Stop cluster task response.
 * @throws PayaraIdeException When error occurred during administration
 *         command execution.
 */
public static ResultString stopCluster(PayaraServer server,
        String target) throws PayaraIdeException {
    Command command = new CommandStopCluster(target);
    Future<ResultString> future
            = ServerAdmin.<ResultString>exec(server, command);
    try {
        return future.get();
    } catch (InterruptedException | ExecutionException
            | CancellationException ie) {
        throw new PayaraIdeException(ERROR_MESSAGE, ie);
    }
}
 
源代码30 项目: besu   文件: AbstractEthTask.java
/**
 * Utility for executing completable futures that handles cleanup if this EthTask is cancelled.
 *
 * @param subTask a subTask to execute
 * @param <S> the type of data returned from the CompletableFuture
 * @return The completableFuture that was executed
 */
protected final <S> CompletableFuture<S> executeSubTask(
    final Supplier<CompletableFuture<S>> subTask) {
  synchronized (result) {
    if (!isCancelled()) {
      final CompletableFuture<S> subTaskFuture = subTask.get();
      subTaskFutures.add(subTaskFuture);
      subTaskFuture.whenComplete((r, t) -> subTaskFutures.remove(subTaskFuture));
      return subTaskFuture;
    } else {
      return CompletableFuture.failedFuture(new CancellationException());
    }
  }
}
 
 类所在包
 类方法
 同包方法