Java util concurrent cancellationexception

java.util.concurrent.CancellationException Java Examples

The following examples show how to use java.util.concurrent.CancellationException . 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.

Source File: AsyncCancellationTest.java From microprofile-fault-tolerance with Apache License 2.0 6 votes
@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()); >
Source File: RSocketTest.java From rsocket-java with Apache License 2.0 6 votes
void errorFromResponderPublisher( TestPublisher requesterPublisher, AssertSubscriber requesterSubscriber, TestPublisher responderPublisher, AssertSubscriber 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(); >
Source File: MCRXMLFunctions.java From mycore with GNU General Public License v3.0 6 votes
/** * 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 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; > >
Source File: DFSInputStream.java From big-c with Apache License 2.0 6 votes
private ByteBuffer getFirstToComplete( CompletionService hedgedService, ArrayList futures) throws InterruptedException < if (futures.isEmpty()) < throw new InterruptedException("let's retry"); >Future 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"); >
Source File: CountedCompleterTest.java From streamsupport with GNU General Public License v2.0 6 votes
/** * timed get of a forked task throws exception when task cancelled */ public void testCancelledForkTimedGet() throws Exception < @SuppressWarnings("serial") ForkJoinTaska = 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); >
Source File: GrpcClient.java From etcd-java with Apache License 2.0 6 votes
public static T waitFor(Future 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(); >>
Source File: BowerProblemsProvider.java From netbeans with Apache License 2.0 6 votes
@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); >
Source File: AbstractRedisSetWrapper.java From geowave with Apache License 2.0 6 votes
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(); >>
Source File: CompletableFuture.java From hottub with GNU General Public License v2.0 6 votes
/** * Reports result using Future.get conventions. */ private static 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; >
Source File: ForkJoinPool8Test.java From streamsupport with GNU General Public License v2.0 6 votes
/** * 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); >
Source File: WipeFilesTask.java From edslite with GNU General Public License v2.0 6 votes
@Override public void onCompleted(Result result) < try < result.getResult(); >catch(CancellationException ignored) < >catch (Throwable e) < reportError(e); >finally < super.onCompleted(result); >>
Source File: AnnotationProcessor.java From xtext-xtend with Eclipse Public License 2.0 6 votes
/** * 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_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; >
Source File: DeferredManualAutoFocus.java From Camera2 with Apache License 2.0 6 votes
@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 is not ready, do nothing. return; > > >
Source File: ReportingExecutor.java From remixed-dungeon with GNU General Public License v3.0 6 votes
@SneakyThrows protected void afterExecute(Runnable r, Throwable t) < super.afterExecute(r, t); if (t == null && r instanceof Future) < try < Futurefuture = (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; >>
Source File: CompletableFuture.java From whiskey with Apache License 2.0 6 votes
@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 Listenerlistener : listeners) < listener.getExecutor().execute(new Runnable() < @Override public void run() < listener.onError(e); >>); > notifyAll(); return true; > >
Source File: DialogFragmentController.java From android-oauth-client with Apache License 2.0 6 votes
@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(); >>
Source File: AbstractConverterTest.java From future-converter with Apache License 2.0 6 votes
@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()); >
Source File: FutureCallback.java From mongodb-async-driver with Apache License 2.0 6 votes
/** * 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); > >
Source File: SingleToCompletionStageTest.java From servicetalk with Apache License 2.0 6 votes
@Test public void blockingCancellationBeforeListen() throws Exception < CompletionStagestage = source.toCompletionStage(); CompletableFuture future = stage.toCompletableFuture(); AtomicReference 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(); >
Source File: ConnectionRetryConfigTest.java From molgenis with GNU Lesser General Public License v3.0 6 votes
@Test void testInterruptFailingTries() throws Exception < Futureresult = executorService.submit( () -> < RetryCallbackfail = 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()); >
Source File: Task.java From loom-fiber with MIT License 6 votes
@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 (($$$)result).throwable; > return (T)result; >
Source File: SettableListenableFutureTests.java From java-technology-stack with MIT License 5 votes
@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()); >
Source File: WrappedSubscriber.java From smallrye-reactive-streams-operators with Apache License 2.0 5 votes
@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(); >>
Source File: FutureUtil.java From n4js with Eclipse Public License 1.0 5 votes
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; >
Source File: SchedulerImpl.java From smarthome with Eclipse Public License 2.0 5 votes
@Override public ScheduledCompletableFuture before(CompletableFuture promise, Duration timeout) < final AtomicBoolean done = new AtomicBoolean(); final ConsumerrunOnce = runnable -> < if (!done.getAndSet(true)) < runnable.run(); >>; final ScheduledCompletableFutureOnce wrappedPromise = new ScheduledCompletableFutureOnce<>(); Callable callable = () -> < wrappedPromise.completeExceptionally(new TimeoutException()); return null; >; final ScheduledCompletableFutureOnce 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; >
Source File: SettableListenableFutureTest.java From threadly with Mozilla Public License 2.0 5 votes
@Test public void failureFlatMapCancelationExceptionMessageTest() throws InterruptedException, TimeoutException < String msg = StringUtils.makeRandomString(5); SettableListenableFutureslf = new CancelMessageTestSettableListenableFuture(msg); ListenableFuture mappedFuture = slf.flatMapFailure(CancellationException.class, (c) -> FutureUtils.immediateFailureFuture(c)); slf.cancel(false); verifyCancelationExceptionMessageOnGet(msg, mappedFuture); verifyCancelationExceptionMessageInCallback(msg, mappedFuture); >
Source File: EthScheduler.java From besu with Apache License 2.0 5 votes
public CompletableFuture scheduleSyncWorkerTask( final Supplier future) < final CompletableFuturepromise = 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; >
Source File: SingleTakeUntilTest.java From RxJava3-preview with Apache License 2.0 5 votes
@Test public void otherOnCompletePublisher() < PublishProcessorpp = PublishProcessor.create(); PublishProcessor source = PublishProcessor.create(); TestObserver ts = takeUntil(single(source, -99), pp) .test(); pp.onComplete(); ts.assertFailure(CancellationException.class); >
Source File: CommandStopCluster.java From netbeans with Apache License 2.0 5 votes
/** * Stops cluster. * * @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); Futurefuture = ServerAdmin.exec(server, command); try < return future.get(); >catch (InterruptedException | ExecutionException | CancellationException ie) < throw new PayaraIdeException(ERROR_MESSAGE, ie); >>
Source File: AbstractEthTask.java From besu with Apache License 2.0 5 votes
/** * Utility for executing completable futures that handles cleanup if this EthTask is cancelled. * * @param subTask a subTask to execute * @param the type of data returned from the CompletableFuture * @return The completableFuture that was executed */ protected final CompletableFuture executeSubTask( final Supplier subTask) < synchronized (result) < if (!isCancelled()) < final CompletableFuturesubTaskFuture = subTask.get(); subTaskFutures.add(subTaskFuture); subTaskFuture.whenComplete((r, t) -> subTaskFutures.remove(subTaskFuture)); return subTaskFuture; > else < return CompletableFuture.failedFuture(new CancellationException()); >> >

Источник

Java util concurrent cancellationexception

Пожалуйста, учтите, что спецификации и другая информация, содержащаяся здесь, не являются заключительными и могут быть изменены. Информация доступна для вас исключительно ради ознакомления.

  • Сводка:
  • Вложенный |
  • Поле |
  • Конструктор |
  • Метод
  • Детально:
  • Поле |
  • Конструктор |
  • Метод

Класс CancellationException

Оцените статью