Example usage for java.util.concurrent CompletableFuture CompletableFuture

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

Introduction

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

Prototype

public CompletableFuture() 

Source Link

Document

Creates a new incomplete CompletableFuture.

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  ww  w  .j av a  2  s.c  o  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);/*  w  w w . j av a  2 s .  com*/
    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  v a  2  s .c om
        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:Main.java

public static <T> CompletableFuture<T> anyOfFutures(List<? extends CompletableFuture<? extends T>> futures) {
    CompletableFuture<T> cf = new CompletableFuture<>();
    CompletableFuture/*from w  ww  .j a  v a 2  s  .com*/
            .allOf(futures.stream().map(f -> f.thenAccept(cf::complete)).toArray(CompletableFuture<?>[]::new))
            .exceptionally(ex -> {
                cf.completeExceptionally(ex);
                return null;
            });
    return cf;
}

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 ww .j  a v a  2  s .  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:com.opopov.cloud.image.utils.Utils.java

public static <T> CompletableFuture<T> fromListenableFuture(ListenableFuture<T> listenable) {
    CompletableFuture<T> completable = new CompletableFuture<T>() {

        @Override//from www .  j  a  va2s  .  com
        public boolean isCancelled() {
            return listenable.isCancelled();
        }

        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            //delegate cancel to the wrapped listenable
            boolean cancelledStatus = listenable.cancel(mayInterruptIfRunning);
            super.cancel(mayInterruptIfRunning);
            return cancelledStatus;
        }
    };

    //now delegate the callbacks
    ListenableFutureCallback<T> callback = new ListenableFutureCallback<T>() {
        @Override
        public void onFailure(Throwable ex) {
            //delegate exception
            completable.completeExceptionally(ex);
        }

        @Override
        public void onSuccess(T result) {
            //delegate success
            completable.complete(result);
        }
    };

    listenable.addCallback(callback);

    return completable;

}

From source file:enmasse.queue.scheduler.Artemis.java

public static Future<Broker> create(Vertx vertx, ProtonConnection connection) {
    CompletableFuture<Broker> promise = new CompletableFuture<>();
    connection.sessionOpenHandler(ProtonSession::open);
    BlockingQueue<Message> replies = new LinkedBlockingDeque<>();
    ProtonSender sender = connection.createSender("activemq.management");
    sender.openHandler(result -> {/*ww w.  ja  v  a 2s. c om*/
        ProtonReceiver receiver = connection.createReceiver("activemq.management");
        Source source = new Source();
        source.setDynamic(true);
        receiver.setSource(source);
        receiver.openHandler(h -> {
            promise.complete(new Artemis(vertx, sender, h.result().getRemoteSource().getAddress(), replies));
        });
        receiver.handler(((protonDelivery, message) -> {
            try {
                replies.put(message);
                ProtonHelper.accepted(protonDelivery, true);
            } catch (Exception e) {
                ProtonHelper.rejected(protonDelivery, true);
            }
        }));
        receiver.open();
    });
    sender.open();
    return promise;
}

From source file:org.jnode.net.NServerSocket.java

public CompletableFuture<NServerSocket> listen(int port) {

    if (isBound) {
        CompletableFuture cf = new CompletableFuture<>();
        cf.completeExceptionally(new IllegalStateException("Server already bound"));
        return cf;
    }/*from   www.j  a va 2 s  .c  o  m*/
    return createServerChannel(port).thenCompose((socketChannel) -> {
        this.ssc = socketChannel;
        return looper.register(socketChannel, SelectionKey.OP_ACCEPT, new ServerChannelEvent());
    }).whenComplete((ok, ex) -> {
        if (ex != null && ssc != null && ssc.isOpen())
            IOUtils.closeQuietly(ssc);
    }).thenCompose((SelectionKey selKey) -> {
        sk = selKey;
        isBound = true;
        return CompletableFuture.completedFuture(this);
    });
}

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

public static CompletableFuture<Optional<TableState>> getTableState(RawAsyncTable metaTable,
        TableName tableName) {// ww w.j  av a  2  s.c om
    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;
}

From source file:pt.isel.mpd.util.HttpGwAsyncNio.java

public CompletableFuture<Response> getDataAsync(String path) {

    CompletableFuture<Response> promise = new CompletableFuture<>();
    client.prepareGet(path).execute(new AsyncCompletionHandler<Object>() {
        @Override/*from   ww  w.  jav  a2 s .  c  om*/
        public Object onCompleted(Response response) throws Exception {
            promise.complete(response);
            return response;
        }
    });
    return promise;
}