Java Code Examples for java.util.concurrent.CancellationException

The following examples show how to use java.util.concurrent.CancellationException. 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
@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());
}
 
Example 2
Source Project: rsocket-java   Source File: RSocketTest.java    License: Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 3
Source Project: mycore   Source File: MCRXMLFunctions.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example 4
Source Project: big-c   Source File: DFSInputStream.java    License: Apache License 2.0 6 votes vote down vote up
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");
}
 
Example 5
/**
 * 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);
}
 
Example 6
Source Project: etcd-java   Source File: GrpcClient.java    License: Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example 7
Source Project: netbeans   Source File: BowerProblemsProvider.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 8
Source Project: geowave   Source File: AbstractRedisSetWrapper.java    License: Apache License 2.0 6 votes vote down vote up
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();
  }
}
 
Example 9
Source Project: hottub   Source File: CompletableFuture.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 10
/**
 * 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);
}
 
Example 11
Source Project: edslite   Source File: WipeFilesTask.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void onCompleted(Result result)
{
       try
	{
           result.getResult();
	}
       catch(CancellationException ignored)
       {

       }
	catch (Throwable e)
	{
           reportError(e);
	}
       finally
	{
           super.onCompleted(result);
	}
}
 
Example 12
Source Project: xtext-xtend   Source File: AnnotationProcessor.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 13
Source Project: Camera2   Source File: DeferredManualAutoFocus.java    License: Apache License 2.0 6 votes vote down vote up
@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;
        }
    }
}
 
Example 14
@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;
    }
}
 
Example 15
Source Project: whiskey   Source File: CompletableFuture.java    License: Apache License 2.0 6 votes vote down vote up
@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;
    }
}
 
Example 16
@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();
    }
}
 
Example 17
Source Project: future-converter   Source File: AbstractConverterTest.java    License: Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example 18
Source Project: mongodb-async-driver   Source File: FutureCallback.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 19
Source Project: servicetalk   Source File: SingleToCompletionStageTest.java    License: Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example 20
@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());
}
 
Example 21
Source Project: loom-fiber   Source File: Task.java    License: MIT License 6 votes vote down vote up
@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;
}
 
Example 22
@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());
}
 
Example 23
@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();
    }
}
 
Example 24
Source Project: n4js   Source File: FutureUtil.java    License: Eclipse Public License 1.0 5 votes vote down vote up
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;
}
 
Example 25
Source Project: smarthome   Source File: SchedulerImpl.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@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;
}
 
Example 26
@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);
}
 
Example 27
Source Project: besu   Source File: EthScheduler.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 28
Source Project: RxJava3-preview   Source File: SingleTakeUntilTest.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 29
Source Project: netbeans   Source File: CommandStopCluster.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 30
Source Project: besu   Source File: AbstractEthTask.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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());
    }
  }
}