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.service.ServerCnx.java

@Override
protected void handleSubscribe(final CommandSubscribe subscribe) {
    checkArgument(state == State.Connected);
    CompletableFuture<Boolean> authorizationFuture;
    if (service.isAuthorizationEnabled()) {
        authorizationFuture = service.getAuthorizationManager()
                .canConsumeAsync(DestinationName.get(subscribe.getTopic()), authRole);
    } else {/*from www  . ja v a 2 s .  co  m*/
        authorizationFuture = CompletableFuture.completedFuture(true);
    }
    final String topicName = subscribe.getTopic();
    final String subscriptionName = subscribe.getSubscription();
    final long requestId = subscribe.getRequestId();
    final long consumerId = subscribe.getConsumerId();
    final SubType subType = subscribe.getSubType();
    final String consumerName = subscribe.getConsumerName();
    final boolean isDurable = subscribe.getDurable();
    final MessageIdImpl startMessageId = subscribe.hasStartMessageId()
            ? new MessageIdImpl(subscribe.getStartMessageId().getLedgerId(),
                    subscribe.getStartMessageId().getEntryId(), subscribe.getStartMessageId().getPartition())
            : null;

    final int priorityLevel = subscribe.hasPriorityLevel() ? subscribe.getPriorityLevel() : 0;

    authorizationFuture.thenApply(isAuthorized -> {
        if (isAuthorized) {
            if (log.isDebugEnabled()) {
                log.debug("[{}] Client is authorized to subscribe with role {}", remoteAddress, authRole);
            }

            log.info("[{}] Subscribing on topic {} / {}", remoteAddress, topicName, subscriptionName);

            CompletableFuture<Consumer> consumerFuture = new CompletableFuture<>();
            CompletableFuture<Consumer> existingConsumerFuture = consumers.putIfAbsent(consumerId,
                    consumerFuture);

            if (existingConsumerFuture != null) {
                if (existingConsumerFuture.isDone() && !existingConsumerFuture.isCompletedExceptionally()) {
                    Consumer consumer = existingConsumerFuture.getNow(null);
                    log.info("[{}] Consumer with the same id is already created: {}", remoteAddress, consumer);
                    ctx.writeAndFlush(Commands.newSuccess(requestId));
                    return null;
                } else {
                    // There was an early request to create a consumer with same consumerId. This can happen when
                    // client timeout is lower the broker timeouts. We need to wait until the previous consumer
                    // creation request either complete or fails.
                    log.warn("[{}][{}][{}] Consumer is already present on the connection", remoteAddress,
                            topicName, subscriptionName);
                    ServerError error = !existingConsumerFuture.isDone() ? ServerError.ServiceNotReady
                            : getErrorCode(existingConsumerFuture);
                    ctx.writeAndFlush(Commands.newError(requestId, error,
                            "Consumer is already present on the connection"));
                    return null;
                }
            }

            service.getTopic(topicName).thenCompose(topic -> topic.subscribe(ServerCnx.this, subscriptionName,
                    consumerId, subType, priorityLevel, consumerName, isDurable, startMessageId))
                    .thenAccept(consumer -> {
                        if (consumerFuture.complete(consumer)) {
                            log.info("[{}] Created subscription on topic {} / {}", remoteAddress, topicName,
                                    subscriptionName);
                            ctx.writeAndFlush(Commands.newSuccess(requestId), ctx.voidPromise());
                        } else {
                            // The consumer future was completed before by a close command
                            try {
                                consumer.close();
                                log.info("[{}] Cleared consumer created after timeout on client side {}",
                                        remoteAddress, consumer);
                            } catch (BrokerServiceException e) {
                                log.warn(
                                        "[{}] Error closing consumer created after timeout on client side {}: {}",
                                        remoteAddress, consumer, e.getMessage());
                            }
                            consumers.remove(consumerId, consumerFuture);
                        }

                    }) //
                    .exceptionally(exception -> {
                        log.warn("[{}][{}][{}] Failed to create consumer: {}", remoteAddress, topicName,
                                subscriptionName, exception.getCause().getMessage(), exception);

                        // If client timed out, the future would have been completed by subsequent close. Send error
                        // back to client, only if not completed already.
                        if (consumerFuture.completeExceptionally(exception)) {
                            ctx.writeAndFlush(Commands.newError(requestId,
                                    BrokerServiceException.getClientErrorCode(exception.getCause()),
                                    exception.getCause().getMessage()));
                        }
                        consumers.remove(consumerId, consumerFuture);

                        return null;

                    });
        } else {
            String msg = "Client is not authorized to subscribe";
            log.warn("[{}] {} with role {}", remoteAddress, msg, authRole);
            ctx.writeAndFlush(Commands.newError(requestId, ServerError.AuthorizationError, msg));
        }
        return null;
    });
}

