當前位置: 首頁>>代碼示例>>Java>>正文


Java CompletionStage.whenComplete方法代碼示例

本文整理匯總了Java中java.util.concurrent.CompletionStage.whenComplete方法的典型用法代碼示例。如果您正苦於以下問題:Java CompletionStage.whenComplete方法的具體用法?Java CompletionStage.whenComplete怎麽用?Java CompletionStage.whenComplete使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.util.concurrent.CompletionStage的用法示例。


在下文中一共展示了CompletionStage.whenComplete方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: subscribe

import java.util.concurrent.CompletionStage; //導入方法依賴的package包/類
protected void subscribe(CompletionStage<T> parent, boolean unwrapException) {
    if (unwrapException) {
        parent.whenComplete((r, t) -> {
            if (t == null) {
                complete(r);
            } else {
                completeExceptionally(Dispatcher.unwrapCompletionException(t));
            }
        });
    } else {
        parent.whenComplete((r, t) -> {
            if (t == null) {
                complete(r);
            } else {
                completeExceptionally(t);
            }
        });
    }
}
 
開發者ID:goodees,項目名稱:goodees,代碼行數:20,代碼來源:AsyncResult.java

示例2: fetchOrCreateAndResolveReference

import java.util.concurrent.CompletionStage; //導入方法依賴的package包/類
/**
 * Given an {@link PriceDraftBuilder} and a {@code channelKey} this method fetches the actual id of the
 * channel corresponding to this key, ideally from a cache. Then it sets this id on the supply channel reference
 * id of the inventory entry draft. If the id is not found in cache nor the CTP project and {@code ensureChannel}
 * option is set to true, a new channel will be created with this key and the role {@code "InventorySupply"}.
 * However, if the {@code ensureChannel} is set to false, the future is completed exceptionally with a
 * {@link ReferenceResolutionException}.
 *
 * @param draftBuilder      the price draft builder where to set resolved references.
 * @param channelKey the key of the channel to resolve it's actual id on the draft.
 * @return a {@link CompletionStage} that contains as a result the same {@code draft} instance with resolved
 *         supply channel reference or an exception.
 */
@Nonnull
private CompletionStage<PriceDraftBuilder> fetchOrCreateAndResolveReference(
    @Nonnull final PriceDraftBuilder draftBuilder,
    @Nonnull final String channelKey) {
    final CompletionStage<PriceDraftBuilder> priceDraftCompletionStage = channelService
        .fetchCachedChannelId(channelKey)
        .thenCompose(resolvedChannelIdOptional -> resolvedChannelIdOptional
            .map(resolvedChannelId -> setChannelReference(resolvedChannelId, draftBuilder))
            .orElseGet(() -> createChannelAndSetReference(channelKey, draftBuilder)));

    final CompletableFuture<PriceDraftBuilder> result = new CompletableFuture<>();
    priceDraftCompletionStage
        .whenComplete((resolvedDraft, exception) -> {
            if (exception != null) {
                result.completeExceptionally(
                    new ReferenceResolutionException(format(FAILED_TO_RESOLVE_CHANNEL, draftBuilder.getCountry(),
                        draftBuilder.getValue(), exception.getMessage()), exception));
            } else {
                result.complete(resolvedDraft);
            }
        });
    return result;
}
 
開發者ID:commercetools,項目名稱:commercetools-sync-java,代碼行數:37,代碼來源:PriceReferenceResolver.java

示例3: fetchOrCreateAndResolveReference

import java.util.concurrent.CompletionStage; //導入方法依賴的package包/類
/**
 * Given an {@link InventoryEntryDraftBuilder} and a {@code channelKey} this method fetches the actual id of the
 * channel corresponding to this key, ideally from a cache. Then it sets this id on the supply channel reference
 * id of the inventory entry draft builder. If the id is not found in cache nor the CTP project
 * and {@code ensureChannel} option is set to true, a new channel will be created with this key
 * and the role {@code "InventorySupply"}.
 * However, if the {@code ensureChannel} is set to false, the future is completed exceptionally with a
 * {@link ReferenceResolutionException}.
 *
 * @param draftBuilder the inventory draft builder to read it's values (key, sku, channel)
 *                     and then to write resolved references.
 * @param channelKey the key of the channel to resolve it's actual id on the draft.
 * @return a {@link CompletionStage} that contains as a result the same {@code draftBuilder} inventory draft builder
 *         instance with resolved supply channel reference or an exception.
 */
