Java Code Examples for java.util.concurrent.CompletableFuture#cancel()

The following examples show how to use java.util.concurrent.CompletableFuture#cancel() . 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: AsyncOperationCancelTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testEventStreamingOperation() {
    CompletableFuture<Void> responseFuture = client.eventStreamOperation(r -> {
            },
            subscriber -> {},
            new EventStreamOperationResponseHandler() {
                @Override
                public void responseReceived(EventStreamOperationResponse response) {
                }

                @Override
                public void onEventStream(SdkPublisher<EventStream> publisher) {
                }

                @Override
                public void exceptionOccurred(Throwable throwable) {
                }

                @Override
                public void complete() {
                }
            });
    responseFuture.cancel(true);
    assertThat(executeFuture.isCompletedExceptionally()).isTrue();
    assertThat(executeFuture.isCancelled()).isTrue();
}
 
Example 2
Source File: JDTLanguageServer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<CompletionItem> resolveCompletionItem(CompletionItem unresolved) {
	logInfo(">> document/resolveCompletionItem");
	CompletionResolveHandler handler = new CompletionResolveHandler(preferenceManager);
	final IProgressMonitor[] monitors = new IProgressMonitor[1];
	CompletableFuture<CompletionItem> result = computeAsync((monitor) -> {
		monitors[0] = monitor;
		if ((Boolean.getBoolean(JAVA_LSP_JOIN_ON_COMPLETION))) {
			waitForLifecycleJobs(monitor);
		}
		return handler.resolve(unresolved, monitor);
	});
	result.join();
	if (monitors[0].isCanceled()) {
		result.cancel(true);
	}
	return result;
}
 
Example 3
Source File: UpnpNatManager.java    From besu with Apache License 2.0 6 votes vote down vote up
/**
 * Stop the manager. Must not be in stopped state.
 *
 * @throws IllegalStateException if stopped.
 */
@Override
public synchronized void doStop() {
  CompletableFuture<Void> portForwardReleaseFuture = releaseAllPortForwards();
  try {
    LOG.info("Allowing 3 seconds to release all port forwards...");
    portForwardReleaseFuture.get(3, TimeUnit.SECONDS);
  } catch (Exception e) {
    LOG.warn("Caught exception while trying to release port forwards, ignoring", e);
  }

  for (CompletableFuture<RemoteService> future : recognizedServices.values()) {
    future.cancel(true);
  }

  upnpService.getRegistry().removeListener(registryListener);
  upnpService.shutdown();
}
 
Example 4
Source File: RpcChannelFactory.java    From barge with Apache License 2.0 5 votes vote down vote up
@Override
public void destroyObject(Object key, CompletableFuture<NettyRpcChannel> obj) throws Exception {
  if (obj.isDone() && !obj.isCancelled()) {
    obj.get().close();
  } else {
    obj.cancel(false);
  }
}
 
Example 5
Source File: AsyncOperationCancelTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testStreamingOutputOperation() {
    CompletableFuture<ResponseBytes<StreamingOutputOperationResponse>> responseFuture = client.streamingOutputOperation(r -> {
    }, AsyncResponseTransformer.toBytes());
    responseFuture.cancel(true);
    assertThat(executeFuture.isCompletedExceptionally()).isTrue();
    assertThat(executeFuture.isCancelled()).isTrue();
}
 
Example 6
Source File: BlockingDrainingQueue.java    From pravega with Apache License 2.0 5 votes vote down vote up
/**
 * Cancels any pending Future from a take() operation.
 */
public void cancelPendingTake() {
    CompletableFuture<Queue<T>> pending;
    synchronized (this.contents) {
        pending = this.pendingTake;
        this.pendingTake = null;
    }

    // Cancel any pending poll request.
    if (pending != null) {
        pending.cancel(true);
    }
}
 
Example 7
Source File: CompletableFutureTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * runAfterBoth result completes exceptionally if either source cancelled
 */