From source file:io.atomix.cluster.messaging.impl.NettyMessagingService.java

private CompletableFuture<Channel> getChannel(Address address, String messageType) {
    List<CompletableFuture<Channel>> channelPool = getChannelPool(address);
    int offset = getChannelOffset(messageType);

    CompletableFuture<Channel> channelFuture = channelPool.get(offset);
    if (channelFuture == null || channelFuture.isCompletedExceptionally()) {
        synchronized (channelPool) {
            channelFuture = channelPool.get(offset);
            if (channelFuture == null || channelFuture.isCompletedExceptionally()) {
                channelFuture = openChannel(address);
                channelPool.set(offset, channelFuture);
            }//from ww w. ja  va  2s.c  o m
        }
    }

    final CompletableFuture<Channel> future = new CompletableFuture<>();
    final CompletableFuture<Channel> finalFuture = channelFuture;
    finalFuture.whenComplete((channel, error) -> {
        if (error == null) {
            if (!channel.isActive()) {
                CompletableFuture<Channel> currentFuture;
                synchronized (channelPool) {
                    currentFuture = channelPool.get(offset);
                    if (currentFuture == finalFuture) {
                        channelPool.set(offset, null);
                    } else if (currentFuture == null) {
                        currentFuture = openChannel(address);
                        channelPool.set(offset, currentFuture);
                    }
                }

                final ClientConnection connection = clientConnections.remove(channel);
                if (connection != null) {
                    connection.close();
                }

                if (currentFuture == finalFuture) {
                    getChannel(address, messageType).whenComplete((recursiveResult, recursiveError) -> {
                        if (recursiveError == null) {
                            future.complete(recursiveResult);
                        } else {
                            future.completeExceptionally(recursiveError);
                        }
                    });
                } else {
                    currentFuture.whenComplete((recursiveResult, recursiveError) -> {
                        if (recursiveError == null) {
                            future.complete(recursiveResult);
                        } else {
                            future.completeExceptionally(recursiveError);
                        }
                    });
                }
            } else {
                future.complete(channel);
            }
        } else {
            future.completeExceptionally(error);
        }
    });
    return future;
}

From source file:io.sqp.client.impl.SqpConnectionImpl.java

CompletableFuture<Void> closeServerResources(Collection<CloseableServerResource> resources) {
    if (resources.isEmpty()) {
        return CompletableFuture.completedFuture(null);
    }//from  w  ww .  j  av  a2 s  .  c  o  m
    CompletableFuture<Void> future = new CompletableFuture<>();

    List<String> cursorIds = resources.stream().filter(r -> r instanceof CursorImpl)
            .map(CloseableServerResource::getId).collect(Collectors.toList());
    List<String> statementIds = resources.stream().filter(r -> r instanceof PreparedStatementImpl)
            .map(CloseableServerResource::getId).collect(Collectors.toList());
    // now set their status to closed
    resources.forEach(CloseableServerResource::setClosed);

    // remove them from the open resource list
    // TODO: wait for success?
    cursorIds.forEach(_openServerResources::remove);
    statementIds.forEach(_openServerResources::remove);

    send(new ReleaseMessage(cursorIds, statementIds), new ConfirmationResponseHandler(future,
            MessageType.ReleaseCompleteMessage, "waiting for a cursor/statement release confirmation"));
    return future;
}

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

@Override
CompletableFuture<Void> sealActiveTx(int epoch, UUID txId, boolean commit, ActiveTxnRecord txnRecord,
        int version) {
    Preconditions.checkNotNull(txId);/*from  w ww .  j a v a  2  s. c  o m*/

    CompletableFuture<Void> result = new CompletableFuture<>();
    synchronized (txnsLock) {
        if (!activeTxns.containsKey(txId.toString())) {
            result.completeExceptionally(StoreException.create(StoreException.Type.DATA_NOT_FOUND,
                    "Stream: " + getName() + " Transaction: " + txId.toString()));
        } else {
            activeTxns.compute(txId.toString(), (x, y) -> {
                if (version != y.getVersion()) {
                    result.completeExceptionally(StoreException.create(StoreException.Type.WRITE_CONFLICT,
                            "Stream: " + getName() + " Transaction: " + txId.toString()));
                    return y;
                } else {
                    ActiveTxnRecord previous = ActiveTxnRecord.parse(y.getData());
                    ActiveTxnRecord updated = new ActiveTxnRecord(previous.getTxCreationTimestamp(),
                            previous.getLeaseExpiryTime(), previous.getMaxExecutionExpiryTime(),
                            previous.getScaleGracePeriod(), commit ? TxnStatus.COMMITTING : TxnStatus.ABORTING);
                    result.complete(null);
                    return new Data<>(updated.toByteArray(), y.getVersion() + 1);
                }
            });
        }
    }
    return result;
}