@Nonnull
private CompletionStage<InventoryEntryDraftBuilder> fetchOrCreateAndResolveReference(
    @Nonnull final InventoryEntryDraftBuilder draftBuilder,
    @Nonnull final String channelKey) {
    final CompletionStage<InventoryEntryDraftBuilder> inventoryEntryDraftCompletionStage = channelService
        .fetchCachedChannelId(channelKey)
        .thenCompose(resolvedChannelIdOptional -> resolvedChannelIdOptional
            .map(resolvedChannelId -> setChannelReference(resolvedChannelId, draftBuilder))
            .orElseGet(() -> createChannelAndSetReference(channelKey, draftBuilder)));

    final CompletableFuture<InventoryEntryDraftBuilder> result = new CompletableFuture<>();
    inventoryEntryDraftCompletionStage
        .whenComplete((resolvedDraftBuilder, exception) -> {
            if (exception != null) {
                result.completeExceptionally(
                    new ReferenceResolutionException(format(FAILED_TO_RESOLVE_SUPPLY_CHANNEL, draftBuilder.getSku(),
                        exception.getCause().getMessage()), exception));
            } else {
                result.complete(resolvedDraftBuilder);
            }
        });
    return result;

}
 
開發者ID:commercetools,項目名稱:commercetools-sync-java,代碼行數:40,代碼來源:InventoryReferenceResolver.java

示例4: main

import java.util.concurrent.CompletionStage; //導入方法依賴的package包/類
public static void main(String[] args) {
    final ActorSystem system = ActorSystem.create("KafkaProducerSystem");

    final Materializer materializer = ActorMaterializer.create(system);

    final ProducerSettings<byte[], String> producerSettings =
            ProducerSettings
                    .create(system, new ByteArraySerializer(), new StringSerializer())
                    .withBootstrapServers("localhost:9092");

    CompletionStage<Done> done =
            Source.range(1, 100)
                    .map(n -> n.toString())
                    .map(elem ->
                            new ProducerRecord<byte[], String>(
                                    "topic1-ts",
                                    0,
                                    Instant.now().getEpochSecond(),
                                    null,
                                    elem))
                    .runWith(Producer.plainSink(producerSettings), materializer);

    done.whenComplete((d, ex) -> System.out.println("sent"));
}
 
開發者ID:jeqo,項目名稱:talk-kafka-messaging-logs,代碼行數:25,代碼來源:KafkaProducer.java

示例5: processClose