public void testRunAfterBoth_sourceCancelled() throws Throwable {
    for (ExecutionMode m : ExecutionMode.values())
    for (boolean mayInterruptIfRunning : new boolean[] { true, false })
    for (boolean fFirst : new boolean[] { true, false })
    for (boolean failFirst : new boolean[] { true, false })
    for (Integer v1 : new Integer[] { 1, null })
{
    final CompletableFuture<Integer> f = new CompletableFuture<>();
    final CompletableFuture<Integer> g = new CompletableFuture<>();
    final Noop r1 = new Noop(m);
    final Noop r2 = new Noop(m);
    final Noop r3 = new Noop(m);

    final CompletableFuture<Integer> fst =  fFirst ? f : g;
    final CompletableFuture<Integer> snd = !fFirst ? f : g;
    final Callable<Boolean> complete1 = failFirst ?
        () -> fst.cancel(mayInterruptIfRunning) :
        () -> fst.complete(v1);
    final Callable<Boolean> complete2 = failFirst ?
        () -> snd.complete(v1) :
        () -> snd.cancel(mayInterruptIfRunning);

    final CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
    assertTrue(complete1.call());
    final CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
    checkIncomplete(h1);
    checkIncomplete(h2);
    assertTrue(complete2.call());
    final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);

    checkCompletedWithWrappedCancellationException(h1);
    checkCompletedWithWrappedCancellationException(h2);
    checkCompletedWithWrappedCancellationException(h3);
    r1.assertNotInvoked();
    r2.assertNotInvoked();
    r3.assertNotInvoked();
    checkCompletedNormally(failFirst ? snd : fst, v1);
    checkCancelled(failFirst ? fst : snd);
}}
 
Example 8
Source File: MapPipelinedCursor.java    From fdb-record-layer with Apache License 2.0 5 votes vote down vote up
@Nonnull
private RecordCursorContinuation cancelPendingFutures() {
    Iterator<CompletableFuture<RecordCursorResult<V>>> iter = pipeline.iterator();
    // The earliest continuation we could need to start with is the one from the last returned result.
    // We may, however, return more results if they are already completed.
    RecordCursorContinuation continuation = nextResult.getContinuation();
    while (iter.hasNext()) {
        CompletableFuture<RecordCursorResult<V>> pendingEntry = iter.next();
        if (!pendingEntry.isDone()) {
            // Once we have found an entry that is not done, cancel that and all remaining
            // futures, remove them from the pipeline, and do *not* update the continuation.
            while (true) {
                iter.remove();
                pendingEntry.cancel(false);
                if (!iter.hasNext()) {
                    return continuation;
                }
                pendingEntry = iter.next();
            }
        } else {
            // Entry is done, so this cursor will return this result. Keep the entry
            // in the pipeline, and update the continuation.
            continuation = pendingEntry.join().getContinuation();
        }
    }
    return continuation;
}
 
Example 9
Source File: UtilsTest.java    From mug with Apache License 2.0 5 votes vote down vote up
@Test public void testPropagateCancellation_cancellationWithInterruptionPropagated() {
  CompletableFuture<String> outer = new CompletableFuture<>();
  CompletableFuture<String> inner = new CompletableFuture<>();
  assertThat(Utils.propagateCancellation(outer, inner)).isSameAs(outer);
  outer.cancel(true);
  assertThat(outer.isCancelled()).isTrue();
  assertThat(inner.isCancelled()).isTrue();
  assertThat(outer.isDone()).isTrue();
  assertThat(inner.isDone()).isTrue();
  assertThrows(CancellationException.class, inner::get);
}
 