From source file:org.apache.bookkeeper.client.LedgerHandle.java

/**
 * {@inheritDoc}//w w w  . j  av a2 s  . c  o m
 */
@Override
public CompletableFuture<Void> closeAsync() {
    CompletableFuture<Void> result = new CompletableFuture<>();
    SyncCloseCallback callback = new SyncCloseCallback(result);
    asyncClose(callback, null);
    return result;
}

From source file:org.apache.bookkeeper.mledger.impl.OffloadPrefixTest.java

public void offloadThreeOneFails(int failIndex) throws Exception {
    CompletableFuture<Set<Long>> promise = new CompletableFuture<>();
    MockLedgerOffloader offloader = new ErroringMockLedgerOffloader(promise);
    ManagedLedgerConfig config = new ManagedLedgerConfig();
    config.setMaxEntriesPerLedger(10);//from www.ja v  a 2s.c  om
    config.setMinimumRolloverTime(0, TimeUnit.SECONDS);
    config.setRetentionTime(10, TimeUnit.MINUTES);
    config.setLedgerOffloader(offloader);
    ManagedLedgerImpl ledger = (ManagedLedgerImpl) factory.open("my_test_ledger", config);

    int i = 0;
    for (; i < 35; i++) {
        String content = "entry-" + i;
        ledger.addEntry(content.getBytes());
    }
    Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 4);

    // mark ledgers to fail
    promise.complete(ImmutableSet.of(ledger.getLedgersInfoAsList().get(failIndex).getLedgerId()));

    try {
        ledger.offloadPrefix(ledger.getLastConfirmedEntry());
    } catch (ManagedLedgerException e) {
        Assert.assertEquals(e.getCause().getClass(), CompletionException.class);
    }

    Assert.assertEquals(ledger.getLedgersInfoAsList().size(), 4);
    Assert.assertEquals(ledger.getLedgersInfoAsList().stream().filter(e -> e.getOffloadContext().getComplete())
            .map(e -> e.getLedgerId()).collect(Collectors.toSet()), offloader.offloadedLedgers());
    Assert.assertEquals(
            ledger.getLedgersInfoAsList().stream().filter(e -> e.getOffloadContext().getComplete()).count(), 2);
    Assert.assertFalse(ledger.getLedgersInfoAsList().get(failIndex).getOffloadContext().getComplete());
}

From source file:org.apache.pulsar.broker.loadbalance.impl.LoadManagerShared.java

/**
 * It returns map of broker and count of namespace that are belong to the same anti-affinity group as given
 * {@param namespaceName}//from  w  ww .ja v  a2  s .  com
 *
 * @param pulsar
 * @param namespaceName
 * @param brokerToNamespaceToBundleRange
 * @return
 */
public static CompletableFuture<Map<String, Integer>> getAntiAffinityNamespaceOwnedBrokers(
        final PulsarService pulsar, String namespaceName,
        Map<String, Map<String, Set<String>>> brokerToNamespaceToBundleRange) {

    CompletableFuture<Map<String, Integer>> antiAffinityNsBrokersResult = new CompletableFuture<>();
    ZooKeeperDataCache<Policies> policiesCache = pulsar.getConfigurationCache().policiesCache();

    policiesCache.getAsync(path(POLICIES, namespaceName)).thenAccept(policies -> {
        if (!policies.isPresent() || StringUtils.isBlank(policies.get().antiAffinityGroup)) {
            antiAffinityNsBrokersResult.complete(null);
            return;
        }
        final String antiAffinityGroup = policies.get().antiAffinityGroup;
        final Map<String, Integer> brokerToAntiAffinityNamespaceCount = new ConcurrentHashMap<>();
        final List<CompletableFuture<Void>> futures = Lists.newArrayList();
        brokerToNamespaceToBundleRange.forEach((broker, nsToBundleRange) -> {
            nsToBundleRange.forEach((ns, bundleRange) -> {
                CompletableFuture<Void> future = new CompletableFuture<>();
                futures.add(future);
                policiesCache.getAsync(path(POLICIES, ns)).thenAccept(nsPolicies -> {
                    if (nsPolicies.isPresent()
                            && antiAffinityGroup.equalsIgnoreCase(nsPolicies.get().antiAffinityGroup)) {
                        brokerToAntiAffinityNamespaceCount.compute(broker,
                                (brokerName, count) -> count == null ? 1 : count + 1);
                    }
                    future.complete(null);
                }).exceptionally(ex -> {
                    future.complete(null);
                    return null;
                });
            });
        });
        FutureUtil.waitForAll(futures)
                .thenAccept(r -> antiAffinityNsBrokersResult.complete(brokerToAntiAffinityNamespaceCount));
    }).exceptionally(ex -> {
        // namespace-policies has not been created yet
        antiAffinityNsBrokersResult.complete(null);
        return null;
    });
    return antiAffinityNsBrokersResult;
}

