List of usage examples for com.google.common.util.concurrent Futures getUnchecked
@GwtIncompatible("TODO") public static <V> V getUnchecked(Future<V> future)
From source file:org.excalibur.core.util.concurrent.Futures2.java
/** * Returns the result of calling {@link Future#get()} uninterruptibly on a task known not to throw a checked exception. This makes {@code Future} * more suitable for lightweight, fast-running tasks that, barring bugs in the code, will not fail. This gives it exception-handling behavior * similar to that of {@code ForkJoinTask.join}. * // w w w. ja va 2 s. c o m * <p> * Exceptions from {@code Future.get} are treated as follows: * <ul> * <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an {@link UncheckedExecutionException} (if the cause is an {@code Exception} * ) or {@link ExecutionError} (if the cause is an {@code Error}). * <li>Any {@link InterruptedException} causes a retry of the {@code get} call. The interrupt is restored before {@code getUnchecked} returns. * <li>Any {@link CancellationException} is propagated untouched. So is any other {@link RuntimeException} ({@code get} implementations are * discouraged from throwing such exceptions). * </ul> * * <p> * The overall principle is to eliminate all checked exceptions: to loop to avoid {@code InterruptedException}, to pass through * {@code CancellationException}, and to wrap any exception from the underlying computation in an {@code UncheckedExecutionException} or * {@code ExecutionError}. * * <p> * For an uninterruptible {@code get} that preserves other exceptions, see {@link Uninterruptibles#getUninterruptibly(Future)}. * * @throws UncheckedExecutionException * if {@code get} throws an {@code ExecutionException} with an {@code Exception} as its cause * @throws ExecutionError * if {@code get} throws an {@code ExecutionException} with an {@code Error} as its cause * @throws CancellationException * if {@code get} throws a {@code CancellationException} */ public static <V> List<V> getUnchecked(List<Future<V>> futures) { List<V> results = Lists.newArrayList(); for (Future<V> future : futures) { results.add(Futures.getUnchecked(future)); } return results; }
From source file:com.continuuity.loom.common.zookeeper.lib.SynchronizedZKMap.java
private T removeInternal(Object key) { if (!(key instanceof String)) { throw new IllegalArgumentException( "Expected key of type java.lang.String but was " + (key == null ? null : key.getClass())); }// w w w . ja v a2 s. c o m if (!currentView.containsKey(key)) { return null; } Map<String, T> current = Maps.newHashMap(currentView); T removed = current.remove(key); currentView = ImmutableMap.<String, T>builder().putAll(current).build(); // note: we cannot only issue remove from zk if removed != null because even if removed == null this could mean // the element was removed (and for other race-condition reasons) Futures.getUnchecked(ZKClientExt.delete(zkClient, getItemNodePath((String) key), true)); return removed; }
From source file:org.onosproject.incubator.net.virtual.impl.VirtualNetworkMastershipManager.java
@Override public void balanceRoles() { //FIXME: More advanced logic for balancing virtual network roles. List<ControllerNode> nodes = clusterService.getNodes().stream() .filter(n -> clusterService.getState(n.id()).equals(ControllerNode.State.ACTIVE)) .collect(Collectors.toList()); nodes.sort(Comparator.comparing(ControllerNode::id)); //Pick a node using network Id, NodeId masterNode = nodes.get((int) ((networkId.id() - 1) % nodes.size())).id(); List<CompletableFuture<Void>> setRoleFutures = Lists.newLinkedList(); for (VirtualDevice device : manager.getVirtualDevices(networkId)) { setRoleFutures.add(setRole(masterNode, device.id(), MastershipRole.MASTER)); }/*from ww w. jav a2 s. c o m*/ CompletableFuture<Void> balanceRolesFuture = CompletableFuture .allOf(setRoleFutures.toArray(new CompletableFuture[setRoleFutures.size()])); Futures.getUnchecked(balanceRolesFuture); }
From source file:org.apache.aurora.scheduler.app.local.FakeMaster.java
@Override public Status launchTasks(Collection<OfferID> offerIds, Collection<TaskInfo> tasks) { assertNotStopped();/*from ww w .jav a2 s. co m*/ OfferID id = Iterables.getOnlyElement(offerIds); Offer offer = sentOffers.remove(id); checkState(offer != null, "Offer " + id + " is invalid."); final TaskInfo task = Iterables.getOnlyElement(tasks); synchronized (activeTasks) { checkState(!activeTasks.containsKey(task.getTaskId()), "Task " + task.getTaskId() + " already exists."); activeTasks.put(task.getTaskId(), new Task(offer, task)); } executor.schedule( () -> Futures.getUnchecked(schedulerFuture).statusUpdate(this, TaskStatus.newBuilder() .setTaskId(task.getTaskId()).setState(TaskState.TASK_RUNNING).build()), 1, TimeUnit.SECONDS); return Status.DRIVER_RUNNING; }
From source file:org.apache.aurora.scheduler.mesos.VersionedSchedulerDriverService.java
@Override public void acknowledgeStatusUpdate(TaskStatus status) { // The Mesos API says frameworks are only supposed to acknowledge status updates // with a UUID. The V0Driver accepts them just fine but the V1Driver logs every time // a status update is given without a uuid. To silence logs, we drop them here. whenRegistered(() -> {/*w w w. j a v a 2 s . co m*/ if (!status.hasUuid()) { return; } LOG.info("Acking status update for {} with uuid: {}", status.getTaskId().getValue(), status.getUuid()); Futures.getUnchecked(mesosFuture) .send(Call.newBuilder().setType(Call.Type.ACKNOWLEDGE).setFrameworkId(getFrameworkId()) .setAcknowledge(Call.Acknowledge.newBuilder().setAgentId(status.getAgentId()) .setTaskId(status.getTaskId()).setUuid(status.getUuid())) .build()); }); }
From source file:co.cask.cdap.common.twill.AbstractDistributedMasterServiceManager.java
@Override public void restartAllInstances() { Iterable<TwillController> twillControllers = twillRunnerService.lookup(Constants.Service.MASTER_SERVICES); for (TwillController twillController : twillControllers) { // Call restart instances Futures.getUnchecked(twillController.restartAllInstances(serviceName)); }/*from w w w. j a v a2 s . co m*/ }
From source file:com.continuuity.loom.common.zookeeper.lib.SynchronizedZKMap.java
private void clearInternal() { if (currentView.size() > 0) { currentView = Collections.emptyMap(); NodeChildren nodeChildren = Futures.getUnchecked(zkClient.getChildren(ENTRIES_PATH)); List<ListenableFuture<String>> deleteFutures = Lists.newArrayList(); for (String node : nodeChildren.getChildren()) { deleteFutures.add(ZKClientExt.delete(zkClient, getNodePath(node), true)); }//from www.ja v a 2 s. com Futures.getUnchecked(Futures.allAsList(deleteFutures)); } }
From source file:com.continuuity.loom.common.zookeeper.lib.ZKMap.java
private void setExternalChangeWatcher() throws ExecutionException, InterruptedException { ZKOperations.watchChildren(zkClient, "", new ZKOperations.ChildrenCallback() { @Override/*w w w .jav a 2s . com*/ public void updated(NodeChildren nodeChildren) { List<String> nodes = nodeChildren.getChildren(); final Map<String, ListenableFuture<NodeData>> nodeAndDataFutures = Maps.newHashMap(); List<OperationFuture<NodeData>> dataFutures = Lists.newArrayList(); for (String node : nodes) { OperationFuture<NodeData> dataFuture = zkClient.getData(getNodePath(node)); dataFutures.add(dataFuture); nodeAndDataFutures.put(node, dataFuture); } final ListenableFuture<List<NodeData>> fetchFuture = Futures.successfulAsList(dataFutures); fetchFuture.addListener(new Runnable() { @Override public void run() { ImmutableMap.Builder<String, T> builder = ImmutableMap.builder(); for (Map.Entry<String, ListenableFuture<NodeData>> nodeAndData : nodeAndDataFutures .entrySet()) { T value = serializer .deserialize(Futures.getUnchecked(nodeAndData.getValue()).getData()); builder.put(nodeAndData.getKey(), value); } currentView.set(builder.build()); updateWaitingForElements(); } }, Threads.SAME_THREAD_EXECUTOR); } }); }
From source file:com.facebook.buck.distributed.DistBuildArtifactCacheImpl.java
@Override public synchronized ListenableFuture<BuildRule> uploadFromLocal(BuildRule rule) throws IOException { Preconditions.checkState(localCache.isPresent()); if (localUploadFutures.containsKey(rule)) { return localUploadFutures.get(rule); }/*from w w w . j ava 2s. c o m*/ ListenableFuture<RuleKey> asyncRuleKey = ruleKeyCalculator.calculate(eventBus, rule); NamedTemporaryFile releasedFile; ListenableFuture<CacheResult> asyncfetchResult; try (CloseableHolder<NamedTemporaryFile> tempFile = new CloseableHolder<>( new NamedTemporaryFile(MostFiles.sanitize(rule.getBuildTarget().getShortName()), ""))) { asyncfetchResult = Futures.transformAsync(asyncRuleKey, ruleKey -> localCache.get().fetchAsync(rule.getBuildTarget(), ruleKey, LazyPath.ofInstance(tempFile.get().get())), // We should already have computed the rulekey before calling this method, so using // DirectExecutor here is fine. MoreExecutors.directExecutor()); releasedFile = tempFile.release(); } ListenableFuture<Void> uploadFuture = Futures.transformAsync(asyncfetchResult, fetchResult -> { if (!fetchResult.getType().isSuccess()) { LOG.error("Could not upload missing target [%s] from local cache.", rule.getBuildTarget().getFullyQualifiedName()); return Futures.immediateFuture(null); } return remoteCache.store( ArtifactInfo.builder().setRuleKeys(ImmutableSet.of(Futures.getUnchecked(asyncRuleKey))) .setMetadata(fetchResult.getMetadata()).build(), BorrowablePath.notBorrowablePath(releasedFile.get())); }, executorService); ListenableFuture<BuildRule> finalFuture = Futures.transform(uploadFuture, result -> { try { releasedFile.close(); } catch (IOException e) { throw new RuntimeException(e); } return rule; }, MoreExecutors.directExecutor()); localUploadFutures.put(rule, finalFuture); return finalFuture; }
From source file:co.cask.cdap.common.twill.AbstractDistributedMasterServiceManager.java
@Override public void restartInstances(int instanceId, int... moreInstanceIds) { Iterable<TwillController> twillControllers = twillRunnerService.lookup(Constants.Service.MASTER_SERVICES); for (TwillController twillController : twillControllers) { // Call restart instances Futures.getUnchecked(twillController.restartInstances(serviceName, instanceId, moreInstanceIds)); }/* w ww . j a va 2 s .co m*/ }