Example 10
Source File: ProgMainHttp2Client.java    From javase with MIT License 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    try {
        HttpClient httpClient = HttpClient.newHttpClient(); //Create a HttpClient
        System.out.println(httpClient.version());
        HttpRequest httpRequest = 
        		HttpRequest.newBuilder().uri(new URI("https://www.google.com/")).GET().build(); //Create a GET request for the given URI
        Map <String, List<String> > headers = httpRequest.headers().map();
        headers.forEach((k, v) -> System.out.println(k + "-" + v));
        HttpResponse < String > httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandler.asString());
        //System.out.println("HTTP2 response = \n" + httpResponse.body());
    
        CompletableFuture<HttpResponse<String>> httpResponse2 
        	= httpClient.sendAsync(httpRequest, HttpResponse.BodyHandler.asString());
        
        Thread.currentThread().sleep(5000);
        
        if(httpResponse2.isDone()) {
        	System.out.println("\n\n httpResponse2 = \n");
            System.out.println(httpResponse2.get().statusCode());
            System.out.println(httpResponse2.get().body());
        } else {
        	System.out.println("Response not received!");
            httpResponse2.cancel(true);
        }
        
        //Thread.currentThread().sleep(5000);
    } catch (Exception e) {
        System.out.println("message " + e);
    }
}
 
Example 11
Source File: CompletableFutureTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * runAfterBoth result completes exceptionally if either source cancelled
 */
public void testRunAfterBoth_sourceCancelled() throws Throwable {
    for (ExecutionMode m : ExecutionMode.values())
    for (boolean mayInterruptIfRunning : new boolean[] { true, false })
    for (boolean fFirst : new boolean[] { true, false })
    for (boolean failFirst : new boolean[] { true, false })
    for (Integer v1 : new Integer[] { 1, null })
{
    final CompletableFuture<Integer> f = new CompletableFuture<>();
    final CompletableFuture<Integer> g = new CompletableFuture<>();
    final Noop r1 = new Noop(m);
    final Noop r2 = new Noop(m);
    final Noop r3 = new Noop(m);

    final CompletableFuture<Integer> fst =  fFirst ? f : g;
    final CompletableFuture<Integer> snd = !fFirst ? f : g;
    final Callable<Boolean> complete1 = failFirst ?
        () -> fst.cancel(mayInterruptIfRunning) :
        () -> fst.complete(v1);
    final Callable<Boolean> complete2 = failFirst ?
        () -> snd.complete(v1) :
        () -> snd.cancel(mayInterruptIfRunning);

    final CompletableFuture<Void> h1 = m.runAfterBoth(f, g, r1);
    assertTrue(complete1.call());
    final CompletableFuture<Void> h2 = m.runAfterBoth(f, g, r2);
    checkIncomplete(h1);
    checkIncomplete(h2);
    assertTrue(complete2.call());
    final CompletableFuture<Void> h3 = m.runAfterBoth(f, g, r3);

    checkCompletedWithWrappedCancellationException(h1);
    checkCompletedWithWrappedCancellationException(h2);
    checkCompletedWithWrappedCancellationException(h3);
    r1.assertNotInvoked();
    r2.assertNotInvoked();
    r3.assertNotInvoked();
    checkCompletedNormally(failFirst ? snd : fst, v1);
    checkCancelled(failFirst ? fst : snd);
}}
 
Example 12
Source File: StreamIOTest.java    From riptide with MIT License 5 votes vote down vote up
@Test
void shouldCancelRequest() throws IOException {
    driver.addExpectation(onRequestTo("/repos/zalando/riptide/contributors"),
            giveResponseAsBytes(getResource("contributors.json").openStream(), "application/json"));

    final CompletableFuture<ClientHttpResponse> future = http.get("/repos/{org}/{repo}/contributors", "zalando",
            "riptide")
            .dispatch(series(),
                    on(SUCCESSFUL).call(pass()));

    future.cancel(true);

    assertThrows(CancellationException.class, future::join);
}
 
Example 13
Source File: UtilsTest.java    From mug with Apache License 2.0 5 votes vote down vote up
@Test public void testPropagateCancellation_innerAlreadyCompleted() throws Exception {
  CompletableFuture<String> outer = new CompletableFuture<>();
  CompletableFuture<String> inner = new CompletableFuture<>();
  assertThat(Utils.propagateCancellation(outer, inner)).isSameAs(outer);
  inner.complete("inner");
  outer.cancel(false);
  assertThat(outer.isCancelled()).isTrue();
  assertThat(inner.isCancelled()).isFalse();
  assertThat(outer.isCompletedExceptionally()).isTrue();
  assertThat(inner.isCompletedExceptionally()).isFalse();
  assertThat(outer.isDone()).isTrue();
  assertThat(inner.isDone()).isTrue();
  assertThat(inner.get()).isEqualTo("inner");
}
 
