当前位置: 首页>>代码示例>>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;未经允许,请勿转载。