Example usage for java.util.concurrent CompletableFuture complete

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

Introduction

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

Prototype

public boolean complete(T value) 

Source Link

Document

If not already completed, sets the value returned by #get() and related methods to the given value.

Usage

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

@Test
public void testAggPerfDefaultPartial() throws InterruptedException, ExecutionException, TimeoutException {
    AggregatingMessageHandler handler = new AggregatingMessageHandler(
            new DefaultAggregatingMessageGroupProcessor());
    handler.setCorrelationStrategy(message -> "foo");
    handler.setReleasePartialSequences(true);
    DirectChannel outputChannel = new DirectChannel();
    handler.setOutputChannel(outputChannel);

    final CompletableFuture<Collection<?>> resultFuture = new CompletableFuture<>();
    outputChannel.subscribe(message -> {
        Collection<?> payload = (Collection<?>) message.getPayload();
        logger.warn("Received " + payload.size());
        resultFuture.complete(payload);
    });/*w  w  w.j  a v  a  2 s  .c  o m*/

    SimpleMessageStore store = new SimpleMessageStore();

    SimpleMessageGroupFactory messageGroupFactory = new SimpleMessageGroupFactory(
            SimpleMessageGroupFactory.GroupType.BLOCKING_QUEUE);

    store.setMessageGroupFactory(messageGroupFactory);

    handler.setMessageStore(store);

    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(
                MessageBuilder.withPayload("foo").setSequenceSize(120000).setSequenceNumber(i + 1).build());
    }
    stopwatch.stop();
    logger.warn("Sent " + 120000 + " in " + stopwatch.getTotalTimeSeconds() + " (10k in "
            + stopwatch.getLastTaskTimeMillis() + "ms)");

    Collection<?> result = resultFuture.get(10, TimeUnit.SECONDS);
    assertNotNull(result);
    assertEquals(120000, result.size());
    assertThat(stopwatch.getTotalTimeSeconds(), lessThan(60.0)); // actually < 2.0, was many minutes
}

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

