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:playground.Application.java

public static void main(String[] args) throws Exception {

    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("playground");
    DispatcherHandler dispatcherHandler = new DispatcherHandler();
    dispatcherHandler.setApplicationContext(context);

    HttpServer server = new ReactorHttpServer();
    server.setPort(8080);//from   w w  w .  ja va2  s .  co  m
    server.setHandler(dispatcherHandler);
    server.afterPropertiesSet();
    server.start();

    CompletableFuture<Void> stop = new CompletableFuture<>();
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        stop.complete(null);
    }));

    synchronized (stop) {
        stop.wait();
    }

}

From source file:playground.app.Application.java

public static void main(String[] args) throws Exception {

    HttpHandler httpHandler = createHttpHandler();

    HttpServer server = new TomcatHttpServer();
    server.setPort(8080);/*from   w w w .  j  av  a 2s  . c  om*/
    server.setHandler(httpHandler);
    server.afterPropertiesSet();
    server.start();

    CompletableFuture<Void> stop = new CompletableFuture<>();
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        stop.complete(null);
    }));
    synchronized (stop) {
        stop.wait();
    }
}

From source file:org.apache.pulsar.testclient.ManagedLedgerWriter.java

public static void main(String[] args) throws Exception {

    final Arguments arguments = new Arguments();
    JCommander jc = new JCommander(arguments);
    jc.setProgramName("pulsar-perf-producer");

    try {/*from   ww w.j a va 2 s . c  o  m*/
        jc.parse(args);
    } catch (ParameterException e) {
        System.out.println(e.getMessage());
        jc.usage();
        System.exit(-1);
    }

    if (arguments.help) {
        jc.usage();
        System.exit(-1);
    }

    arguments.testTime = TimeUnit.SECONDS.toMillis(arguments.testTime);

    // Dump config variables
    ObjectMapper m = new ObjectMapper();
    ObjectWriter w = m.writerWithDefaultPrettyPrinter();
    log.info("Starting Pulsar managed-ledger perf writer with config: {}", w.writeValueAsString(arguments));

    byte[] payloadData = new byte[arguments.msgSize];
    ByteBuf payloadBuffer = PooledByteBufAllocator.DEFAULT.directBuffer(arguments.msgSize);
    payloadBuffer.writerIndex(arguments.msgSize);

    // Now processing command line arguments
    String managedLedgerPrefix = "test-" + DigestUtils.sha1Hex(UUID.randomUUID().toString()).substring(0, 5);

    ClientConfiguration bkConf = new ClientConfiguration();
    bkConf.setUseV2WireProtocol(true);
    bkConf.setAddEntryTimeout(30);
    bkConf.setReadEntryTimeout(30);
    bkConf.setThrottleValue(0);
    bkConf.setNumChannelsPerBookie(arguments.maxConnections);
    bkConf.setZkServers(arguments.zookeeperServers);

    ManagedLedgerFactoryConfig mlFactoryConf = new ManagedLedgerFactoryConfig();
    mlFactoryConf.setMaxCacheSize(0);
    ManagedLedgerFactory factory = new ManagedLedgerFactoryImpl(bkConf, mlFactoryConf);

    ManagedLedgerConfig mlConf = new ManagedLedgerConfig();
    mlConf.setEnsembleSize(arguments.ensembleSize);
    mlConf.setWriteQuorumSize(arguments.writeQuorum);
    mlConf.setAckQuorumSize(arguments.ackQuorum);
    mlConf.setMinimumRolloverTime(10, TimeUnit.MINUTES);
    mlConf.setMetadataEnsembleSize(arguments.ensembleSize);
    mlConf.setMetadataWriteQuorumSize(arguments.writeQuorum);
    mlConf.setMetadataAckQuorumSize(arguments.ackQuorum);
    mlConf.setDigestType(arguments.digestType);
    mlConf.setMaxSizePerLedgerMb(2048);

    List<CompletableFuture<ManagedLedger>> futures = new ArrayList<>();

    for (int i = 0; i < arguments.numManagedLedgers; i++) {
        String name = String.format("%s-%03d", managedLedgerPrefix, i);
        CompletableFuture<ManagedLedger> future = new CompletableFuture<>();
        futures.add(future);
        factory.asyncOpen(name, mlConf, new OpenLedgerCallback() {

            @Override
            public void openLedgerComplete(ManagedLedger ledger, Object ctx) {
                future.complete(ledger);
            }

            @Override
            public void openLedgerFailed(ManagedLedgerException exception, Object ctx) {
                future.completeExceptionally(exception);
            }
        }, null);
    }

    List<ManagedLedger> managedLedgers = futures.stream().map(CompletableFuture::join)
            .collect(Collectors.toList());

    log.info("Created {} managed ledgers", managedLedgers.size());

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            printAggregatedStats();
        }
    });

    Collections.shuffle(managedLedgers);
    AtomicBoolean isDone = new AtomicBoolean();

    List<List<ManagedLedger>> managedLedgersPerThread = Lists.partition(managedLedgers,
            Math.max(1, managedLedgers.size() / arguments.numThreads));

    for (int i = 0; i < arguments.numThreads; i++) {
        List<ManagedLedger> managedLedgersForThisThread = managedLedgersPerThread.get(i);
        int nunManagedLedgersForThisThread = managedLedgersForThisThread.size();
        long numMessagesForThisThread = arguments.numMessages / arguments.numThreads;
        int maxOutstandingForThisThread = arguments.maxOutstanding;

        executor.submit(() -> {
            try {
                final double msgRate = arguments.msgRate / (double) arguments.numThreads;
                final RateLimiter rateLimiter = RateLimiter.create(msgRate);

                // Acquire 1 sec worth of messages to have a slower ramp-up
                rateLimiter.acquire((int) msgRate);
                final long startTime = System.currentTimeMillis();

                final Semaphore semaphore = new Semaphore(maxOutstandingForThisThread);

                final AddEntryCallback addEntryCallback = new AddEntryCallback() {
                    @Override
                    public void addComplete(Position position, Object ctx) {
                        long sendTime = (Long) (ctx);
                        messagesSent.increment();
                        bytesSent.add(payloadData.length);

                        long latencyMicros = NANOSECONDS.toMicros(System.nanoTime() - sendTime);
                        recorder.recordValue(latencyMicros);
                        cumulativeRecorder.recordValue(latencyMicros);

                        semaphore.release();
                    }

                    @Override
                    public void addFailed(ManagedLedgerException exception, Object ctx) {
                        log.warn("Write error on message", exception);
                        System.exit(-1);
                    }
                };

                // Send messages on all topics/producers
                long totalSent = 0;
                while (true) {
                    for (int j = 0; j < nunManagedLedgersForThisThread; j++) {
                        if (arguments.testTime > 0) {
                            if (System.currentTimeMillis() - startTime > arguments.testTime) {
                                log.info("------------------- DONE -----------------------");
                                printAggregatedStats();
                                isDone.set(true);
                                Thread.sleep(5000);
                                System.exit(0);
                            }
                        }

                        if (numMessagesForThisThread > 0) {
                            if (totalSent++ >= numMessagesForThisThread) {
                                log.info("------------------- DONE -----------------------");
                                printAggregatedStats();
                                isDone.set(true);
                                Thread.sleep(5000);
                                System.exit(0);
                            }
                        }

                        semaphore.acquire();
                        rateLimiter.acquire();

                        final long sendTime = System.nanoTime();
                        managedLedgersForThisThread.get(j).asyncAddEntry(payloadBuffer, addEntryCallback,
                                sendTime);
                    }
                }
            } catch (Throwable t) {
                log.error("Got error", t);
            }
        });
    }

    // Print report stats
    long oldTime = System.nanoTime();

    Histogram reportHistogram = null;

    while (true) {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            break;
        }

        if (isDone.get()) {
            break;
        }

        long now = System.nanoTime();
        double elapsed = (now - oldTime) / 1e9;

        double rate = messagesSent.sumThenReset() / elapsed;
        double throughput = bytesSent.sumThenReset() / elapsed / 1024 / 1024 * 8;

        reportHistogram = recorder.getIntervalHistogram(reportHistogram);

        log.info(
                "Throughput produced: {}  msg/s --- {} Mbit/s --- Latency: mean: {} ms - med: {} - 95pct: {} - 99pct: {} - 99.9pct: {} - 99.99pct: {} - Max: {}",
                throughputFormat.format(rate), throughputFormat.format(throughput),
                dec.format(reportHistogram.getMean() / 1000.0),
                dec.format(reportHistogram.getValueAtPercentile(50) / 1000.0),
                dec.format(reportHistogram.getValueAtPercentile(95) / 1000.0),
                dec.format(reportHistogram.getValueAtPercentile(99) / 1000.0),
                dec.format(reportHistogram.getValueAtPercentile(99.9) / 1000.0),
                dec.format(reportHistogram.getValueAtPercentile(99.99) / 1000.0),
                dec.format(reportHistogram.getMaxValue() / 1000.0));

        reportHistogram.reset();

        oldTime = now;
    }

    factory.shutdown();
}

