Example usage for java.util.concurrent CompletableFuture whenCompleteAsync

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

Introduction

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

Prototype

public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T, ? super Throwable> action,
            Executor executor) 

Source Link

Usage

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  ww.  java  2  s  .c  o  m*/
            result.complete(r);
        }
    }, executor);

    return result;
}

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

CompletableFuture<ReadHandle> getLedgerHandle(long ledgerId) {
    CompletableFuture<ReadHandle> ledgerHandle = ledgerCache.get(ledgerId);
    if (ledgerHandle != null) {
        return ledgerHandle;
    }// w  w  w.j a v  a  2  s.c  o m

    // If not present try again and create if necessary
    return ledgerCache.computeIfAbsent(ledgerId, lid -> {
        // Open the ledger for reading if it was not already opened
        if (log.isDebugEnabled()) {
            log.debug("[{}] Asynchronously opening ledger {} for read", name, ledgerId);
        }
        mbean.startDataLedgerOpenOp();

        CompletableFuture<ReadHandle> promise = new CompletableFuture<>();

        LedgerInfo info = ledgers.get(ledgerId);
        CompletableFuture<ReadHandle> openFuture = new CompletableFuture<>();
        if (info != null && info.hasOffloadContext() && info.getOffloadContext().getComplete()) {
            UUID uid = new UUID(info.getOffloadContext().getUidMsb(), info.getOffloadContext().getUidLsb());
            // TODO: improve this to load ledger offloader by driver name recorded in metadata
            openFuture = config.getLedgerOffloader().readOffloaded(ledgerId, uid,
                    OffloadUtils.getOffloadDriverMetadata(info));
        } else {
            openFuture = bookKeeper.newOpenLedgerOp().withRecovery(!isReadOnly()).withLedgerId(ledgerId)
                    .withDigestType(config.getDigestType()).withPassword(config.getPassword()).execute();
        }
        openFuture.whenCompleteAsync((res, ex) -> {
            mbean.endDataLedgerOpenOp();
            if (ex != null) {
                ledgerCache.remove(ledgerId, promise);
                promise.completeExceptionally(createManagedLedgerException(ex));
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("[{}] Successfully opened ledger {} for reading", name, ledgerId);
                }
                promise.complete(res);
            }
        }, executor.chooseThread(name));
        return promise;
    });
}

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

/**
 * NOTE: unlockInternal should only after try lock.
 *//*from  www  .j  a v a2 s  . com*/
private void unlockInternal(final CompletableFuture<Void> promise) {

    // already closed or expired, nothing to cleanup
    this.epochUpdater.incrementAndGet(this);
    if (null != watcher) {
        this.zkClient.unregister(watcher);
    }

    if (lockState.inState(State.CLOSED)) {
        promise.complete(null);
        return;
    }

    LOG.info("Lock {} for {} is closed from state {}.",
            new Object[] { lockId, lockPath, lockState.getState() });

    final boolean skipCleanup = lockState.inState(State.INIT) || lockState.inState(State.EXPIRED);

    lockState.transition(State.CLOSING);

    if (skipCleanup) {
        // Nothing to cleanup if INIT (never tried) or EXPIRED (ephemeral node
        // auto-removed)
        lockState.transition(State.CLOSED);
        promise.complete(null);
        return;
    }

    // In any other state, we should clean up the member node
    CompletableFuture<Void> deletePromise = new CompletableFuture<Void>();
    deleteLockNode(deletePromise);

    // Set the state to closed after we've cleaned up
    deletePromise.whenCompleteAsync(new FutureEventListener<Void>() {
        @Override
        public void onSuccess(Void complete) {
            lockState.transition(State.CLOSED);
            promise.complete(null);
        }

        @Override
        public void onFailure(Throwable cause) {
            // Delete failure is quite serious (causes lock leak) and should be
            // handled better
            LOG.error("lock node delete failed {} {}", lockId, lockPath);
            promise.complete(null);
        }
    }, lockStateExecutor.chooseThread(lockPath));
}

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

private void phaseOneLoop(RawReader reader, Optional<MessageId> firstMessageId, Optional<MessageId> toMessageId,
        MessageId lastMessageId, Map<String, MessageId> latestForKey,
        CompletableFuture<PhaseOneResult> loopPromise) {
    if (loopPromise.isDone()) {
        return;/* w w  w .jav a  2  s .  c  o m*/
    }
    CompletableFuture<RawMessage> future = reader.readNextAsync();
    scheduleTimeout(future);
    future.whenCompleteAsync((m, exception) -> {
        try {
            if (exception != null) {
                loopPromise.completeExceptionally(exception);
                return;
            }
            MessageId id = m.getMessageId();
            boolean deletedMessage = false;
            if (RawBatchConverter.isReadableBatch(m)) {
                try {
                    RawBatchConverter.extractIdsAndKeys(m)
                            .forEach(e -> latestForKey.put(e.getRight(), e.getLeft()));
                } catch (IOException ioe) {
                    log.info("Error decoding batch for message {}. Whole batch will be included in output", id,
                            ioe);
                }
            } else {
                Pair<String, Integer> keyAndSize = extractKeyAndSize(m);
                if (keyAndSize != null) {
                    if (keyAndSize.getRight() > 0) {
                        latestForKey.put(keyAndSize.getLeft(), id);
                    } else {
                        deletedMessage = true;
                        latestForKey.remove(keyAndSize.getLeft());
                    }
                }
            }

            MessageId first = firstMessageId.orElse(deletedMessage ? null : id);
            MessageId to = deletedMessage ? toMessageId.orElse(null) : id;
            if (id.compareTo(lastMessageId) == 0) {
                loopPromise.complete(new PhaseOneResult(first, to, lastMessageId, latestForKey));
            } else {
                phaseOneLoop(reader, Optional.ofNullable(first), Optional.ofNullable(to), lastMessageId,
                        latestForKey, loopPromise);
            }
        } finally {
            m.close();
        }
    }, scheduler);
}