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.
Example #1
Source File: ConnectionRetryConfigTest.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #2
Source File: MCRXMLFunctions.java    From mycore with 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 #3
Source File: DeferredManualAutoFocus.java    From Camera2 with 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 #4
Source File: RSocketTest.java    From rsocket-java with 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 #5
Source File: CompletableFuture.java    From whiskey with 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 #6
Source File: AsyncCancellationTest.java    From microprofile-fault-tolerance with Apache License 2.0 6 votes vote down vote up
@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 #7
Source File: DialogFragmentController.java    From android-oauth-client with Apache License 2.0 6 votes vote down vote up
@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 #8
Source File: AbstractConverterTest.java    From future-converter with 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 #9
Source File: ReportingExecutor.java    From remixed-dungeon with GNU General Public License v3.0 6 votes vote down vote up
@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 #10
Source File: AnnotationProcessor.java    From xtext-xtend with 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 #11
Source File: DFSInputStream.java    From big-c with 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 #12
Source File: CompletableFuture.java    From hottub with 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 #13
Source File: FutureCallback.java    From mongodb-async-driver with 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 #14
Source File: Task.java    From loom-fiber with 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 #15
Source File: CountedCompleterTest.java    From streamsupport with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 #16
Source File: SingleToCompletionStageTest.java    From servicetalk with 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 #17
Source File: GrpcClient.java    From etcd-java with 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 #18
Source File: BowerProblemsProvider.java    From netbeans with 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 #19
Source File: ForkJoinPool8Test.java    From streamsupport with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 #20
Source File: AbstractRedisSetWrapper.java    From geowave with 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 #21
Source File: WipeFilesTask.java    From edslite with 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 #22
Source File: ThreadPoolExecutorSubclassTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public V get() throws InterruptedException, ExecutionException {
    lock.lock();
    try {
        while (!done)
            cond.await();
        if (cancelled)
            throw new CancellationException();
        if (exception != null)
            throw new ExecutionException(exception);
        return result;
    }
    finally { lock.unlock(); }
}
 
Example #23
Source File: SchedulerImplTest.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test(expected = CancellationException.class, timeout = 500)
public void testAfterCancelled() throws InterruptedException, InvocationTargetException, ExecutionException {
    AtomicBoolean check = new AtomicBoolean();
    Callable<Boolean> callable = () -> check.getAndSet(true);
    ScheduledCompletableFuture<Boolean> after = scheduler.after(callable, Duration.ofMillis(200_0000));
    after.cancel(true);
    Thread.sleep(100);
    assertTrue("Scheduled job cancelled before timeout", after.isCancelled());
    Thread.sleep(200);
    assertFalse("Callable method should not been called", check.get());
    after.get();
}
 
Example #24
Source File: rebalance.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private Map simulate() throws CancellationException, InterruptedException
{
	Cache cache = CacheFactory.getAnyInstance();
	ResourceManager manager = cache.getResourceManager();
	RebalanceOperation op = manager.createRebalanceFactory().simulate();
	RebalanceResults results = op.getResults();
	Set<PartitionRebalanceInfo> set = results.getPartitionRebalanceDetails();
	return convertToMap(results);
}
 
Example #25
Source File: CommandStopCluster.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Stops cluster.
 * <p/>
 * @param server GlassFish server entity.
 * @param target Cluster name.
 * @return Stop cluster task response.
 * @throws GlassFishIdeException When error occurred during administration
 *         command execution.
 */
public static ResultString stopCluster(GlassFishServer server,
        String target) throws GlassFishIdeException {
    Command command = new CommandStopCluster(target);
    Future<ResultString> future
            = ServerAdmin.<ResultString>exec(server, command);
    try {
        return future.get();
    } catch (InterruptedException | ExecutionException
            | CancellationException ie) {
        throw new GlassFishIdeException(ERROR_MESSAGE, ie);
    }
}
 