Example 14
Source File: PipelineBuilderTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldAbortPipelineWhenFutureIsCancelled() throws Exception {
  final int allowProcessingUpTo = 5;
  final AtomicBoolean processorInterrupted = new AtomicBoolean(false);
  final List<Integer> output = synchronizedList(new ArrayList<>());
  final CountDownLatch startedProcessingValueSix = new CountDownLatch(1);
  final Pipeline<Integer> pipeline =
      PipelineBuilder.createPipelineFrom("input", tasks, 10, NO_OP_LABELLED_2_COUNTER)
          .thenProcess(
              "stageName",
              value -> {
                if (value > allowProcessingUpTo) {
                  try {
                    startedProcessingValueSix.countDown();
                    Thread.sleep(TimeUnit.MINUTES.toNanos(2));
                  } catch (final InterruptedException e) {
                    processorInterrupted.set(true);
                  }
                }
                return value;
              })
          .andFinishWith("end", output::add);

  final CompletableFuture<?> result = pipeline.start(executorService);

  startedProcessingValueSix.await(10, SECONDS);
  waitForSize(output, allowProcessingUpTo);

  result.cancel(false);

  assertThatThrownBy(() -> result.get(10, SECONDS)).isInstanceOf(CancellationException.class);
  assertThat(output).containsExactly(1, 2, 3, 4, 5);

  waitAtMost(10, SECONDS).untilAsserted(() -> assertThat(processorInterrupted).isTrue());
}
 
Example 15
Source File: BeamFnDataGrpcMultiplexer.java    From beam with Apache License 2.0 5 votes vote down vote up
@Override
public void close() {
  for (CompletableFuture<BiConsumer<ByteString, Boolean>> receiver :
      ImmutableList.copyOf(consumers.values())) {
    // Cancel any observer waiting for the client to complete. If the receiver has already been
    // completed or cancelled, this call will be ignored.
    receiver.cancel(true);
  }
  // Cancel any outbound calls and complete any inbound calls, as this multiplexer is hanging up
  outboundObserver.onError(
      Status.CANCELLED.withDescription("Multiplexer hanging up").asException());
  inboundObserver.onCompleted();
}
 
Example 16
Source File: PingTests.java    From nats.java with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandlingPing() throws IOException, InterruptedException,ExecutionException {
    CompletableFuture<Boolean> gotPong = new CompletableFuture<>();

    NatsServerProtocolMock.Customizer pingPongCustomizer = (ts, r,w) -> {
        
        System.out.println("*** Mock Server @" + ts.getPort() + " sending PING ...");
        w.write("PING\r\n");
        w.flush();

        String pong = "";
        
        System.out.println("*** Mock Server @" + ts.getPort() + " waiting for PONG ...");
        try {
            pong = r.readLine();
        } catch(Exception e) {
            gotPong.cancel(true);
            return;
        }

        if (pong.startsWith("PONG")) {
            System.out.println("*** Mock Server @" + ts.getPort() + " got PONG ...");
            gotPong.complete(Boolean.TRUE);
        } else {
            System.out.println("*** Mock Server @" + ts.getPort() + " got something else... " + pong);
            gotPong.complete(Boolean.FALSE);
        }
    };

    try (NatsServerProtocolMock ts = new NatsServerProtocolMock(pingPongCustomizer)) {
        Connection  nc = Nats.connect(ts.getURI());
        try {
            assertTrue("Connected Status", Connection.Status.CONNECTED == nc.getStatus());
            assertTrue("Got pong.", gotPong.get().booleanValue());
        } finally {
            nc.close();
            assertTrue("Closed Status", Connection.Status.CLOSED == nc.getStatus());
        }
    }
}
 