@Test
public void testAggPerf() throws InterruptedException, ExecutionException, TimeoutException {
    AggregatingMessageHandler handler = new AggregatingMessageHandler(
            new DefaultAggregatingMessageGroupProcessor());
    handler.setCorrelationStrategy(message -> "foo");
    handler.setReleaseStrategy(new MessageCountReleaseStrategy(60000));
    handler.setExpireGroupsUponCompletion(true);
    handler.setSendPartialResultOnExpiry(true);
    DirectChannel outputChannel = new DirectChannel();
    handler.setOutputChannel(outputChannel);

    final CompletableFuture<Collection<?>> resultFuture = new CompletableFuture<>();
    outputChannel.subscribe(message -> {
        Collection<?> payload = (Collection<?>) message.getPayload();
        logger.warn("Received " + payload.size());
        resultFuture.complete(payload);
    });//from  w  ww  . j a  v a  2 s. co m

    SimpleMessageStore store = new SimpleMessageStore();

    SimpleMessageGroupFactory messageGroupFactory = new SimpleMessageGroupFactory(
            SimpleMessageGroupFactory.GroupType.BLOCKING_QUEUE);

    store.setMessageGroupFactory(messageGroupFactory);

    handler.setMessageStore(store);

    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:com.yahoo.pulsar.common.naming.NamespaceBundleFactory.java

public NamespaceBundleFactory(PulsarService pulsar, HashFunction hashFunc) {
    this.hashFunc = hashFunc;

    this.bundlesCache = Caffeine.newBuilder().buildAsync((NamespaceName namespace, Executor executor) -> {
        String path = AdminResource.joinPath(LOCAL_POLICIES_ROOT, namespace.toString());
        if (LOG.isDebugEnabled()) {
            LOG.debug("Loading cache with bundles for {}", namespace);
        }/*from  w w  w.j  a  v  a 2  s .co  m*/

        if (pulsar == null || pulsar.getConfigurationCache() == null) {
            return CompletableFuture.completedFuture(getBundles(namespace, null));
        }

        CompletableFuture<NamespaceBundles> future = new CompletableFuture<>();
        // Read the static bundle data from the policies
        pulsar.getLocalZkCacheService().policiesCache().getAsync(path).thenAccept(policies -> {
            // If no policies defined for namespace, assume 1 single bundle
            BundlesData bundlesData = policies.map(p -> p.bundles).orElse(null);
            NamespaceBundles namespaceBundles = getBundles(namespace, bundlesData);
            future.complete(namespaceBundles);
        }).exceptionally(ex -> {
            future.completeExceptionally(ex);
            return null;
        });
        return future;
    });

    if (pulsar != null && pulsar.getConfigurationCache() != null) {
        pulsar.getLocalZkCacheService().policiesCache().registerListener(this);
    }

    this.pulsar = pulsar;
}

From source file:org.apache.pulsar.client.impl.BinaryProtoLookupService.java

private CompletableFuture<PartitionedTopicMetadata> getPartitionedTopicMetadata(InetSocketAddress socketAddress,
        TopicName topicName) {/*from   w  ww. ja va 2 s .com*/

    CompletableFuture<PartitionedTopicMetadata> partitionFuture = new CompletableFuture<PartitionedTopicMetadata>();

    client.getCnxPool().getConnection(socketAddress).thenAccept(clientCnx -> {
        long requestId = client.newRequestId();
        ByteBuf request = Commands.newPartitionMetadataRequest(topicName.toString(), requestId);
        clientCnx.newLookup(request, requestId).thenAccept(lookupDataResult -> {
            try {
                partitionFuture.complete(new PartitionedTopicMetadata(lookupDataResult.partitions));
            } catch (Exception e) {
                partitionFuture.completeExceptionally(new PulsarClientException.LookupException(
                        format("Failed to parse partition-response redirect=%s , partitions with %s",
                                lookupDataResult.redirect, lookupDataResult.partitions, e.getMessage())));
            }
        }).exceptionally((e) -> {
            log.warn("[{}] failed to get Partitioned metadata : {}", topicName.toString(),
                    e.getCause().getMessage(), e);
            partitionFuture.completeExceptionally(e);
            return null;
        });
    }).exceptionally(connectionException -> {
        partitionFuture.completeExceptionally(connectionException);
        return null;
    });

    return partitionFuture;
}

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  w w  .  ja v a 2  s  . c  om*/

        @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.bookkeeper.mledger.offload.jcloud.impl.BlobStoreManagedLedgerOffloader.java

@Override
public CompletableFuture<ReadHandle> readOffloaded(long ledgerId, UUID uid,
        Map<String, String> offloadDriverMetadata) {
    String readBucket = getReadBucket(offloadDriverMetadata);
    BlobStore readBlobstore = getReadBlobStore(offloadDriverMetadata);

    CompletableFuture<ReadHandle> promise = new CompletableFuture<>();
    String key = dataBlockOffloadKey(ledgerId, uid);
    String indexKey = indexBlockOffloadKey(ledgerId, uid);
    scheduler.chooseThread(ledgerId).submit(() -> {
        try {/*w ww  .  j a v  a  2s .c  om*/
            promise.complete(BlobStoreBackedReadHandleImpl.open(scheduler.chooseThread(ledgerId), readBlobstore,
                    readBucket, key, indexKey, VERSION_CHECK, ledgerId, readBufferSize));
        } catch (Throwable t) {
            log.error("Failed readOffloaded: ", t);
            promise.completeExceptionally(t);
        }
    });
    return promise;
}

From source file:org.onosproject.incubator.store.meter.impl.DistributedMeterStore.java

@Override
public CompletableFuture<MeterStoreResult> updateMeter(Meter meter) {
    CompletableFuture<MeterStoreResult> future = new CompletableFuture<>();
    MeterKey key = MeterKey.key(meter.deviceId(), meter.id());
    futures.put(key, future);/*from   w ww.j  a  v  a 2s. c  o  m*/

    MeterData data = new MeterData(meter, null, local);
    try {
        if (meters.computeIfPresent(key, (k, v) -> data) == null) {
            future.complete(MeterStoreResult.fail(MeterFailReason.INVALID_METER));
        }
    } catch (StorageException e) {
        futures.remove(key);
        future.completeExceptionally(e);
    }
    return future;
}

From source file:org.pentaho.di.ui.repo.controller.RepositoryConnectController.java

public boolean deleteDatabaseConnection(String database) {
    CompletableFuture<Boolean> future = new CompletableFuture<>();
    spoonSupplier.get().getShell().getDisplay().asyncExec(() -> {
        removeDatabase(database);/* ww w . ja v  a  2  s  .  co  m*/
        future.complete(true);
    });
    try {
        return future.get();
    } catch (Exception e) {
        return false;
    }
}

From source file:org.onosproject.store.primitives.impl.CopycatTransportConnection.java

private <T> void handleResponse(byte[] response, Throwable error, CompletableFuture<T> future,
        ThreadContext context) {/*from   w  w  w.j av a  2s .c o m*/
    if (error != null) {
        context.execute(() -> future.completeExceptionally(error));
        return;
    }
    checkNotNull(response);
    InputStream input = new ByteArrayInputStream(response);
    try {
        byte status = (byte) input.read();
        if (status == FAILURE) {
            Throwable t = context.serializer().readObject(input);
            context.execute(() -> future.completeExceptionally(t));
        } else {
            context.execute(() -> future.complete(context.serializer().readObject(input)));
        }
    } catch (IOException e) {
        context.execute(() -> future.completeExceptionally(e));
    }
}

From source file:io.pravega.controller.store.stream.AbstractStreamMetadataStore.java

private <T> CompletableFuture<T> withCompletion(CompletableFuture<T> future, final Executor executor) {

    // Following makes sure that the result future given out to caller is actually completed on
    // caller's executor. So any chaining, if done without specifying an executor, will either happen on
    // caller's executor or fork join pool but never on someone else's executor.

    CompletableFuture<T> result = new CompletableFuture<>();

    future.whenCompleteAsync((r, e) -> {
        if (e != null) {
            result.completeExceptionally(e);
        } else {//from   w  w  w.j  a v a 2s. c  om
            result.complete(r);
        }
    }, executor);

    return result;
}