From source file:net.javacrumbs.futureconverter.springjava.FutureConverter.java

private static <T> CompletableFuture<T> buildCompletableFutureFromListenableFuture(
        final ListenableFuture<T> listenableFuture) {
    CompletableFuture<T> completable = new CompletableListenableFuture<T>(listenableFuture);
    listenableFuture.addCallback(new ListenableFutureCallback<T>() {
        @Override/*from   w  w w  .  j  ava 2 s .c  om*/
        public void onSuccess(T result) {
            completable.complete(result);
        }

        @Override
        public void onFailure(Throwable t) {
            completable.completeExceptionally(t);
        }
    });
    return completable;
}

From source file:Main.java

public static <T> CompletableFuture<List<T>> allOfFutures(
        List<? extends CompletableFuture<? extends T>> futures) {
    List<T> result = new ArrayList<>(futures.size());
    CompletableFuture<List<T>> cf = new CompletableFuture<>();
    CompletableFuture/*from w  w w .j  a v a 2s .  c  o  m*/
            .allOf(futures.stream().map(s -> s.thenAccept(result::add)).toArray(CompletableFuture<?>[]::new))
            .exceptionally(ex -> {
                cf.completeExceptionally(ex);
                return null;
            }).thenAccept(v -> cf.complete(result));
    return cf;
}

