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:com.yahoo.pulsar.broker.namespace.NamespaceService.java

/**
 * Main internal method to lookup and setup ownership of service unit to a broker
 *
 * @param bundle//w  w w .j a v  a 2 s.c om
 * @param authoritative
 * @param readOnly
 * @return
 * @throws PulsarServerException
 */
private CompletableFuture<LookupResult> findBrokerServiceUrl(NamespaceBundle bundle, boolean authoritative,
        boolean readOnly) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("findBrokerServiceUrl: {} - read-only: {}", bundle, readOnly);
    }

    CompletableFuture<LookupResult> future = new CompletableFuture<>();

    // First check if we or someone else already owns the bundle
    ownershipCache.getOwnerAsync(bundle).thenAccept(nsData -> {
        if (!nsData.isPresent()) {
            // No one owns this bundle

            if (readOnly) {
                // Do not attempt to acquire ownership
                future.completeExceptionally(new IllegalStateException(
                        String.format("Can't find owner of ServiceUnit: %s", bundle)));
            } else {
                // Now, no one owns the namespace yet. Hence, we will try to dynamically assign it
                pulsar.getExecutor().execute(() -> {
                    searchForCandidateBroker(bundle, future, authoritative);
                });
            }
        } else if (nsData.get().isDisabled()) {
            future.completeExceptionally(
                    new IllegalStateException(String.format("Namespace bundle %s is being unloaded", bundle)));
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Namespace bundle {} already owned by {} ", bundle, nsData);
            }
            future.complete(new LookupResult(nsData.get()));
        }
    }).exceptionally(exception -> {
        LOG.warn("Failed to check owner for bundle {}: {}", bundle, exception.getMessage(), exception);
        future.completeExceptionally(exception);
        return null;
    });

    return future;
}

From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor.java

/**
 * Evaluate a script and allow for the submission of alteration to the entire evaluation execution lifecycle.
 *
 * @param script the script to evaluate//from  w w  w.  j  av  a  2s.  com
 * @param language the language to evaluate it in
 * @param boundVars the bindings to evaluate in the context of the script
 * @param lifeCycle a set of functions that can be applied at various stages of the evaluation process
 */
public CompletableFuture<Object> eval(final String script, final String language, final Bindings boundVars,
        final LifeCycle lifeCycle) {
    final String lang = Optional.ofNullable(language).orElse("gremlin-groovy");

    logger.debug("Preparing to evaluate script - {} - in thread [{}]", script,
            Thread.currentThread().getName());

    final Bindings bindings = new SimpleBindings();
    bindings.putAll(globalBindings);
    bindings.putAll(boundVars);

    final CompletableFuture<Object> evaluationFuture = new CompletableFuture<>();
    final FutureTask<Void> f = new FutureTask<>(() -> {
        try {
            lifeCycle.getBeforeEval().orElse(beforeEval).accept(bindings);

            logger.debug("Evaluating script - {} - in thread [{}]", script, Thread.currentThread().getName());

            final Object o = scriptEngines.eval(script, bindings, lang);

            // apply a transformation before sending back the result - useful when trying to force serialization
            // in the same thread that the eval took place given ThreadLocal nature of graphs as well as some
            // transactional constraints
            final Object result = lifeCycle.getTransformResult().isPresent()
                    ? lifeCycle.getTransformResult().get().apply(o)
                    : o;

            // a mechanism for taking the final result and doing something with it in the same thread, but
            // AFTER the eval and transform are done and that future completed.  this provides a final means
            // for working with the result in the same thread as it was eval'd
            if (lifeCycle.getWithResult().isPresent())
                lifeCycle.getWithResult().get().accept(result);

            lifeCycle.getAfterSuccess().orElse(afterSuccess).accept(bindings);

            // the evaluationFuture must be completed after all processing as an exception in lifecycle events
            // that must raise as an exception to the caller who has the returned evaluationFuture. in other words,
            // if it occurs before this point, then the handle() method won't be called again if there is an
            // exception that ends up below trying to completeExceptionally()
            evaluationFuture.complete(result);
        } catch (Throwable ex) {
            final Throwable root = null == ex.getCause() ? ex : ExceptionUtils.getRootCause(ex);

            // thread interruptions will typically come as the result of a timeout, so in those cases,
            // check for that situation and convert to TimeoutException
            if (root instanceof InterruptedException)
                evaluationFuture.completeExceptionally(new TimeoutException(String.format(
                        "Script evaluation exceeded the configured 'scriptEvaluationTimeout' threshold of %s ms for request [%s]: %s",
                        scriptEvaluationTimeout, script, root.getMessage())));
            else {
                lifeCycle.getAfterFailure().orElse(afterFailure).accept(bindings, root);
                evaluationFuture.completeExceptionally(root);
            }
        }

        return null;
    });

    executorService.execute(f);

    if (scriptEvaluationTimeout > 0) {
        // Schedule a timeout in the thread pool for future execution
        final ScheduledFuture<?> sf = scheduledExecutorService.schedule(() -> {
            logger.warn("Timing out script - {} - in thread [{}]", script, Thread.currentThread().getName());
            if (!f.isDone()) {
                lifeCycle.getAfterTimeout().orElse(afterTimeout).accept(bindings);
                f.cancel(true);
            }
        }, scriptEvaluationTimeout, TimeUnit.MILLISECONDS);

        // Cancel the scheduled timeout if the eval future is complete or the script evaluation failed
        // with exception
        evaluationFuture.handleAsync((v, t) -> {
            logger.debug(
                    "Killing scheduled timeout on script evaluation as the eval completed (possibly with exception).");
            return sf.cancel(true);
        });
    }

    return evaluationFuture;
}