Example 17
Source File: UtilsTest.java    From mug with Apache License 2.0 5 votes vote down vote up
@Test public void testIfCancelled_cancelledWithInterruption() {
  AtomicReference<CancellationException> cancelled = new AtomicReference<>();
  CompletableFuture<String> future = new CompletableFuture<>();
  future.cancel(true);
  Utils.ifCancelled(future, cancelled::set);
  assertThat(cancelled.get()).isInstanceOf(CancellationException.class);
}
 
Example 18
Source File: AsynchronousResources.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
@Produces(TEXT_PLAIN)
@Path("/failed-text")
@GET
public CompletionStage<String> getFailed(@QueryParam("cancel") final boolean cancel) {
    final CompletableFuture<String> cf = new CompletableFuture<>();
    if (cancel) {
        cf.cancel(true);
    } else {
        cf.completeExceptionally(DELIBERATE_EXCEPTION);
    }
    return cf;
}
 
Example 19
Source File: RestClientTest.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
/**
 * Tests that we fail the operation if the remote connection closes.
 */
@Test
public void testConnectionClosedHandling() throws Exception {
	final Configuration config = new Configuration();
	config.setLong(RestOptions.IDLENESS_TIMEOUT, 5000L);
	try (final ServerSocket serverSocket = new ServerSocket(0);
		final RestClient restClient = new RestClient(RestClientConfiguration.fromConfiguration(config), TestingUtils.defaultExecutor())) {

		final String targetAddress = "localhost";
		final int targetPort = serverSocket.getLocalPort();

		// start server
		final CompletableFuture<Socket> socketCompletableFuture = CompletableFuture.supplyAsync(CheckedSupplier.unchecked(serverSocket::accept));

		final CompletableFuture<EmptyResponseBody> responseFuture = restClient.sendRequest(
			targetAddress,
			targetPort,
			new TestMessageHeaders(),
			EmptyMessageParameters.getInstance(),
			EmptyRequestBody.getInstance(),
			Collections.emptyList());

		Socket connectionSocket = null;

		try {
			connectionSocket = socketCompletableFuture.get(TIMEOUT, TimeUnit.SECONDS);
		} catch (TimeoutException ignored) {
			// could not establish a server connection --> see that the response failed
			socketCompletableFuture.cancel(true);
		}

		if (connectionSocket != null) {
			// close connection
			connectionSocket.close();
		}

		try {
			responseFuture.get();
		} catch (ExecutionException ee) {
			if (!ExceptionUtils.findThrowable(ee, IOException.class).isPresent()) {
				throw ee;
			}
		}
	}
}
 
Example 20
Source File: FutureUtilsTest.java    From flink with Apache License 2.0 4 votes vote down vote up
/**
 * Tests that we can cancel a retry future.
 */
@Test
public void testRetryCancellation() throws Exception {
	final int retries = 10;
	final AtomicInteger atomicInteger = new AtomicInteger(0);
	final OneShotLatch notificationLatch = new OneShotLatch();
	final OneShotLatch waitLatch = new OneShotLatch();
	final AtomicReference<Throwable> atomicThrowable = new AtomicReference<>(null);

	CompletableFuture<?> retryFuture = FutureUtils.retry(
		() ->
			CompletableFuture.supplyAsync(
				() -> {
					if (atomicInteger.incrementAndGet() == 2) {
						notificationLatch.trigger();
						try {
							waitLatch.await();
						} catch (InterruptedException e) {
							atomicThrowable.compareAndSet(null, e);
						}
					}

					throw new CompletionException(new FlinkException("Test exception"));
				},
				TestingUtils.defaultExecutor()),
		retries,
		TestingUtils.defaultExecutor());

	// await that we have failed once
	notificationLatch.await();

	assertFalse(retryFuture.isDone());

	// cancel the retry future
	retryFuture.cancel(false);

	// let the retry operation continue
	waitLatch.trigger();

	assertTrue(retryFuture.isCancelled());
	assertEquals(2, atomicInteger.get());

	if (atomicThrowable.get() != null) {
		throw new FlinkException("Exception occurred in the retry operation.", atomicThrowable.get());
	}
}