Example usage for com.google.common.util.concurrent Futures getUnchecked

List of usage examples for com.google.common.util.concurrent Futures getUnchecked

Introduction

In this page you can find the example usage for com.google.common.util.concurrent Futures getUnchecked.

Prototype

@GwtIncompatible("TODO")
public static <V> V getUnchecked(Future<V> future) 

Source Link

Document

Returns the result of calling Future#get() uninterruptibly on a task known not to throw a checked exception.

Usage

From source file:org.apache.cassandra.repair.RepairJob.java

/**
 * Runs repair job./*from   w  w  w . j  a  va 2  s .co  m*/
 *
 * This sets up necessary task and runs them on given {@code taskExecutor}.
 * After submitting all tasks, waits until validation with replica completes.
 */
public void run() {
    List<InetAddress> allEndpoints = new ArrayList<>(session.endpoints);
    allEndpoints.add(FBUtilities.getBroadcastAddress());

    ListenableFuture<List<TreeResponse>> validations;
    // Create a snapshot at all nodes unless we're using pure parallel repairs
    if (parallelismDegree != RepairParallelism.PARALLEL) {
        // Request snapshot to all replica
        List<ListenableFuture<InetAddress>> snapshotTasks = new ArrayList<>(allEndpoints.size());
        for (InetAddress endpoint : allEndpoints) {
            SnapshotTask snapshotTask = new SnapshotTask(desc, endpoint);
            snapshotTasks.add(snapshotTask);
            taskExecutor.execute(snapshotTask);
        }
        // When all snapshot complete, send validation requests
        ListenableFuture<List<InetAddress>> allSnapshotTasks = Futures.allAsList(snapshotTasks);
        validations = Futures.transform(allSnapshotTasks,
                new AsyncFunction<List<InetAddress>, List<TreeResponse>>() {
                    public ListenableFuture<List<TreeResponse>> apply(List<InetAddress> endpoints)
                            throws Exception {
                        logger.info(String.format("[repair #%s] requesting merkle trees for %s (to %s)",
                                desc.sessionId, desc.columnFamily, endpoints));
                        if (parallelismDegree == RepairParallelism.SEQUENTIAL)
                            return sendSequentialValidationRequest(endpoints);
                        else
                            return sendDCAwareValidationRequest(endpoints);
                    }
                }, taskExecutor);
    } else {
        logger.info(String.format("[repair #%s] requesting merkle trees for %s (to %s)", desc.sessionId,
                desc.columnFamily, allEndpoints));
        // If not sequential, just send validation request to all replica
        validations = sendValidationRequest(allEndpoints);
    }

    // When all validations complete, submit sync tasks
    ListenableFuture<List<SyncStat>> syncResults = Futures.transform(validations,
            new AsyncFunction<List<TreeResponse>, List<SyncStat>>() {
                public ListenableFuture<List<SyncStat>> apply(List<TreeResponse> trees) throws Exception {
                    InetAddress local = FBUtilities.getLocalAddress();

                    List<SyncTask> syncTasks = new ArrayList<>();
                    // We need to difference all trees one against another
                    for (int i = 0; i < trees.size() - 1; ++i) {
                        TreeResponse r1 = trees.get(i);
                        for (int j = i + 1; j < trees.size(); ++j) {
                            TreeResponse r2 = trees.get(j);
                            SyncTask task;
                            if (r1.endpoint.equals(local) || r2.endpoint.equals(local)) {
                                task = new LocalSyncTask(desc, r1, r2, repairedAt);
                            } else {
                                task = new RemoteSyncTask(desc, r1, r2);
                                // RemoteSyncTask expects SyncComplete message sent back.
                                // Register task to RepairSession to receive response.
                                session.waitForSync(Pair.create(desc, new NodePair(r1.endpoint, r2.endpoint)),
                                        (RemoteSyncTask) task);
                            }
                            syncTasks.add(task);
                            taskExecutor.submit(task);
                        }
                    }
                    return Futures.allAsList(syncTasks);
                }
            }, taskExecutor);

    // When all sync complete, set the final result
    Futures.addCallback(syncResults, new FutureCallback<List<SyncStat>>() {
        public void onSuccess(List<SyncStat> stats) {
            logger.info(String.format("[repair #%s] %s is fully synced", session.getId(), desc.columnFamily));
            SystemDistributedKeyspace.successfulRepairJob(session.getId(), desc.keyspace, desc.columnFamily);
            set(new RepairResult(desc, stats));
        }

        /**
         * Snapshot, validation and sync failures are all handled here
         */
        public void onFailure(Throwable t) {
            logger.warn(String.format("[repair #%s] %s sync failed", session.getId(), desc.columnFamily));
            SystemDistributedKeyspace.failedRepairJob(session.getId(), desc.keyspace, desc.columnFamily, t);
            setException(t);
        }
    }, taskExecutor);

    // Wait for validation to complete
    Futures.getUnchecked(validations);
}

