List of usage examples for com.google.common.util.concurrent Futures successfulAsList
@Beta @CheckReturnValue public static <V> ListenableFuture<List<V>> successfulAsList( Iterable<? extends ListenableFuture<? extends V>> futures)
From source file:com.google.cloud.bigtable.hbase.BatchExecutor.java
/** * Implementation of/*from w ww . ja va 2s. com*/ * {@link org.apache.hadoop.hbase.client.HTable#batchCallback(List, Object[], Batch.Callback)} * * @param actions a {@link java.util.List} object. * @param results an array of {@link java.lang.Object} objects. * @param callback a {@link org.apache.hadoop.hbase.client.coprocessor.Batch.Callback} object. * @throws java.io.IOException if any. * @throws java.lang.InterruptedException if any. * @param <R> a R object. */ public <R> void batchCallback(List<? extends Row> actions, Object[] results, Batch.Callback<R> callback) throws IOException, InterruptedException { Preconditions.checkArgument(results.length == actions.size(), "Result array must be the same length as actions."); Timer.Context timerContext = batchTimer.time(); try { // Don't want to throw an exception for failed futures, instead the place in results is // set to null. Futures.successfulAsList(issueAsyncRowRequests(actions, results, callback)).get(); } catch (ExecutionException e) { LOG.error("Encountered exception in batchCallback(List<>, Object[], Batch.Callback). ", e); throw new IOException("batchCallback error", e); } finally { timerContext.close(); } }
From source file:org.jclouds.aliyun.ecs.compute.strategy.CreateResourcesThenCreateNodes.java
private void registerAutoGeneratedKeyPairCleanupCallbacks(Map<?, ListenableFuture<Void>> responses, final String regionId, final String keyPairName) { // The Futures.allAsList fails immediately if some of the futures fail. // The Futures.successfulAsList, however, // returns a list containing the results or 'null' for those futures that // failed. We want to wait for all them // (even if they fail), so better use the latter form. ListenableFuture<List<Void>> aggregatedResponses = Futures.successfulAsList(responses.values()); // Key pairs must be cleaned up after all futures completed (even if some // failed).// ww w .j a va 2s .co m Futures.addCallback(aggregatedResponses, new FutureCallback<List<Void>>() { @Override public void onSuccess(List<Void> result) { cleanupAutoGeneratedKeyPairs(keyPairName); } @Override public void onFailure(Throwable t) { cleanupAutoGeneratedKeyPairs(keyPairName); } private void cleanupAutoGeneratedKeyPairs(String keyPairName) { logger.debug(">> cleaning up auto-generated key pairs..."); try { api.sshKeyPairApi().delete(regionId, keyPairName); } catch (Exception ex) { logger.warn(">> could not delete key pair %s: %s", keyPairName, ex.getMessage()); } } }, userExecutor); }
From source file:org.opendaylight.openflowplugin.impl.util.DeviceInitializationUtils.java
private static ListenableFuture<List<RpcResult<List<MultipartReply>>>> createDeviceFeaturesForOF13( final DeviceContext deviceContext, final DeviceState deviceState, final boolean switchFeaturesMandatory) { final ListenableFuture<RpcResult<List<MultipartReply>>> replyDesc = getNodeStaticInfo( MultipartType.OFPMPDESC, deviceContext, deviceState.getNodeInstanceIdentifier(), deviceState.getVersion());//w ww . j av a 2 s. c om //first process description reply, write data to DS and write consequent data if successful return Futures.transform(replyDesc, new AsyncFunction<RpcResult<List<MultipartReply>>, List<RpcResult<List<MultipartReply>>>>() { @Override public ListenableFuture<List<RpcResult<List<MultipartReply>>>> apply( final RpcResult<List<MultipartReply>> rpcResult) throws Exception { translateAndWriteReply(MultipartType.OFPMPDESC, deviceContext, deviceState.getNodeInstanceIdentifier(), rpcResult.getResult()); final ListenableFuture<RpcResult<List<MultipartReply>>> replyMeterFeature = getNodeStaticInfo( MultipartType.OFPMPMETERFEATURES, deviceContext, deviceState.getNodeInstanceIdentifier(), deviceState.getVersion()); createSuccessProcessingCallback(MultipartType.OFPMPMETERFEATURES, deviceContext, deviceState.getNodeInstanceIdentifier(), replyMeterFeature); final ListenableFuture<RpcResult<List<MultipartReply>>> replyGroupFeatures = getNodeStaticInfo( MultipartType.OFPMPGROUPFEATURES, deviceContext, deviceState.getNodeInstanceIdentifier(), deviceState.getVersion()); createSuccessProcessingCallback(MultipartType.OFPMPGROUPFEATURES, deviceContext, deviceState.getNodeInstanceIdentifier(), replyGroupFeatures); final ListenableFuture<RpcResult<List<MultipartReply>>> replyTableFeatures = getNodeStaticInfo( MultipartType.OFPMPTABLEFEATURES, deviceContext, deviceState.getNodeInstanceIdentifier(), deviceState.getVersion()); createSuccessProcessingCallback(MultipartType.OFPMPTABLEFEATURES, deviceContext, deviceState.getNodeInstanceIdentifier(), replyTableFeatures); final ListenableFuture<RpcResult<List<MultipartReply>>> replyPortDescription = getNodeStaticInfo( MultipartType.OFPMPPORTDESC, deviceContext, deviceState.getNodeInstanceIdentifier(), deviceState.getVersion()); createSuccessProcessingCallback(MultipartType.OFPMPPORTDESC, deviceContext, deviceState.getNodeInstanceIdentifier(), replyPortDescription); if (switchFeaturesMandatory) { return Futures.allAsList(Arrays.asList(replyMeterFeature, replyGroupFeatures, replyTableFeatures, replyPortDescription)); } else { return Futures.successfulAsList(Arrays.asList(replyMeterFeature, replyGroupFeatures, replyTableFeatures, replyPortDescription)); } } }); }
From source file:org.thingsboard.server.actors.plugin.PluginProcessingContext.java
private void convertFuturesAndAddCallback(PluginCallback<List<AttributeKvEntry>> callback, List<ListenableFuture<List<AttributeKvEntry>>> futures) { ListenableFuture<List<AttributeKvEntry>> future = Futures.transform(Futures.successfulAsList(futures), (Function<? super List<List<AttributeKvEntry>>, ? extends List<AttributeKvEntry>>) input -> { List<AttributeKvEntry> result = new ArrayList<>(); input.forEach(r -> result.addAll(r)); return result; }, executor);//ww w . j a va2 s . c o m Futures.addCallback(future, getCallback(callback, v -> v), executor); }
From source file:org.apache.twill.internal.appmaster.RunningContainers.java
/** * Stops all running services. Only called when the AppMaster stops. *///from w w w. ja v a 2 s . c o m void stopAll() { containerLock.lock(); // Stop the runnables one by one in reverse order of start sequence List<String> reverseRunnables = new LinkedList<>(); try { Iterators.addAll(reverseRunnables, startSequence.descendingIterator()); } finally { containerLock.unlock(); } List<ListenableFuture<Service.State>> futures = Lists.newLinkedList(); for (String runnableName : reverseRunnables) { LOG.info("Stopping all instances of " + runnableName); futures.clear(); // Parallel stops all running containers of the current runnable. containerLock.lock(); try { for (TwillContainerController controller : containers.row(runnableName).values()) { futures.add(controller.stop()); } } finally { containerLock.unlock(); } // Wait for containers to stop. Assumes the future returned by Futures.successfulAsList won't throw exception. // This will block until handleCompleted() is run for the runnables or a timeout occurs. Futures.getUnchecked(Futures.successfulAsList(futures)); LOG.info("Terminated all instances of " + runnableName); } // When we acquire this lock, all stopped runnables should have been cleaned up by handleCompleted() method containerLock.lock(); try { for (Map.Entry<String, Map<String, TwillContainerController>> entry : containers.rowMap().entrySet()) { String runnableName = entry.getKey(); Collection<ContainerInfo> containerInfos = containerStats.get(runnableName); for (Map.Entry<String, TwillContainerController> containerControllerEntry : entry.getValue() .entrySet()) { for (ContainerInfo containerInfo : containerInfos) { if (containerInfo.getId().equals(containerControllerEntry.getKey())) { // Only call eventHandler.containerStopped if container is not removed by handleCompleted eventHandler.containerStopped(runnableName, containerControllerEntry.getValue().getInstanceId(), containerControllerEntry.getKey(), ContainerExitCodes.ABORTED); break; } } } } containers.clear(); runnableInstances.clear(); numRetries.clear(); containerStats.clear(); } finally { containerLock.unlock(); } }
From source file:org.apache.cassandra.service.ActiveRepairService.java
/** * Submit anti-compaction jobs to CompactionManager. * When all jobs are done, parent repair session is removed whether those are suceeded or not. * * @param parentRepairSession parent repair session ID * @return Future result of all anti-compaction jobs. *///from ww w .j a v a2 s.c o m @SuppressWarnings("resource") public ListenableFuture<List<Object>> doAntiCompaction(final UUID parentRepairSession, Collection<Range<Token>> successfulRanges) { assert parentRepairSession != null; ParentRepairSession prs = getParentRepairSession(parentRepairSession); //A repair will be marked as not global if it is a subrange repair to avoid many small anti-compactions //in addition to other scenarios such as repairs not involving all DCs or hosts if (!prs.isGlobal) { logger.info("Not a global repair, will not do anticompaction"); removeParentRepairSession(parentRepairSession); return Futures.immediateFuture(Collections.emptyList()); } assert prs.ranges.containsAll(successfulRanges) : "Trying to perform anticompaction on unknown ranges"; List<ListenableFuture<?>> futures = new ArrayList<>(); // if we don't have successful repair ranges, then just skip anticompaction if (!successfulRanges.isEmpty()) { for (Map.Entry<UUID, ColumnFamilyStore> columnFamilyStoreEntry : prs.columnFamilyStores.entrySet()) { Refs<SSTableReader> sstables = prs.getAndReferenceSSTables(columnFamilyStoreEntry.getKey()); ColumnFamilyStore cfs = columnFamilyStoreEntry.getValue(); futures.add(CompactionManager.instance.submitAntiCompaction(cfs, successfulRanges, sstables, prs.repairedAt)); } } ListenableFuture<List<Object>> allAntiCompactionResults = Futures.successfulAsList(futures); allAntiCompactionResults.addListener(new Runnable() { @Override public void run() { removeParentRepairSession(parentRepairSession); } }, MoreExecutors.sameThreadExecutor()); return allAntiCompactionResults; }
From source file:org.thingsboard.server.dao.relation.BaseRelationService.java
@Override public ListenableFuture<List<EntityRelationInfo>> findInfoByFrom(TenantId tenantId, EntityId from, RelationTypeGroup typeGroup) {/* www. j a v a 2s .c o m*/ log.trace("Executing findInfoByFrom [{}][{}]", from, typeGroup); validate(from); validateTypeGroup(typeGroup); ListenableFuture<List<EntityRelation>> relations = relationDao.findAllByFrom(tenantId, from, typeGroup); return Futures.transformAsync(relations, relations1 -> { List<ListenableFuture<EntityRelationInfo>> futures = new ArrayList<>(); relations1.forEach(relation -> futures.add(fetchRelationInfoAsync(tenantId, relation, EntityRelation::getTo, EntityRelationInfo::setToName))); return Futures.successfulAsList(futures); }); }
From source file:com.sri.ai.util.concurrent.BranchAndMerge.java
private static <V, T> Result<T> executeConcurrent(List<? extends Callable<V>> tasks, Predicate<V> cancelOutstandingOnSuccess, Predicate<Throwable> cancelOutstandingOnFailure, Function<List<V>, T> transformResults) { boolean failureOccurred = false; T result = null;/* ww w .j av a2s .c om*/ try { List<Future<V>> invokedFutures = _sharedExecutorService.invokeAll(tasks); List<ListenableFuture<V>> lfutures = new ArrayList<ListenableFuture<V>>(); for (Future<V> future : invokedFutures) { lfutures.add((ListenableFuture<V>) future); } CancelOutstandingCallback<V> cancelOutstandingCallback = new CancelOutstandingCallback<V>( cancelOutstandingOnSuccess, cancelOutstandingOnFailure, lfutures); for (ListenableFuture<V> future : lfutures) { Futures.addCallback(future, cancelOutstandingCallback); } ListenableFuture<List<V>> resultsFuture = Futures.successfulAsList(lfutures); List<V> resultValues = resultsFuture.get(); if (cancelOutstandingCallback.failureOccurred()) { failureOccurred = true; // If I don't cancel outstanding on failure // then I'll attempt to create a result if (!cancelOutstandingOnFailure.apply(null)) { result = transformResults.apply(resultValues); } } else { result = transformResults.apply(resultValues); } } catch (Throwable t) { failureOccurred = true; } return new DefaultResult<T>(failureOccurred, result); }
From source file:org.apache.twill.discovery.ZKDiscoveryService.java
/** * Creates a CacheLoader for creating live Iterable for watching instances changes for a given service. *///from www .j a va 2 s. c o m private CacheLoader<String, ServiceDiscoveredCacheEntry> createServiceLoader() { return new CacheLoader<String, ServiceDiscoveredCacheEntry>() { @Override public ServiceDiscoveredCacheEntry load(String service) throws Exception { final DefaultServiceDiscovered serviceDiscovered = new DefaultServiceDiscovered(service); final String pathBase = "/" + service; // Watch for children changes in /service Cancellable cancellable = ZKOperations.watchChildren(zkClient, pathBase, new ZKOperations.ChildrenCallback() { @Override public void updated(NodeChildren nodeChildren) { // Fetch data of all children nodes in parallel. List<String> children = nodeChildren.getChildren(); List<OperationFuture<NodeData>> dataFutures = Lists .newArrayListWithCapacity(children.size()); for (String child : children) { dataFutures.add(zkClient.getData(pathBase + "/" + child)); } // Update the service map when all fetching are done. final ListenableFuture<List<NodeData>> fetchFuture = Futures .successfulAsList(dataFutures); fetchFuture.addListener(new Runnable() { @Override public void run() { ImmutableSet.Builder<Discoverable> builder = ImmutableSet.builder(); for (NodeData nodeData : Futures.getUnchecked(fetchFuture)) { // For successful fetch, decode the content. if (nodeData != null) { Discoverable discoverable = DiscoverableAdapter .decode(nodeData.getData()); if (discoverable != null) { builder.add(discoverable); } } } serviceDiscovered.setDiscoverables(builder.build()); } }, Threads.SAME_THREAD_EXECUTOR); } }); return new ServiceDiscoveredCacheEntry(serviceDiscovered, cancellable); } }; }
From source file:org.thingsboard.server.dao.relation.BaseRelationService.java
@Override public ListenableFuture<List<EntityRelationInfo>> findInfoByTo(TenantId tenantId, EntityId to, RelationTypeGroup typeGroup) {//www . ja v a2 s . co m log.trace("Executing findInfoByTo [{}][{}]", to, typeGroup); validate(to); validateTypeGroup(typeGroup); ListenableFuture<List<EntityRelation>> relations = relationDao.findAllByTo(tenantId, to, typeGroup); return Futures.transformAsync(relations, relations1 -> { List<ListenableFuture<EntityRelationInfo>> futures = new ArrayList<>(); relations1.forEach(relation -> futures.add(fetchRelationInfoAsync(tenantId, relation, EntityRelation::getFrom, EntityRelationInfo::setFromName))); return Futures.successfulAsList(futures); }); }