Example usage for java.util.concurrent CompletableFuture get

List of usage examples for java.util.concurrent CompletableFuture get

Introduction

In this page you can find the example usage for java.util.concurrent CompletableFuture get.

Prototype

@SuppressWarnings("unchecked")
public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException 

Source Link

Document

Waits if necessary for at most the given time for this future to complete, and then returns its result, if available.

Usage

From source file:io.pravega.segmentstore.server.reading.StorageReaderTests.java

/**
 * Tests the ability to queue dependent reads (subsequent reads that only want to read a part of a previous read).
 * Test this both with successful and failed reads.
 *//* www.  ja v  a2s.  c o  m*/
@Test
public void testDependents() {
    final Duration waitTimeout = Duration.ofSeconds(5);
    TestStorage storage = new TestStorage();
    CompletableFuture<Integer> signal = new CompletableFuture<>();
    AtomicBoolean wasReadInvoked = new AtomicBoolean();
    storage.readImplementation = () -> {
        if (wasReadInvoked.getAndSet(true)) {
            Assert.fail(
                    "Read was invoked multiple times, which is a likely indicator that the requests were not chained.");
        }
        return signal;
    };

    @Cleanup
    StorageReader reader = new StorageReader(SEGMENT_METADATA, storage, executorService());

    // Create some reads.
    CompletableFuture<StorageReader.Result> c1 = new CompletableFuture<>();
    CompletableFuture<StorageReader.Result> c2 = new CompletableFuture<>();
    reader.execute(new StorageReader.Request(0, 100, c1::complete, c1::completeExceptionally, TIMEOUT));
    reader.execute(new StorageReader.Request(50, 100, c2::complete, c2::completeExceptionally, TIMEOUT));

    Assert.assertFalse("One or more of the reads has completed prematurely.", c1.isDone() || c2.isDone());

    signal.completeExceptionally(new IntentionalException());
    AssertExtensions.assertThrows("The first read was not failed with the correct exception.",
            () -> c1.get(waitTimeout.toMillis(), TimeUnit.MILLISECONDS),
            ex -> ex instanceof IntentionalException);

    AssertExtensions.assertThrows("The second read was not failed with the correct exception.",
            () -> c2.get(waitTimeout.toMillis(), TimeUnit.MILLISECONDS),
            ex -> ex instanceof IntentionalException);
}

From source file:io.pravega.segmentstore.server.reading.StorageReadManagerTests.java

/**
 * Tests the ability to queue dependent reads (subsequent reads that only want to read a part of a previous read).
 * Test this both with successful and failed reads.
 *//* ww  w.  ja  v a 2s  .  co  m*/
@Test
public void testDependents() {
    final Duration waitTimeout = Duration.ofSeconds(5);
    TestStorage storage = new TestStorage();
    CompletableFuture<Integer> signal = new CompletableFuture<>();
    AtomicBoolean wasReadInvoked = new AtomicBoolean();
    storage.readImplementation = () -> {
        if (wasReadInvoked.getAndSet(true)) {
            Assert.fail(
                    "Read was invoked multiple times, which is a likely indicator that the requests were not chained.");
        }
        return signal;
    };

    @Cleanup
    StorageReadManager reader = new StorageReadManager(SEGMENT_METADATA, storage, executorService());

    // Create some reads.
    CompletableFuture<StorageReadManager.Result> c1 = new CompletableFuture<>();
    CompletableFuture<StorageReadManager.Result> c2 = new CompletableFuture<>();
    reader.execute(new StorageReadManager.Request(0, 100, c1::complete, c1::completeExceptionally, TIMEOUT));
    reader.execute(new StorageReadManager.Request(50, 100, c2::complete, c2::completeExceptionally, TIMEOUT));

    Assert.assertFalse("One or more of the reads has completed prematurely.", c1.isDone() || c2.isDone());

    signal.completeExceptionally(new IntentionalException());
    AssertExtensions.assertThrows("The first read was not failed with the correct exception.",
            () -> c1.get(waitTimeout.toMillis(), TimeUnit.MILLISECONDS),
            ex -> ex instanceof IntentionalException);

    AssertExtensions.assertThrows("The second read was not failed with the correct exception.",
            () -> c2.get(waitTimeout.toMillis(), TimeUnit.MILLISECONDS),
            ex -> ex instanceof IntentionalException);
}

From source file:io.ventu.rpc.amqp.AmqpInvokerimplTest.java

