本文整理汇总了Java中java.util.concurrent.CompletableFuture.allOf方法的典型用法代码示例。如果您正苦于以下问题:Java CompletableFuture.allOf方法的具体用法?Java CompletableFuture.allOf怎么用?Java CompletableFuture.allOf使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.util.concurrent.CompletableFuture
的用法示例。
在下文中一共展示了CompletableFuture.allOf方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testAllOf_exceptional
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
public void testAllOf_exceptional() throws Exception {
for (int k = 1; k < 10; k++) {
CompletableFuture<Integer>[] fs
= (CompletableFuture<Integer>[]) new CompletableFuture[k];
CFException ex = new CFException();
for (int i = 0; i < k; i++)
fs[i] = new CompletableFuture<>();
CompletableFuture<Void> f = CompletableFuture.allOf(fs);
for (int i = 0; i < k; i++) {
checkIncomplete(f);
checkIncomplete(CompletableFuture.allOf(fs));
if (i != k / 2) {
fs[i].complete(i);
checkCompletedNormally(fs[i], i);
} else {
fs[i].completeExceptionally(ex);
checkCompletedExceptionally(fs[i], ex);
}
}
checkCompletedWithWrappedException(f, ex);
checkCompletedWithWrappedException(CompletableFuture.allOf(fs), ex);
}
}
示例2: onProducerRemoved
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
private void onProducerRemoved(final ProducerRemoved message) {
LOG.debug("Received ProducerRemoved: {}", message);
final List<CompletableFuture<Object>> futures = new ArrayList<>();
for (final String address : resolver.getShardingServicePeerActorAddresses()) {
final ActorSelection selection = actorSystem.actorSelection(address);
futures.add(FutureConverters.toJava(
actorContext.executeOperationAsync(selection, new NotifyProducerRemoved(message.getSubtrees())))
.toCompletableFuture());
}
final CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(
futures.toArray(new CompletableFuture[futures.size()]));
final ActorRef respondTo = getSender();
combinedFuture
.thenRun(() -> respondTo.tell(new Status.Success(null), self()))
.exceptionally(e -> {
respondTo.tell(new Status.Failure(null), self());
return null;
});
}
示例3: failValidation
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
/**
* Audit a failed submission validation.
*
* @param conversionReport report of the conversion
* @return future
*/
@Override
public CompletableFuture<Void> failValidation(Converter.ConversionReport conversionReport) {
if (noAudit()) {
return null;
}
API_LOG.info("Writing audit information for a validation failure scenario");
Source qrdaSource = conversionReport.getQrdaSource();
Source qppSource = conversionReport.getQppSource();
Source validationErrorSource = conversionReport.getValidationErrorsSource();
Source rawValidationErrorSource = conversionReport.getRawValidationErrorsOrEmptySource();
Metadata metadata = initMetadata(conversionReport, Outcome.VALIDATION_ERROR);
CompletableFuture<Void> allWrites = CompletableFuture.allOf(
storeContent(rawValidationErrorSource).thenAccept(metadata::setRawValidationErrorLocator),
storeContent(validationErrorSource).thenAccept(metadata::setValidationErrorLocator),
storeContent(qppSource).thenAccept(metadata::setQppLocator),
storeContent(qrdaSource).thenAccept(metadata::setSubmissionLocator));
return allWrites.whenComplete((nada, thrown) -> persist(metadata, thrown));
}
示例4: refreshAnnotationsView
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
/**
* Refreshes the view for Annotations that already exist but are modified.
* @param observationUuid
*/
public void refreshAnnotationsView(Set<UUID> observationUuid) {
CopyOnWriteArrayList<Annotation> annotations = new CopyOnWriteArrayList<>();
final AnnotationService annotationService = toolBox.getServices().getAnnotationService();
CompletableFuture[] futures = observationUuid.stream()
.map(uuid -> annotationService.findByUuid(uuid)
.thenAccept(annotations::add))
.toArray(i -> new CompletableFuture[i]);
CompletableFuture<Void> all = CompletableFuture.allOf(futures);
final EventBus eventBus = toolBox.getEventBus();
all.thenAccept(v -> {
eventBus.send(new AnnotationsChangedEvent(annotations));
});
}
示例5: closeNodes
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
private static CompletableFuture<Void> closeNodes(Stream<BoundNode> nodes, CloseType closeType) {
return CompletableFuture.allOf(
nodes
.map(n -> n.closeConnectionsAsync(closeType).toCompletableFuture())
.collect(Collectors.toList())
.toArray(new CompletableFuture[] {}));
}
示例6: closeChannelGroup
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
private static CompletableFuture<Void> closeChannelGroup(
ChannelGroup channelGroup, CloseType closeType) {
switch (closeType) {
case DISCONNECT:
return completable(channelGroup.disconnect());
default:
return CompletableFuture.allOf(
channelGroup
.stream()
.map(
c -> {
CompletableFuture<Void> f;
Function<SocketChannel, ChannelFuture> shutdownMethod =
closeType == CloseType.SHUTDOWN_READ
? SocketChannel::shutdownInput
: SocketChannel::shutdownOutput;
if (c instanceof SocketChannel) {
f = completable(shutdownMethod.apply((SocketChannel) c));
} else {
logger.warn(
"Got {} request for non-SocketChannel {}, disconnecting instead.",
closeType,
c);
f = completable(c.disconnect());
}
return f;
})
.collect(Collectors.toList())
.toArray(new CompletableFuture[] {}));
}
}
示例7: sequence
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
private <T> CompletionStage<List<T>> sequence(final List<CompletionStage<T>> stages) {
//noinspection SuspiciousToArrayCall
final CompletableFuture<Void> done = CompletableFuture.allOf(stages.toArray(new CompletableFuture[stages.size()]));
return done.thenApply(v -> stages.stream()
.map(CompletionStage::toCompletableFuture)
.map(CompletableFuture::join)
.collect(Collectors.<T>toList())
);
}
示例8: syncProducts
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
@Nonnull
private CompletionStage<Void> syncProducts(@Nonnull final Map<ProductDraft, Product> productsToSync) {
final List<CompletableFuture<Optional<Product>>> futureUpdates =
productsToSync.entrySet().stream()
.map(entry -> fetchProductAttributesMetadataAndUpdate(entry.getValue(), entry.getKey()))
.map(CompletionStage::toCompletableFuture)
.collect(Collectors.toList());
return CompletableFuture.allOf(futureUpdates.toArray(new CompletableFuture[futureUpdates.size()]));
}
示例9: getProductSet
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
@Override
public CompletableFuture<ProductSet> getProductSet() {
CompletableFuture<ProductSet> getFuture = new CompletableFuture<>();
CompletableFuture<Void> allCompleted = CompletableFuture
.allOf(loaders.toArray(new CompletableFuture[loaders.size()]));
allCompleted.thenRun(() -> {
loaders.forEach(loader -> loader.join().forEach(loaded -> products.addProductLinkage(loaded)));
getFuture.complete(products);
}).exceptionally(t -> {
LOG.error("unexpected error loading products", t);
return null;
});
return getFuture;
}
示例10: testValueFactoryRequiresMainThreadHeldByOtherSync
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
/**
* Verifies that no deadlock occurs if the value factory synchronously blocks while switching to the UI thread.
*/
private void testValueFactoryRequiresMainThreadHeldByOtherSync(boolean passJtfToLazyCtor) throws Exception {
SynchronizationContext ctxt = SingleThreadedSynchronizationContext.create();
SynchronizationContext.setSynchronizationContext(ctxt);
JoinableFutureContext context = new JoinableFutureContext();
JoinableFutureFactory asyncPump = context.getFactory();
Thread originalThread = Thread.currentThread();
AsyncManualResetEvent evt = new AsyncManualResetEvent();
AsyncLazy<Object> lazy = new AsyncLazy<>(
() -> {
// It is important that no await appear before this JFF.run call, since
// we're testing that the value factory is not invoked while the AsyncLazy
// holds a private lock that would deadlock when called from another thread.
asyncPump.run(() -> Async.awaitAsync(asyncPump.switchToMainThreadAsync(getTimeoutToken())));
return Async.awaitAsync(
Async.yieldAsync(),
() -> CompletableFuture.completedFuture(new Object()));
},
// mix it up to exercise all the code paths in the ctor.
passJtfToLazyCtor ? asyncPump : null);
CompletableFuture<?> backgroundRequest = Futures.supplyAsync(() -> Async.awaitAsync(lazy.getValueAsync()));
// Give the background thread time to call GetValueAsync(), but it doesn't yield (when the test was written).
Thread.sleep(ASYNC_DELAY.toMillis());
CompletableFuture<?> foregroundRequest = lazy.getValueAsync();
Frame frame = SingleThreadedSynchronizationContext.newFrame();
CompletableFuture<?> combinedTask = CompletableFuture.allOf(foregroundRequest, backgroundRequest);
TplExtensions.withTimeout(combinedTask, UNEXPECTED_TIMEOUT).thenRun(() -> frame.setContinue(false));
SingleThreadedSynchronizationContext.pushFrame(ctxt, frame);
// Ensure that the test didn't simply timeout, and that the individual tasks did not throw.
Assert.assertTrue(foregroundRequest.isDone());
Assert.assertTrue(backgroundRequest.isDone());
Assert.assertSame(foregroundRequest.join(), backgroundRequest.join());
}
示例11: onProducerCreated
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
private void onProducerCreated(final ProducerCreated message) {
LOG.debug("Received ProducerCreated: {}", message);
// fastpath if we have no peers
if (resolver.getShardingServicePeerActorAddresses().isEmpty()) {
getSender().tell(new Status.Success(null), noSender());
}
final ActorRef sender = getSender();
final Collection<DOMDataTreeIdentifier> subtrees = message.getSubtrees();
final List<CompletableFuture<Object>> futures = new ArrayList<>();
for (final String address : resolver.getShardingServicePeerActorAddresses()) {
final ActorSelection actorSelection = actorSystem.actorSelection(address);
futures.add(
FutureConverters.toJava(
actorContext.executeOperationAsync(
actorSelection, new NotifyProducerCreated(subtrees), DEFAULT_ASK_TIMEOUT))
.toCompletableFuture());
}
final CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(
futures.toArray(new CompletableFuture[futures.size()]));
combinedFuture
.thenRun(() -> sender.tell(new Success(null), noSender()))
.exceptionally(throwable -> {
sender.tell(new Status.Failure(throwable), self());
return null;
});
}
示例12: balanceRoles
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
@Override
public void balanceRoles() {
List<ControllerNode> nodes = newArrayList(clusterService.getNodes());
Map<ControllerNode, Set<DeviceId>> controllerDevices = new HashMap<>();
int deviceCount = 0;
// Create buckets reflecting current ownership.
for (ControllerNode node : nodes) {
if (clusterService.getState(node.id()).isActive()) {
Set<DeviceId> devicesOf = new HashSet<>(getDevicesOf(node.id()));
deviceCount += devicesOf.size();
controllerDevices.put(node, devicesOf);
log.info("Node {} has {} devices.", node.id(), devicesOf.size());
}
}
if (useRegionForBalanceRoles && balanceRolesUsingRegions(controllerDevices)) {
return;
}
// Now re-balance the buckets until they are roughly even.
List<CompletableFuture<Void>> balanceBucketsFutures = balanceControllerNodes(controllerDevices, deviceCount);
CompletableFuture<Void> balanceRolesFuture = CompletableFuture.allOf(
balanceBucketsFutures.toArray(new CompletableFuture[balanceBucketsFutures.size()]));
Futures.getUnchecked(balanceRolesFuture);
}
示例13: balanceBuckets
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
/**
* Balance the node buckets by moving devices from largest to smallest node.
*
* @param smallest node that is master of the smallest number of devices
* @param largest node that is master of the largest number of devices
* @param controllerDevices controller nodes to devices map
* @param deviceCount number of devices mastered by controller nodes
* @return list of setRole futures for "moved" devices
*/
private CompletableFuture<Void> balanceBuckets(ControllerNode smallest, ControllerNode largest,
Map<ControllerNode, Set<DeviceId>> controllerDevices,
int deviceCount) {
Collection<DeviceId> minBucket = controllerDevices.get(smallest);
Collection<DeviceId> maxBucket = controllerDevices.get(largest);
int bucketCount = controllerDevices.keySet().size();
int delta = (maxBucket.size() - minBucket.size()) / 2;
delta = Math.min(deviceCount / bucketCount, delta);
List<CompletableFuture<Void>> setRoleFutures = Lists.newLinkedList();
if (delta > 0) {
log.info("Attempting to move {} nodes from {} to {}...", delta,
largest.id(), smallest.id());
int i = 0;
Iterator<DeviceId> it = maxBucket.iterator();
while (it.hasNext() && i < delta) {
DeviceId deviceId = it.next();
log.info("Setting {} as the master for {}", smallest.id(), deviceId);
setRoleFutures.add(setRole(smallest.id(), deviceId, MASTER));
controllerDevices.get(smallest).add(deviceId);
it.remove();
i++;
}
}
return CompletableFuture.allOf(setRoleFutures.toArray(new CompletableFuture[setRoleFutures.size()]));
}
示例14: evict
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
@Override
public CompletableFuture<Void> evict(NodeId nodeId) {
return CompletableFuture.allOf(getLeaderElectors().stream()
.map(le -> le.evict(nodeId))
.toArray(CompletableFuture[]::new));
}
示例15: addListener
import java.util.concurrent.CompletableFuture; //导入方法依赖的package包/类
@Override
public CompletableFuture<Void> addListener(MapEventListener<K, V> listener, Executor executor) {
return CompletableFuture.allOf(getMaps().stream()
.map(map -> map.addListener(listener, executor))
.toArray(CompletableFuture[]::new));
}