From source file:org.eclipse.smarthome.binding.mqtt.generic.internal.generic.ChannelState.java

/**
 * Publishes a value on MQTT. A command topic needs to be set in the configuration.
 *
 * @param command The command to send/*from   w  ww  . j a  v  a 2 s. co  m*/
 * @return A future that completes with true if the publishing worked and false and/or exceptionally otherwise.
 */
public CompletableFuture<@Nullable Void> publishValue(Command command) {
    cachedValue.update(command);

    String mqttCommandValue = cachedValue.getMQTTpublishValue();

    final MqttBrokerConnection connection = this.connection;

    if (!readOnly && connection != null) {
        // Formatter: Applied before the channel state value is published to the MQTT broker.
        if (config.formatBeforePublish.length() > 0) {
            try (Formatter formatter = new Formatter()) {
                Formatter format = formatter.format(config.formatBeforePublish, mqttCommandValue);
                mqttCommandValue = format.toString();
            } catch (IllegalFormatException e) {
                logger.debug("Format pattern incorrect for {}", channelUID, e);
            }
        }
        // Send retained messages if this is a stateful channel
        return connection.publish(config.commandTopic, mqttCommandValue.getBytes(), 1, config.retained)
                .thenRun(() -> {
                });
    } else {
        CompletableFuture<@Nullable Void> f = new CompletableFuture<>();
        f.completeExceptionally(new IllegalStateException("No connection or readOnly channel!"));
        return f;
    }
}

From source file:com.yahoo.pulsar.client.impl.PulsarClientImpl.java

@Override
public CompletableFuture<Void> closeAsync() {
    log.info("Client closing. URL: {}", lookup.getServiceUrl());
    if (!state.compareAndSet(State.Open, State.Closing)) {
        return FutureUtil
                .failedFuture(new PulsarClientException.AlreadyClosedException("Client already closed"));
    }// w ww  .  ja v  a  2s  .c o  m

    final CompletableFuture<Void> closeFuture = new CompletableFuture<>();
    List<CompletableFuture<Void>> futures = Lists.newArrayList();

    synchronized (producers) {
        // Copy to a new list, because the closing will trigger a removal from the map
        // and invalidate the iterator
        List<ProducerBase> producersToClose = Lists.newArrayList(producers.keySet());
        producersToClose.forEach(p -> futures.add(p.closeAsync()));
    }

    synchronized (consumers) {
        List<ConsumerBase> consumersToClose = Lists.newArrayList(consumers.keySet());
        consumersToClose.forEach(c -> futures.add(c.closeAsync()));
    }

    FutureUtil.waitForAll(futures).thenRun(() -> {
        // All producers & consumers are now closed, we can stop the client safely
        try {
            shutdown();
            closeFuture.complete(null);
            state.set(State.Closed);
        } catch (PulsarClientException e) {
            closeFuture.completeExceptionally(e);
        }
    }).exceptionally(exception -> {
        closeFuture.completeExceptionally(exception);
        return null;
    });

    return closeFuture;
}

From source file:org.openhab.binding.mqtt.generic.ChannelState.java

/**
 * Publishes a value on MQTT. A command topic needs to be set in the configuration.
 *
 * @param command The command to send/*from   ww w .  ja  v a2s.  co  m*/
 * @return A future that completes with true if the publishing worked and false if it is a readonly topic
 *         and exceptionally otherwise.
 */