From source file:org.eclipse.smarthome.io.transport.mqtt.MqttBrokerConnection.java

/**
 * Add a new message consumer to this connection. Multiple subscribers with the same
 * topic are allowed. This method will not protect you from adding a subscriber object
 * multiple times!/*from   w  w  w.j a  v a  2s.co m*/
 *
 * If there is a retained message for the topic, you are guaranteed to receive a callback
 * for each new subscriber, even for the same topic.
 *
 * @param topic The topic to subscribe to.
 * @param subscriber The callback listener for received messages for the given topic.
 * @return Completes with true if successful. Completes with false if not connected yet. Exceptionally otherwise.
 */
public CompletableFuture<Boolean> subscribe(String topic, MqttMessageSubscriber subscriber) {
    CompletableFuture<Boolean> future = new CompletableFuture<Boolean>();
    synchronized (subscribers) {
        TopicSubscribers subscriberList = subscribers.getOrDefault(topic, new TopicSubscribers(topic));
        subscribers.put(topic, subscriberList);
        subscriberList.add(subscriber);
    }
    final MqttAsyncClient client = this.client;
    if (client == null) {
        future.completeExceptionally(new Exception("No MQTT client"));
        return future;
    }
    if (client.isConnected()) {
        try {
            client.subscribe(topic, qos, future, actionCallback);
        } catch (org.eclipse.paho.client.mqttv3.MqttException e) {
            future.completeExceptionally(e);
        }
    } else {
        // The subscription will be performed on connecting.
        future.complete(false);
    }
    return future;
}

From source file:com.yahoo.pulsar.broker.service.BrokerService.java

private CompletableFuture<Topic> createPersistentTopic(final String topic) throws RuntimeException {
    checkTopicNsOwnership(topic);/*from w  ww.  j  a  va2  s  .  c  o  m*/

    final long topicCreateTimeMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
    DestinationName destinationName = DestinationName.get(topic);
    if (!pulsar.getNamespaceService().isServiceUnitActive(destinationName)) {
        // namespace is being unloaded
        String msg = String.format("Namespace is being unloaded, cannot add topic %s", topic);
        log.warn(msg);
        throw new RuntimeException(new ServiceUnitNotReadyException(msg));
    }

    final CompletableFuture<Topic> topicFuture = new CompletableFuture<>();

    getManagedLedgerConfig(destinationName).thenAccept(config -> {
        // Once we have the configuration, we can proceed with the async open operation

        managedLedgerFactory.asyncOpen(destinationName.getPersistenceNamingEncoding(), config,
                new OpenLedgerCallback() {
                    @Override
                    public void openLedgerComplete(ManagedLedger ledger, Object ctx) {
                        PersistentTopic persistentTopic = new PersistentTopic(topic, ledger,
                                BrokerService.this);

                        CompletableFuture<Void> replicationFuture = persistentTopic.checkReplication();
                        replicationFuture.thenRun(() -> {
                            log.info("Created topic {}", topic);
                            long topicLoadLatencyMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime())
                                    - topicCreateTimeMs;
                            pulsarStats.recordTopicLoadTimeValue(topic, topicLoadLatencyMs);
                            addTopicToStatsMaps(destinationName, persistentTopic);
                            topicFuture.complete(persistentTopic);
                        });
                        replicationFuture.exceptionally((ex) -> {
                            log.warn("Replication check failed. Removing topic from topics list {}, {}", topic,
                                    ex);
                            persistentTopic.stopReplProducers().whenComplete((v, exception) -> {
                                topics.remove(topic, topicFuture);
                                topicFuture.completeExceptionally(ex);
                            });

                            return null;
                        });
                    }

                    @Override
                    public void openLedgerFailed(ManagedLedgerException exception, Object ctx) {
                        log.warn("Failed to create topic {}", topic, exception);
                        topics.remove(topic, topicFuture);
                        topicFuture.completeExceptionally(new PersistenceException(exception));
                    }
                }, null);

    }).exceptionally((exception) -> {
        log.warn("[{}] Failed to get topic configuration: {}", topic, exception.getMessage(), exception);
        topics.remove(topic, topicFuture);
        topicFuture.completeExceptionally(exception);
        return null;
    });

    return topicFuture;
}

From source file:io.atomix.cluster.messaging.impl.NettyMessagingService.java

private <T> CompletableFuture<T> executeOnPooledConnection(Address address, String type,
        Function<ClientConnection, CompletableFuture<T>> callback, Executor executor) {
    CompletableFuture<T> future = new CompletableFuture<T>();
    executeOnPooledConnection(address, type, callback, executor, future);
    return future;
}