Example #26
Source File: BasicFutureTest.java    From vjtools with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws InterruptedException, ExecutionException {
	MyFuture<String> future = new MyFuture<String>();
	Tasks.success(future);
	String result = future.get();
	assertThat(result).isEqualTo("haha");

	// 无人设置返回值
	try {
		MyFuture<String> future2 = new MyFuture<String>();
		future2.get(10, TimeUnit.MILLISECONDS);
		fail("should fail before");
	} catch (TimeoutException e) {
		assertThat(e).isInstanceOf(TimeoutException.class);
	}

	// 失败
	try {
		MyFuture<String> future3 = new MyFuture<String>();
		Tasks.fail(future3);
		future3.get();
		fail("should fail before");
	} catch (Throwable t) {
		assertThat(ExceptionUtil.unwrap(t)).hasMessage("wuwu");
	}

	// 取消
	MyFuture<String> future4 = new MyFuture<String>();
	Tasks.cancel(future4);
	assertThat(future4.isCancelled()).isTrue();
	try{
		String result4 = future4.get();
		fail("should fail here");
	}catch(CancellationException cae){
		
	}
	
	
}
 
Example #27
Source File: ThreadPoolExecutorSubclassTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * timed invokeAll(c) cancels tasks not completed by timeout
 */
public void testTimedInvokeAll6() throws Exception {
    for (long timeout = timeoutMillis();;) {
        final CountDownLatch done = new CountDownLatch(1);
        final Callable<String> waiter = new CheckedCallable<String>() {
            public String realCall() {
                try { done.await(LONG_DELAY_MS, MILLISECONDS); }
                catch (InterruptedException ok) {}
                return "1"; }};
        final ExecutorService p =
            new CustomTPE(2, 2,
                          LONG_DELAY_MS, MILLISECONDS,
                          new ArrayBlockingQueue<Runnable>(10));
        try (PoolCleaner cleaner = cleaner(p, done)) {
            List<Callable<String>> tasks = new ArrayList<>();
            tasks.add(new StringTask("0"));
            tasks.add(waiter);
            tasks.add(new StringTask("2"));
            long startTime = System.nanoTime();
            List<Future<String>> futures =
                p.invokeAll(tasks, timeout, MILLISECONDS);
            assertEquals(tasks.size(), futures.size());
            assertTrue(millisElapsedSince(startTime) >= timeout);
            for (Future future : futures)
                assertTrue(future.isDone());
            assertTrue(futures.get(1).isCancelled());
            try {
                assertEquals("0", futures.get(0).get());
                assertEquals("2", futures.get(2).get());
                break;
            } catch (CancellationException retryWithLongerTimeout) {
                timeout *= 2;
                if (timeout >= LONG_DELAY_MS / 2)
                    fail("expected exactly one task to be cancelled");
            }
        }
    }
}
 
Example #28
Source File: AsyncTask.java    From utexas-utilities with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
 */
public AsyncTask() {
    mWorker = new WorkerRunnable<Params, Result>() {
        public Result call() throws Exception {
            mTaskInvoked.set(true);

            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            //noinspection unchecked
            return postResult(doInBackground(mParams));
        }
    };

    mFuture = new FutureTask<Result>(mWorker) {
        @Override
        protected void done() {
            try {
                postResultIfNotInvoked(get());
            } catch (InterruptedException e) {
                android.util.Log.w(LOG_TAG, e);
            } catch (ExecutionException e) {
                throw new RuntimeException("An error occured while executing doInBackground()",
                        e.getCause());
            } catch (CancellationException e) {
                postResultIfNotInvoked(null);
            }
        }
    };
}
 
Example #29
Source File: AbstractFutureToSingleTest.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
@Test
public void cancellation() throws InterruptedException {
    CompletableFuture<String> future = new CompletableFuture<>();
    Single<String> single = from(future);
    toSource(single).subscribe(new SingleSource.Subscriber<String>() {
        @Override
        public void onSubscribe(final Cancellable cancellable) {
            cancellable.cancel();
        }

        @Override
        public void onSuccess(@Nullable final String result) {
        }

        @Override
        public void onError(final Throwable t) {
        }
    });

    AtomicReference<Throwable> causeRef = new AtomicReference<>();
    CountDownLatch latch = new CountDownLatch(1);
    future.whenComplete((value, cause) -> {
        causeRef.compareAndSet(null, cause);
        latch.countDown();
    });

    latch.await();
    assertThat(causeRef.get(), is(instanceOf(CancellationException.class)));
}
 
Example #30
Source File: Utils.java    From mug with Apache License 2.0 5 votes vote down vote up
static CompletionStage<?> ifCancelled(
    CompletionStage<?> stage, Consumer<? super CancellationException> action) {
  requireNonNull(action);
  return stage.exceptionally(e -> {
    cast(e, CancellationException.class).ifPresent(action);
    return null;
  });
}