public CompletableFuture<Boolean> publishValue(Command command) {
    cachedValue.update(command);

    String mqttCommandValue = cachedValue.getMQTTpublishValue();

    final MqttBrokerConnection connection = this.connection;

    if (connection == null) {
        CompletableFuture<Boolean> f = new CompletableFuture<>();
        f.completeExceptionally(new IllegalStateException(
                "The connection object has not been set. start() should have been called!"));
        return f;
    }

    if (readOnly) {
        logger.debug(
                "You have tried to publish {} to the mqtt topic '{}' that was marked read-only. You can't 'set' anything on a sensor state topic for example.",
                mqttCommandValue, config.commandTopic);
        return CompletableFuture.completedFuture(false);
    }

    // Formatter: Applied before the channel state value is published to the MQTT broker.
    if (config.formatBeforePublish.length() > 0) {
        try (Formatter formatter = new Formatter()) {
            Formatter format = formatter.format(config.formatBeforePublish, mqttCommandValue);
            mqttCommandValue = format.toString();
        } catch (IllegalFormatException e) {
            logger.debug("Format pattern incorrect for {}", channelUID, e);
        }
    }
    // Outgoing transformations
    for (ChannelStateTransformation t : transformationsOut) {
        mqttCommandValue = t.processValue(mqttCommandValue);
    }
    // Send retained messages if this is a stateful channel
    return connection.publish(config.commandTopic, mqttCommandValue.getBytes(), 1, config.retained);
}

From source file:org.apache.pulsar.compaction.TwoPhaseCompactor.java

private CompletableFuture<LedgerHandle> createLedger(BookKeeper bk, Map<String, byte[]> metadata) {
    CompletableFuture<LedgerHandle> bkf = new CompletableFuture<>();
    bk.asyncCreateLedger(conf.getManagedLedgerDefaultEnsembleSize(), conf.getManagedLedgerDefaultWriteQuorum(),
            conf.getManagedLedgerDefaultAckQuorum(), Compactor.COMPACTED_TOPIC_LEDGER_DIGEST_TYPE,
            Compactor.COMPACTED_TOPIC_LEDGER_PASSWORD, (rc, ledger, ctx) -> {
                if (rc != BKException.Code.OK) {
                    bkf.completeExceptionally(BKException.create(rc));
                } else {
                    bkf.complete(ledger);
                }//from  w ww. j a va2  s . c  om
            }, null, metadata);
    return bkf;
}

From source file:co.runrightfast.vertx.orientdb.verticle.OrientDBVerticleTest.java

@Test
public void testEventLogRepository_getEventCount() throws Exception {
    final Vertx vertx = vertxService.getVertx();
    final RunRightFastVerticleId verticleId = EventLogRepository.VERTICLE_ID;

    final long timeout = 60000L;

    final ProtobufMessageProducer<GetEventCount.Request> getEventCountMessageProducer = new ProtobufMessageProducer<>(
            vertx.eventBus(), EventBusAddress.eventBusAddress(verticleId, GetEventCount.class),
            new ProtobufMessageCodec<>(GetEventCount.Request.getDefaultInstance()), metricRegistry);

    // because the verticles are deployed asynchronously, the EventLogRepository verticle may not yet be deployed yet
    // the message consumer for the Verticle only gets registered, while the verticle is starting. Thus, the message consumer may not yet be registered.
    while (true) {
        final CompletableFuture<GetEventCount.Response> getEventCountFuture = new CompletableFuture<>();
        getEventCountMessageProducer.send(GetEventCount.Request.getDefaultInstance(),
                responseHandler(getEventCountFuture, GetEventCount.Response.class));
        try {//from w ww.j  a  v  a2  s .c  o m
            getEventCountFuture.get(timeout, TimeUnit.MILLISECONDS);
            break;
        } catch (final ExecutionException e) {
            if (e.getCause() instanceof ReplyException) {
                final ReplyException replyException = (ReplyException) e.getCause();
                if (replyException.failureType() == NO_HANDLERS) {
                    log.log(WARNING, "Waiting for EventLogRepository ... ", e);
                    Thread.sleep(5000L);
                    continue;
                }
            }
            throw e;
        }
    }
}

From source file:co.runrightfast.vertx.demo.testHarness.jmx.DemoMXBeanImpl.java