@Test
public void responseReceiver_handleDelivery_responseValidated()
        throws EncodingException, IOException, InterruptedException, ExecutionException, TimeoutException {
    final List<Boolean> invocations = Lists.newArrayList();
    Validator validator = new Validator() {
        @Override//from ww w .j  av a2  s.  c  o m
        public <T> void validate(T value) throws ApiException, IllegalArgumentException {
            invocations.add(Boolean.TRUE);
            assertTrue(value instanceof Res);
            assertEquals(25, ((Res) value).value);
        }
    };
    ResponseReceiverImpl receiver = new ResponseReceiverImpl(serializer, validator, 1, TimeUnit.MINUTES);

    Res res = new Res();
    res.value = 25;

    String correlationId = "987654321";
    CompletableFuture<Res> answer = receiver.put(correlationId, Res.class);
    assertFalse(answer.isDone());
    assertFalse(answer.isCompletedExceptionally());

    receiver.handleDelivery(correlationId, serializer.encode(res));
    assertEquals(1, invocations.size());
    assertTrue(answer.isDone());
    assertFalse(answer.isCompletedExceptionally());

    Res actual = answer.get(500, TimeUnit.MILLISECONDS);
    assertEquals(25, actual.value);
}

From source file:org.apache.storm.messaging.netty.NettyTest.java

private void doTestServerDelayed(Map<String, Object> stormConf) throws Exception {
    LOG.info("4. test server delayed");
    String reqMessage = "0123456789abcdefghijklmnopqrstuvwxyz";
    IContext context = TransportFactory.makeContext(stormConf);
    try {//w w  w  . j  a  v a2  s  .  co  m
        AtomicReference<TaskMessage> response = new AtomicReference<>();
        int port = Utils.getAvailablePort(6700);
        try (IConnection client = context.connect(null, "localhost", port, remoteBpStatus)) {
            AtomicReference<IConnection> server = new AtomicReference<>();
            try {
                CompletableFuture<?> serverStart = CompletableFuture.runAsync(() -> {
                    try {
                        Thread.sleep(100);
                        server.set(context.bind(null, port));
                        server.get().registerRecv(mkConnectionCallback(response::set));
                        waitUntilReady(client, server.get());
                    } catch (Exception e) {
                        throw Utils.wrapInRuntime(e);
                    }
                });
                serverStart.get(Testing.TEST_TIMEOUT_MS, TimeUnit.MILLISECONDS);
                byte[] messageBytes = reqMessage.getBytes(StandardCharsets.UTF_8);

                send(client, taskId, messageBytes);

                waitForNotNull(response);
                TaskMessage responseMessage = response.get();
                assertThat(responseMessage.task(), is(taskId));
                assertThat(responseMessage.message(), is(messageBytes));
            } finally {
                if (server.get() != null) {
                    server.get().close();
                }
            }
        }
    } finally {
        context.term();
    }
}

From source file:org.apache.flink.client.cli.CliFrontend.java

/**
 * Sends a {@link JobManagerMessages.DisposeSavepoint} message to the job manager.
 *//* www  .  j  a v  a2 s . com*/