From source file:org.apache.hadoop.hbase.client.ZKAsyncRegistry.java

private static void tryComplete(MutableInt remaining, HRegionLocation[] locs,
        CompletableFuture<RegionLocations> future) {
    remaining.decrement();/*from   w  w  w . j ava2s . com*/
    if (remaining.intValue() > 0) {
        return;
    }
    future.complete(new RegionLocations(locs));
}

From source file:org.apache.servicecomb.foundation.vertx.VertxUtils.java

public static CompletableFuture<Void> closeVertxByName(String name) {
    LOGGER.info("Closing vertx {}.", name);
    CompletableFuture<Void> future = new CompletableFuture<>();
    Vertx vertx = vertxMap.remove(name);
    if (vertx == null) {
        LOGGER.info("Vertx {} not exist.", name);
        future.complete(null);
        return future;
    }/*from  w ww  .j a va2 s  .co  m*/

    vertx.close(ar -> {
        if (ar.succeeded()) {
            LOGGER.info("Success to close vertx {}.", name);
            future.complete(null);
            return;
        }

        future.completeExceptionally(ar.cause());
    });
    return future;
}

From source file:org.apache.hadoop.hbase.client.ZKAsyncRegistry.java

private static <T> CompletableFuture<T> exec(BackgroundPathable<?> opBuilder, String path,
        CuratorEventProcessor<T> processor) {
    CompletableFuture<T> future = new CompletableFuture<>();
    try {//from   w  w w  .ja v a  2 s . c  om
        opBuilder.inBackground((client, event) -> {
            try {
                future.complete(processor.process(event));
            } catch (Exception e) {
                future.completeExceptionally(e);
            }
        }).withUnhandledErrorListener((msg, e) -> future.completeExceptionally(e)).forPath(path);
    } catch (Exception e) {
        future.completeExceptionally(e);
    }
    return future;
}

From source file:com.ikanow.aleph2.analytics.storm.utils.StormControllerUtil.java

/**
 * Restarts a storm job by first calling stop, then calling start
 * //from w w w. j a  v a  2 s. c om
 * @param bucket
 * @param underlying_artefacts
 * @param yarn_config_dir
 * @param user_lib_paths
 * @param topology
 * @return
 */
public static CompletableFuture<BasicMessageBean> restartJob(final IStormController storm_controller,
        final DataBucketBean bucket, final Optional<String> sub_job,
        final Collection<Object> underlying_artefacts, final Collection<String> user_lib_paths,
        final StormTopology topology, final Map<String, String> config, final String cached_jar_dir) {
    CompletableFuture<BasicMessageBean> stop_future = stopJob(storm_controller, bucket, sub_job);
    try {
        stop_future.get(5, TimeUnit.SECONDS);
        waitForJobToDie(storm_controller, bucket, sub_job, 30L);
    } catch (Exception e) {
        CompletableFuture<BasicMessageBean> error_future = new CompletableFuture<BasicMessageBean>();
        error_future.complete(ErrorUtils.buildErrorMessage(StormControllerUtil.class, "restartJob",
                ErrorUtils.getLongForm("Error stopping storm job: {0}", e)));
        return error_future;
    }
    return startJob(storm_controller, bucket, sub_job, underlying_artefacts, user_lib_paths, topology, config,
            cached_jar_dir);
}

From source file:org.apache.hadoop.hbase.AsyncMetaTableAccessor.java

public static CompletableFuture<Optional<TableState>> getTableState(RawAsyncTable metaTable,
        TableName tableName) {//from w w w  . j ava2s.  c o  m
    CompletableFuture<Optional<TableState>> future = new CompletableFuture<>();
    Get get = new Get(tableName.getName()).addColumn(getTableFamily(), getStateColumn());
    long time = EnvironmentEdgeManager.currentTime();
    try {
        get.setTimeRange(0, time);
        metaTable.get(get).whenComplete((result, error) -> {
            if (error != null) {
                future.completeExceptionally(error);
                return;
            }
            try {
                future.complete(getTableState(result));
            } catch (IOException e) {
                future.completeExceptionally(e);
            }
        });
    } catch (IOException ioe) {
        future.completeExceptionally(ioe);
    }
    return future;
}