From source file:com.tribesman.kobocoinj.examples.ExamplePaymentChannelClient.java

private void waitForSufficientBalance(BigInteger amount) {
    // Not enough money in the wallet.
    BigInteger amountPlusFee = amount.add(Wallet.SendRequest.DEFAULT_FEE_PER_KB);
    // ESTIMATED because we don't really need to wait for confirmation.
    ListenableFuture<BigInteger> balanceFuture = appKit.wallet().getBalanceFuture(amountPlusFee,
            Wallet.BalanceType.ESTIMATED);
    if (!balanceFuture.isDone()) {
        System.out.println("Please send " + Utils.kobocoinValueToFriendlyString(amountPlusFee) + " BTC to "
                + myKey.toAddress(params));
        Futures.getUnchecked(balanceFuture);
    }/*  w  ww .j av  a2s  . c om*/
}

From source file:com.google.vertcoin.examples.ExamplePaymentChannelClient.java

private void waitForSufficientBalance(BigInteger amount) {
    // Not enough money in the wallet.
    BigInteger amountPlusFee = amount.add(Wallet.SendRequest.DEFAULT_FEE_PER_KB);
    // ESTIMATED because we don't really need to wait for confirmation.
    ListenableFuture<BigInteger> balanceFuture = appKit.wallet().getBalanceFuture(amountPlusFee,
            Wallet.BalanceType.ESTIMATED);
    if (!balanceFuture.isDone()) {
        System.out.println("Please send " + Utils.bitcoinValueToFriendlyString(amountPlusFee) + " BTC to "
                + myKey.toAddress(params));
        Futures.getUnchecked(balanceFuture);
    }//from ww w  .j  a va 2  s .  c o m
}

From source file:com.google.logicoin.examples.ExamplePaymentChannelClient.java

private void waitForSufficientBalance(BigInteger amount) {
    // Not enough money in the wallet.
    BigInteger amountPlusFee = amount.add(Wallet.SendRequest.DEFAULT_FEE_PER_KB);
    // ESTIMATED because we don't really need to wait for confirmation.
    ListenableFuture<BigInteger> balanceFuture = appKit.wallet().getBalanceFuture(amountPlusFee,
            Wallet.BalanceType.ESTIMATED);
    if (!balanceFuture.isDone()) {
        System.out.println("Please send " + Utils.logicoinValueToFriendlyString(amountPlusFee) + " BTC to "
                + myKey.toAddress(params));
        Futures.getUnchecked(balanceFuture);
    }/* ww w.  ja v  a2s. c  o  m*/
}

From source file:com.google.worldcoin.examples.ExamplePaymentChannelClient.java

private void waitForSufficientBalance(BigInteger amount) {
    // Not enough money in the wallet.
    BigInteger amountPlusFee = amount.add(Wallet.SendRequest.DEFAULT_FEE_PER_KB);
    // ESTIMATED because we don't really need to wait for confirmation.
    ListenableFuture<BigInteger> balanceFuture = appKit.wallet().getBalanceFuture(amountPlusFee,
            Wallet.BalanceType.ESTIMATED);
    if (!balanceFuture.isDone()) {
        System.out.println("Please send " + Utils.worldcoinValueToFriendlyString(amountPlusFee) + " BTC to "
                + myKey.toAddress(params));
        Futures.getUnchecked(balanceFuture);
    }/* w  ww . j  av  a2s  .  com*/
}