import java.util.concurrent.CompletionStage; //導入方法依賴的package包/類
private void processClose(int statusCode, String reason) {
    receiver.close();
    try {
        channel.shutdownInput();
    } catch (IOException e) {
        Log.logError(e);
    }
    boolean alreadyCompleted = !closeReceived.complete(null);
    if (alreadyCompleted) {
        // This CF is supposed to be completed only once, the first time a
        // Close message is received. No further messages are pulled from
        // the socket.
        throw new InternalError();
    }
    int code;
    if (statusCode == NO_STATUS_CODE || statusCode == CLOSED_ABNORMALLY) {
        code = NORMAL_CLOSURE;
    } else {
        code = statusCode;
    }
    CompletionStage<?> readyToClose = signalClose(statusCode, reason);
    if (readyToClose == null) {
        readyToClose = CompletableFuture.completedFuture(null);
    }
    readyToClose.whenComplete((r, error) -> {
        enqueueClose(new Close(code, ""))
                .whenComplete((r1, error1) -> {
                    if (error1 != null) {
                        Log.logError(error1);
                    }
                });
    });
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:34,代碼來源:WebSocketImpl.java

示例6: testCompletedStage

import java.util.concurrent.CompletionStage; //導入方法依賴的package包/類
/**
 * completedStage returns a completed CompletionStage
 */
public void testCompletedStage() {
    AtomicInteger x = new AtomicInteger(0);
    AtomicReference<Throwable> r = new AtomicReference<>();
    CompletionStage<Integer> f = CompletableFuture.completedStage(1);
    f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
    assertEquals(x.get(), 1);
    assertNull(r.get());
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:12,代碼來源:CompletableFutureTest.java

示例7: testMinimalCompletionStage

import java.util.concurrent.CompletionStage; //導入方法依賴的package包/類
/**
 * minimalCompletionStage returns a CompletableFuture that is
 * completed normally, with the same value, when source is.
 */
public void testMinimalCompletionStage() {
    CompletableFuture<Integer> f = new CompletableFuture<>();
    CompletionStage<Integer> g = f.minimalCompletionStage();
    AtomicInteger x = new AtomicInteger(0);
    AtomicReference<Throwable> r = new AtomicReference<>();
    checkIncomplete(f);
    g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
    f.complete(1);
    checkCompletedNormally(f, 1);
    assertEquals(x.get(), 1);
    assertNull(r.get());
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:17,代碼來源:CompletableFutureTest.java

示例8: testMinimalCompletionStage2

import java.util.concurrent.CompletionStage; //導入方法依賴的package包/類
/**
 * minimalCompletionStage returns a CompletableFuture that is
 * completed exceptionally when source is.
 */
public void testMinimalCompletionStage2() {
    CompletableFuture<Integer> f = new CompletableFuture<>();
    CompletionStage<Integer> g = f.minimalCompletionStage();
    AtomicInteger x = new AtomicInteger(0);
    AtomicReference<Throwable> r = new AtomicReference<>();
    g.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
    checkIncomplete(f);
    CFException ex = new CFException();
    f.completeExceptionally(ex);
    checkCompletedExceptionally(f, ex);
    assertEquals(x.get(), 0);
    assertEquals(r.get().getCause(), ex);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:18,代碼來源:CompletableFutureTest.java

示例9: testFailedStage

import java.util.concurrent.CompletionStage; //導入方法依賴的package包/類
/**
 * failedStage returns a CompletionStage completed
 * exceptionally with the given Exception
 */
public void testFailedStage() {
    CFException ex = new CFException();
    CompletionStage<Integer> f = CompletableFuture.failedStage(ex);
    AtomicInteger x = new AtomicInteger(0);
    AtomicReference<Throwable> r = new AtomicReference<>();
    f.whenComplete((v, e) -> {if (e != null) r.set(e); else x.set(v);});
    assertEquals(x.get(), 0);
    assertEquals(r.get(), ex);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:14,代碼來源:CompletableFutureTest.java

示例10: from

import java.util.concurrent.CompletionStage; //導入方法依賴的package包/類
/**
 * Adapts a stage passed to the {@link Promise} API
 * @param <T>
 *   a type of the value
 * @param stage
 *   a {@link CompletionStage} to be wrapped
 * @return
 *   a {@link Promise}
 */
public static <T> Promise<T> from(CompletionStage<T> stage) {
    if (stage instanceof Promise) {
        return (Promise<T>) stage;
    }

    if (stage instanceof CompletableFuture) {
        return new CompletablePromise<>((CompletableFuture<T>)stage);
    }
    
    CompletablePromise<T> result = createLinkedPromise(stage);
    stage.whenComplete(handler(result::onSuccess, result::onFailure));
    return result;
}
 
開發者ID:vsilaev,項目名稱:tascalate-concurrent,代碼行數:23,代碼來源:Promises.java

示例11: setupCompletionHandlers

import java.util.concurrent.CompletionStage; //導入方法依賴的package包/類
private void setupCompletionHandlers() {
    int i = 0;
    for (CompletionStage<? extends T> promise : promises) {
        final int idx = i++;
        promise.whenComplete((r, e) -> onComplete(idx, r, e));
    }
}
 
開發者ID:vsilaev,項目名稱:tascalate-concurrent,代碼行數:8,代碼來源:AggregatingPromise.java

示例12: doApplyToEitherAsync

import java.util.concurrent.CompletionStage; //導入方法依賴的package包/類
/**
 * This method exists just to reconcile generics when called from
 * {@link #runAfterEitherAsync} which has unexpected type of parameter
 * "other". The alternative is to ignore compiler warning.
 */
private <R, U> Promise<U> doApplyToEitherAsync(CompletionStage<? extends R> first,
                                               CompletionStage<? extends R> second, 
                                               Function<? super R, U> fn, 
                                               Executor executor) {

    AbstractCompletableTask<R> nextStage = internalCreateCompletionStage(executor);

    // Next stage is not exposed to the client, so we can
    // short-circuit its initiation - just fire callbacks
    // without task execution (unlike as in other methods,
    // event in thenComposeAsync with its ad-hoc execution)

    // In certain sense, nextStage here is bogus: neither
    // of Future-defined methods are functional.
    BiConsumer<R, Throwable> action = (result, failure) -> {
        if (failure == null) {
            nextStage.onSuccess(result);
        } else {
            nextStage.onError(Promises.wrapException(failure));
        }
    };
    // only the first result is accepted by completion stage,
    // the other one is ignored
    first.whenComplete(action);
    second.whenComplete(action);

    return nextStage.thenApplyAsync(fn, executor);
}
 
開發者ID:vsilaev,項目名稱:tascalate-concurrent,代碼行數:34,代碼來源:AbstractCompletableTask.java

示例13: getBackendInfo

import java.util.concurrent.CompletionStage; //導入方法依賴的package包/類
private CompletionStage<ShardBackendInfo> getBackendInfo(final long cookie) {
    Preconditions.checkArgument(cookie == 0);

    final ShardState existing = state;
    if (existing != null) {
        return existing.getStage();
    }

    synchronized (this) {
        final ShardState recheck = state;
        if (recheck != null) {
            return recheck.getStage();
        }

        final ShardState newState = resolveBackendInfo(shardName, 0);
        state = newState;

        final CompletionStage<ShardBackendInfo> stage = newState.getStage();
        stage.whenComplete((info, failure) -> {
            if (failure != null) {
                synchronized (SimpleShardBackendResolver.this) {
                    if (state == newState) {
                        state = null;
                    }
                }
            }
        });

        return stage;
    }
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:32,代碼來源:SimpleShardBackendResolver.java

示例14: ShardState

import java.util.concurrent.CompletionStage; //導入方法依賴的package包/類
ShardState(final CompletionStage<ShardBackendInfo> stage) {
    this.stage = Preconditions.checkNotNull(stage);
    stage.whenComplete(this::onStageResolved);
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:5,代碼來源:AbstractShardBackendResolver.java

示例15: getBackendInfo

import java.util.concurrent.CompletionStage; //導入方法依賴的package包/類
@Override
public CompletionStage<ShardBackendInfo> getBackendInfo(final Long cookie) {
    /*
     * We cannot perform a simple computeIfAbsent() here because we need to control sequencing of when the state
     * is inserted into the map and retired from it (based on the stage result).
     *
     * We do not want to hook another stage one processing completes and hooking a removal on failure from a compute
     * method runs the inherent risk of stage completing before the insertion does (i.e. we have a removal of
     * non-existent element.
     */
    final ShardState existing = backends.get(cookie);
    if (existing != null) {
        return existing.getStage();
    }

    final String shardName = shards.inverse().get(cookie);
    if (shardName == null) {
        LOG.warn("Failing request for non-existent cookie {}", cookie);
        throw new IllegalArgumentException("Cookie " + cookie + " does not have a shard assigned");
    }

    LOG.debug("Resolving cookie {} to shard {}", cookie, shardName);
    final ShardState toInsert = resolveBackendInfo(shardName, cookie);

    final ShardState raced = backends.putIfAbsent(cookie, toInsert);
    if (raced != null) {
        // We have had a concurrent insertion, return that
        LOG.debug("Race during insertion of state for cookie {} shard {}", cookie, shardName);
        return raced.getStage();
    }

    // We have succeeded in populating the map, now we need to take care of pruning the entry if it fails to
    // complete
    final CompletionStage<ShardBackendInfo> stage = toInsert.getStage();
    stage.whenComplete((info, failure) -> {
        if (failure != null) {
            LOG.debug("Resolution of cookie {} shard {} failed, removing state", cookie, shardName, failure);
            backends.remove(cookie, toInsert);

            // Remove cache state in case someone else forgot to invalidate it
            flushCache(shardName);
        }
    });

    return stage;
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:47,代碼來源:ModuleShardBackendResolver.java


注:本文中的java.util.concurrent.CompletionStage.whenComplete方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。