@Override
public String lookupIPAddress(final String dnsServer, final String host) {
    final DnsClient client = vertx.createDnsClient(53, dnsServer);
    final CompletableFuture<String> future = new CompletableFuture<>();
    client.lookup("vertx.io", result -> {
        if (result.succeeded()) {
            future.complete(result.result());
        } else {//from  w  ww.  ja v  a 2  s.  c o  m
            future.completeExceptionally(result.cause());
        }
    });

    try {
        return future.get();
    } catch (final InterruptedException | ExecutionException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:io.pravega.controller.server.SegmentHelper.java

public CompletableFuture<TxnStatus> abortTransaction(final String scope, final String stream,
        final int segmentNumber, final UUID txId, final HostControllerStore hostControllerStore,
        final ConnectionFactory clientCF) {
    final Controller.NodeUri uri = getSegmentUri(scope, stream, segmentNumber, hostControllerStore);
    final CompletableFuture<TxnStatus> result = new CompletableFuture<>();
    final WireCommandType type = WireCommandType.ABORT_TRANSACTION;
    final FailingReplyProcessor replyProcessor = new FailingReplyProcessor() {

        @Override/*from w w w  .  j  av a2 s. com*/
        public void connectionDropped() {
            result.completeExceptionally(
                    new WireCommandFailedException(type, WireCommandFailedException.Reason.ConnectionDropped));
        }

        @Override
        public void wrongHost(WireCommands.WrongHost wrongHost) {
            result.completeExceptionally(
                    new WireCommandFailedException(type, WireCommandFailedException.Reason.UnknownHost));
        }

        @Override
        public void transactionCommitted(WireCommands.TransactionCommitted transactionCommitted) {
            result.completeExceptionally(
                    new WireCommandFailedException(type, WireCommandFailedException.Reason.PreconditionFailed));
        }

        @Override
        public void transactionAborted(WireCommands.TransactionAborted transactionDropped) {
            result.complete(TxnStatus.newBuilder().setStatus(TxnStatus.Status.SUCCESS).build());
        }

        @Override
        public void processingFailure(Exception error) {
            result.completeExceptionally(error);
        }
    };

    WireCommands.AbortTransaction request = new WireCommands.AbortTransaction(idGenerator.get(),
            Segment.getScopedName(scope, stream, segmentNumber), txId);
    sendRequestAsync(request, replyProcessor, result, clientCF, ModelHelper.encode(uri));
    return result;
}

From source file:org.apache.distributedlog.lock.TestZKSessionLock.java

@Test(timeout = 60000)
public void testExecuteLockAction() throws Exception {
    String lockPath = "/test-execute-lock-action";
    String clientId = "test-execute-lock-action-" + System.currentTimeMillis();

    ZKSessionLock lock = new ZKSessionLock(zkc, lockPath, clientId, lockStateExecutor);

    final AtomicInteger counter = new AtomicInteger(0);

    // lock action would be executed in same epoch
    final CountDownLatch latch1 = new CountDownLatch(1);
    lock.executeLockAction(lock.getEpoch(), new LockAction() {
        @Override/*from   w w w  .ja  v a  2 s.  c o  m*/
        public void execute() {
            counter.incrementAndGet();
            latch1.countDown();
        }

        @Override
        public String getActionName() {
            return "increment1";
        }
    });
    latch1.await();
    assertEquals("counter should be increased in same epoch", 1, counter.get());

    // lock action would not be executed in same epoch
    final CountDownLatch latch2 = new CountDownLatch(1);
    lock.executeLockAction(lock.getEpoch() + 1, new LockAction() {
        @Override
        public void execute() {
            counter.incrementAndGet();
        }

        @Override
        public String getActionName() {
            return "increment2";
        }
    });
    lock.executeLockAction(lock.getEpoch(), new LockAction() {
        @Override
        public void execute() {
            latch2.countDown();
        }

        @Override
        public String getActionName() {
            return "countdown";
        }
    });
    latch2.await();
    assertEquals("counter should not be increased in different epochs", 1, counter.get());

    // lock action would not be executed in same epoch and promise would be satisfied with exception
    CompletableFuture<Void> promise = new CompletableFuture<Void>();
    lock.executeLockAction(lock.getEpoch() + 1, new LockAction() {
        @Override
        public void execute() {
            counter.incrementAndGet();
        }

        @Override
        public String getActionName() {
            return "increment3";
        }
    }, promise);
    try {
        Utils.ioResult(promise);
        fail("Should satisfy promise with epoch changed exception.");
    } catch (EpochChangedException ece) {
        // expected
    }
    assertEquals("counter should not be increased in different epochs", 1, counter.get());

    lockStateExecutor.shutdown();
}