private void disposeSavepoint(ClusterClient<?> clusterClient, String savepointPath) throws FlinkException {
    Preconditions.checkNotNull(savepointPath,
            "Missing required argument: savepoint path. " + "Usage: bin/flink savepoint -d <savepoint-path>");

    logAndSysout("Disposing savepoint '" + savepointPath + "'.");

    final CompletableFuture<Acknowledge> disposeFuture = clusterClient.disposeSavepoint(savepointPath);

    logAndSysout("Waiting for response...");

    try {
        disposeFuture.get(clientTimeout.toMillis(), TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        throw new FlinkException("Disposing the savepoint '" + savepointPath + "' failed.", e);
    }

    logAndSysout("Savepoint '" + savepointPath + "' disposed.");
}

From source file:org.apache.flink.runtime.rest.RestServerEndpointITCase.java

@Test
public void testVersioning() throws Exception {
    CompletableFuture<EmptyResponseBody> unspecifiedVersionResponse = restClient.sendRequest(
            serverAddress.getHostName(), serverAddress.getPort(), TestVersionHeaders.INSTANCE,
            EmptyMessageParameters.getInstance(), EmptyRequestBody.getInstance(), Collections.emptyList());

    unspecifiedVersionResponse.get(5, TimeUnit.SECONDS);

    CompletableFuture<EmptyResponseBody> specifiedVersionResponse = restClient.sendRequest(
            serverAddress.getHostName(), serverAddress.getPort(), TestVersionHeaders.INSTANCE,
            EmptyMessageParameters.getInstance(), EmptyRequestBody.getInstance(), Collections.emptyList(),
            RestAPIVersion.V1);/* ww  w  .  ja v  a 2s.  co m*/

    specifiedVersionResponse.get(5, TimeUnit.SECONDS);
}

From source file:io.pravega.segmentstore.server.containers.StreamSegmentMapperTests.java

/**
 * Tests the ability of the StreamSegmentMapper to generate/return the Id of an existing StreamSegment, with concurrent requests.
 *///from  w w w. j a v a 2 s .c  om
@Test
public void testGetOrAssignStreamSegmentIdWithConcurrency() throws Exception {
    // We setup a delay in the OperationLog process. We only do this for a stand-alone StreamSegment because the process
    // is driven by the same code for Transactions as well.
    final String segmentName = "Segment";
    final long segmentId = 12345;

    HashSet<String> storageSegments = new HashSet<>();
    storageSegments.add(segmentName);

    @Cleanup
    TestContext context = new TestContext();
    setupStorageGetHandler(context, storageSegments,
            sn -> new StreamSegmentInformation(sn, 0, false, false, new ImmutableDate()));
    CompletableFuture<Long> initialAddFuture = new CompletableFuture<>();
    AtomicBoolean operationLogInvoked = new AtomicBoolean(false);
    context.operationLog.addHandler = op -> {
        if (!(op instanceof StreamSegmentMapOperation)) {
            return FutureHelpers.failedFuture(new IllegalArgumentException("unexpected operation"));
        }
        if (operationLogInvoked.getAndSet(true)) {
            return FutureHelpers.failedFuture(new IllegalStateException("multiple calls to OperationLog.add"));
        }

        // Need to set SegmentId on operation.
        ((StreamSegmentMapOperation) op).setStreamSegmentId(segmentId);
        return initialAddFuture;
    };

    CompletableFuture<Long> firstCall = context.mapper.getOrAssignStreamSegmentId(segmentName, TIMEOUT);
    CompletableFuture<Long> secondCall = context.mapper.getOrAssignStreamSegmentId(segmentName, TIMEOUT);
    Thread.sleep(20);
    Assert.assertFalse("getOrAssignStreamSegmentId (first call) returned before OperationLog finished.",
            firstCall.isDone());
    Assert.assertFalse("getOrAssignStreamSegmentId (second call) returned before OperationLog finished.",
            secondCall.isDone());
    initialAddFuture.complete(1L);
    long firstCallResult = firstCall.get(100, TimeUnit.MILLISECONDS);
    long secondCallResult = secondCall.get(100, TimeUnit.MILLISECONDS);

    Assert.assertEquals(
            "Two concurrent calls to getOrAssignStreamSegmentId for the same StreamSegment returned different ids.",
            firstCallResult, secondCallResult);
}

From source file:org.apache.flink.runtime.rest.RestServerEndpointITCase.java

@Test
public void testVersionSelection() throws Exception {
    CompletableFuture<EmptyResponseBody> version1Response = restClient.sendRequest(serverAddress.getHostName(),
            serverAddress.getPort(), TestVersionSelectionHeaders1.INSTANCE,
            EmptyMessageParameters.getInstance(), EmptyRequestBody.getInstance(), Collections.emptyList(),
            RestAPIVersion.V0);//from w w w.  java 2  s . c  om

    try {
        version1Response.get(5, TimeUnit.SECONDS);
        fail();
    } catch (ExecutionException ee) {
        RestClientException rce = (RestClientException) ee.getCause();
        assertEquals(HttpResponseStatus.OK, rce.getHttpResponseStatus());
    }

    CompletableFuture<EmptyResponseBody> version2Response = restClient.sendRequest(serverAddress.getHostName(),
            serverAddress.getPort(), TestVersionSelectionHeaders2.INSTANCE,
            EmptyMessageParameters.getInstance(), EmptyRequestBody.getInstance(), Collections.emptyList(),
            RestAPIVersion.V1);

    try {
        version2Response.get(5, TimeUnit.SECONDS);
        fail();
    } catch (ExecutionException ee) {
        RestClientException rce = (RestClientException) ee.getCause();
        assertEquals(HttpResponseStatus.ACCEPTED, rce.getHttpResponseStatus());
    }
}

From source file:org.springframework.integration.aggregator.AggregatorTests.java

@Test
public void testCustomAggPerf() throws InterruptedException, ExecutionException, TimeoutException {
    class CustomHandler extends AbstractMessageHandler {

        // custom aggregator, only handles a single correlation

        private final ReentrantLock lock = new ReentrantLock();

        private final Collection<Message<?>> messages = new ArrayList<Message<?>>(60000);

        private final MessageChannel outputChannel;

        private CustomHandler(MessageChannel outputChannel) {
            this.outputChannel = outputChannel;
        }/*from w  ww .j a v a2 s  . c o  m*/

        @Override
        public void handleMessageInternal(Message<?> requestMessage) {
            lock.lock();
            try {
                this.messages.add(requestMessage);
                if (this.messages.size() == 60000) {
                    List<Object> payloads = new ArrayList<Object>(this.messages.size());
                    for (Message<?> message : this.messages) {
                        payloads.add(message.getPayload());
                    }
                    this.messages.clear();
                    outputChannel.send(getMessageBuilderFactory().withPayload(payloads)
                            .copyHeaders(requestMessage.getHeaders()).build());
                }
            } finally {
                lock.unlock();
            }
        }

    }

    DirectChannel outputChannel = new DirectChannel();
    CustomHandler handler = new CustomHandler(outputChannel);

    final CompletableFuture<Collection<?>> resultFuture = new CompletableFuture<>();
    outputChannel.subscribe(message -> {
        Collection<?> payload = (Collection<?>) message.getPayload();
        logger.warn("Received " + payload.size());
        resultFuture.complete(payload);
    });
    Message<?> message = new GenericMessage<String>("foo");
    StopWatch stopwatch = new StopWatch();
    stopwatch.start();
    for (int i = 0; i < 120000; i++) {
        if (i % 10000 == 0) {
            stopwatch.stop();
            logger.warn("Sent " + i + " in " + stopwatch.getTotalTimeSeconds() + " (10k in "
                    + stopwatch.getLastTaskTimeMillis() + "ms)");
            stopwatch.start();
        }
        handler.handleMessage(message);
    }
    stopwatch.stop();
    logger.warn("Sent " + 120000 + " in " + stopwatch.getTotalTimeSeconds() + " (10k in "
            + stopwatch.getLastTaskTimeMillis() + "ms)");

    Collection<?> result = resultFuture.get(10, TimeUnit.SECONDS);
    assertNotNull(result);
    assertEquals(60000, result.size());
}

From source file:org.apache.flink.runtime.rest.RestServerEndpointITCase.java

/**
 * Tests that after calling {@link RestServerEndpoint#closeAsync()}, the handlers are closed
 * first, and we wait for in-flight requests to finish. As long as not all handlers are closed,
 * HTTP requests should be served.//from   w w w.ja  v a  2  s . c  o m
 */
@Test
public void testShouldWaitForHandlersWhenClosing() throws Exception {
    testHandler.closeFuture = new CompletableFuture<>();
    final HandlerBlocker handlerBlocker = new HandlerBlocker(timeout);
    testHandler.handlerBody = id -> {
        // Intentionally schedule the work on a different thread. This is to simulate
        // handlers where the CompletableFuture is finished by the RPC framework.
        return CompletableFuture.supplyAsync(() -> {
            handlerBlocker.arriveAndBlock();
            return new TestResponse(id);
        });
    };

    // Initiate closing RestServerEndpoint but the test handler should block.
    final CompletableFuture<Void> closeRestServerEndpointFuture = serverEndpoint.closeAsync();
    assertThat(closeRestServerEndpointFuture.isDone(), is(false));

    final CompletableFuture<TestResponse> request = sendRequestToTestHandler(new TestRequest(1));
    handlerBlocker.awaitRequestToArrive();

    // Allow handler to close but there is still one in-flight request which should prevent
    // the RestServerEndpoint from closing.
    testHandler.closeFuture.complete(null);
    assertThat(closeRestServerEndpointFuture.isDone(), is(false));

    // Finish the in-flight request.
    handlerBlocker.unblockRequest();

    request.get(timeout.getSize(), timeout.getUnit());
    closeRestServerEndpointFuture.get(timeout.getSize(), timeout.getUnit());
}