From source file:com.woollysammoth.nubitj.examples.ExamplePaymentChannelClient.java

private void waitForSufficientBalance(BigInteger amount) {
    // Not enough money in the wallet.
    BigInteger amountPlusFee = amount.add(Wallet.SendRequest.DEFAULT_FEE_PER_KB);
    // ESTIMATED because we don't really need to wait for confirmation.
    ListenableFuture<BigInteger> balanceFuture = appKit.wallet().getBalanceFuture(amountPlusFee,
            Wallet.BalanceType.ESTIMATED);
    if (!balanceFuture.isDone()) {
        System.out.println("Please send " + Utils.nubitValueToFriendlyString(amountPlusFee) + " BTC to "
                + myKey.toAddress(params));
        Futures.getUnchecked(balanceFuture);
    }//from  w  w  w  .  j  a v  a 2s  .c  o m
}

From source file:com.continuuity.loom.common.zookeeper.lib.SynchronizedZKMap.java

private void reloadCacheIfNeeded() {
    NodeChildren nodeChildren = Futures.getUnchecked(ZKClientExt.getChildrenOrNull(zkClient, ENTRIES_PATH));
    if (nodeChildren == null) {
        if (currentView.size() > 0) {
            currentView = Collections.emptyMap();
        }//  w  ww  . j a  va2s . c  o  m

        return;
    }

    // we use children version to detect if we need to update local view
    int trueVersion = nodeChildren.getStat().getCversion();

    if (currentViewVersion == trueVersion) {
        return;
    }

    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);
    }

    Futures.getUnchecked(Futures.successfulAsList(dataFutures));

    ImmutableMap.Builder<String, T> builder = ImmutableMap.builder();
    for (Entry<String, ListenableFuture<NodeData>> nodeAndData : nodeAndDataFutures.entrySet()) {
        T value = serializer.deserialize(Futures.getUnchecked(nodeAndData.getValue()).getData());
        builder.put(nodeAndData.getKey(), value);
    }

    currentView = builder.build();
    currentViewVersion = trueVersion;
}

From source file:org.apache.aurora.scheduler.mesos.VersionedSchedulerDriverService.java

@Override
public void reconcileTasks(Collection<TaskStatus> statuses) {
    whenRegistered(() -> {/* w  w  w  .  j  a v a2  s. c  o m*/
        Collection<Call.Reconcile.Task> tasks = Collections2.transform(statuses,
                taskStatus -> Call.Reconcile.Task.newBuilder().setTaskId(taskStatus.getTaskId()).build());

        Futures.getUnchecked(mesosFuture)
                .send(Call.newBuilder().setType(Call.Type.RECONCILE).setFrameworkId(getFrameworkId())
                        .setReconcile(Call.Reconcile.newBuilder().addAllTasks(tasks)).build());
    });
}

From source file:org.apache.aurora.scheduler.app.local.FakeMaster.java

@Override
public Status killTask(TaskID taskId) {
    assertNotStopped();/*from  ww  w.  ja v  a 2 s  .co m*/

    Task task = activeTasks.remove(taskId);
    checkState(task != null, "Task " + taskId + " not found.");
    idleOffers.put(task.getOffer().getId(), task.getOffer());

    Futures.getUnchecked(schedulerFuture).statusUpdate(this,
            TaskStatus.newBuilder().setTaskId(taskId).setState(TaskState.TASK_FINISHED).build());

    return Status.DRIVER_RUNNING;
}

From source file:com.facebook.buck.core.graph.transformation.DefaultAsyncTransformationEngine.java

@Override
public final ComputeResult computeUnchecked(ComputeKey key) {
    return Futures.getUnchecked(compute(key));
}