Example usage for com.google.common.util.concurrent ListenableFuture get

List of usage examples for com.google.common.util.concurrent ListenableFuture get

Introduction

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

Prototype

V get() throws InterruptedException, ExecutionException;

Source Link

Document

Waits if necessary for the computation to complete, and then retrieves its result.

Usage

From source file:org.robotninjas.barge.rpc.netty.RpcChannelFactory.java

@Override
public void destroyObject(Object key, ListenableFuture<NettyRpcChannel> obj) throws Exception {
    if (obj.isDone() && !obj.isCancelled()) {
        obj.get().close();
    } else {/*from   w w w  .  j  av a 2  s . co m*/
        obj.cancel(false);
    }
}

From source file:org.apache.hadoop.examples.render.twill.RenderTwillMain.java

public void exec(List<String> argsList) throws ExecutionException, InterruptedException, IOException {
    RenderArgs params = new RenderArgs(argsList);
    params.validateForMain();/*w  w  w .ja v a 2 s .co  m*/

    String zkStr = params.zookeeper;

    String rmAddr = conf.get(YarnConfiguration.RM_ADDRESS);
    Preconditions.checkState(!rmAddr.startsWith("0.0.0.0"), "Resource manager not defined " + rmAddr);

    final TwillRunnerService twillRunner = new YarnTwillRunnerService(conf, zkStr, createLocationFactory());
    twillRunner.startAndWait();

    controller = null;

    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        if (controller != null) {
            controller.stopAndWait();
        }
        twillRunner.stopAndWait();
    }));

    controller = twillRunner.prepare(new StdoutRunnable())
            //          .addLogHandler(new Slf4JLogHandler(log))
            .addLogHandler(new PrinterLogHandler(new PrintWriter(System.out)))
            .withApplicationArguments(params.getArguments()).start();

    ListenableFuture<Service.State> future = Services.getCompletionFuture(controller);
    future.get();

}

From source file:com.github.nethad.clustermeister.integration.sc01.Scenario01.java

@Override
public void runScenario() throws Exception {
    logger.info("Run scenario.");

    Clustermeister clustermeister = ClustermeisterFactory.create();
    try {/*from   ww w  .  ja  va 2 s .  c  o  m*/
        logger.info("Start Clustermeister.");
        Collection<ExecutorNode> allNodes = clustermeister.getAllNodes();
        addToReport("node size", allNodes.size());
        //            logger.info("nodes size = {}", allNodes.size());
        //            Assertions.assertEquals(1, allNodes.size(), "Number of nodes not as expected");
        String expectedString = "it works!";

        for (ExecutorNode executorNode : allNodes) {
            ListenableFuture<String> resultFuture = executorNode
                    .execute(new ReturnStringCallable(expectedString));
            String result = resultFuture.get();
            addToReport("result " + executorNode.getID(), result);
        }
    } catch (ExecutionException ex) {
        addToReport("ExecutionException", ex.getMessage());
    } finally {
        clustermeister.shutdown();
    }
}

From source file:org.opendaylight.mdsal.dom.store.inmemory.ShardCanCommitCoordinationTask.java

void canCommitBlocking() throws TransactionCommitFailedException {
    for (final ListenableFuture<?> canCommit : canCommitAll()) {
        try {/*from   ww w .ja va2  s.  com*/
            final Boolean result = (Boolean) canCommit.get();
            if (result == null || !result) {
                throw new TransactionCommitFailedException("CanCommit failed, no detailed cause available.");
            }
        } catch (InterruptedException | ExecutionException e) {
            throw new TransactionCommitFailedException("CanCommit failed", e);
        }
    }
}

From source file:com.github.nethad.clustermeister.provisioning.torque.commands.RemoveNodeCommand.java

@Override
public void execute(CommandLineArguments arguments) {
    Collection<NodeInformation> allNodes = getRmiServerForApi().getAllNodes();
    LinkedList<String> nodeUuids = new LinkedList<String>();

    Scanner scanner = arguments.asScanner();

    while (scanner.hasNext()) {
        final String currentId = scanner.next();
        boolean validId = Iterables.any(allNodes, new Predicate<NodeInformation>() {
            @Override/*from w ww  .j  av  a  2 s  .co  m*/
            public boolean apply(NodeInformation input) {
                return input.getID().equalsIgnoreCase(currentId);
            }
        });
        if (validId) {
            nodeUuids.add(currentId);
        }
    }
    ListenableFuture<Void> removeNodesFuture = getNodeManager().removeNodes(nodeUuids);
    try {
        removeNodesFuture.get();
    } catch (InterruptedException ex) {
        throw new RuntimeException(ex);
    } catch (ExecutionException ex) {
        throw new RuntimeException(ex);
    }

}

From source file:com.google.cloud.pubsub.PublisherSamples.java

private void handleResults(List<ListenableFuture<String>> results) {
    List<String> messageIds = new ArrayList<>(results.size());
    Futures.whenAllComplete(results).call(new Callable<Void>() {
        @Override//from   www  .j  ava  2 s  . c  om
        public Void call() throws Exception {
            long endTime = System.currentTimeMillis();
            System.out.printf("Finished publishing messages at %d ms, elapsed %d ms\n", endTime,
                    endTime - startTimeMs);
            int okCount = 0;
            int failCount = 0;
            for (ListenableFuture<String> result : results) {
                try {
                    messageIds.add(result.get());
                    ++okCount;
                } catch (Exception e) {
                    e.printStackTrace();
                    ++failCount;
                }
            }
            System.out.println("Total messages published OK: " + okCount);
            System.out.println("Total messages failed: " + failCount);

            return null;
        }
    });
}

From source file:com.dangdang.ddframe.rdb.sharding.executor.ExecutorEngine.java

private <O> O getFutureResults(final ListenableFuture<O> futures) {
    try {/*from   w w  w  .  j av a2 s  . c om*/
        return futures.get();
    } catch (final InterruptedException | ExecutionException ex) {
        ExecutorExceptionHandler.handleException(ex);
        return null;
    }
}

From source file:com.proofpoint.concurrent.BenchmarkWhenAnyCompleteCancelOthers.java

@Benchmark
public void benchmark() throws Exception {
    Semaphore semaphore = new Semaphore(futureCount);

    ArrayList<SettableFuture<?>> futures = new ArrayList<>();
    for (int i = 0; i < futureCount; i++) {
        SettableFuture<?> future = SettableFuture.create();
        future.addListener(() -> semaphore.release(1), directExecutor());
        futures.add(future);//  ww w  .j a  v a 2s. com
    }
    ListenableFuture<?> anyComplete = whenAnyCompleteCancelOthers(futures);
    futures.get(futureCount / 2).set(null);
    semaphore.acquireUninterruptibly(futureCount);
    anyComplete.get();
}

From source file:org.apache.gobblin.hive.HiveRegisterStep.java

@Override
public void execute() throws IOException {

    if (this.verifyBeforeRegistering) {
        if (!this.hiveSpec.getTable().getLocation().isPresent()) {
            throw getException("Table does not have a location parameter.");
        }/*  w ww  . jav  a 2 s.  c  om*/
        Path tablePath = new Path(this.hiveSpec.getTable().getLocation().get());

        FileSystem fs = this.hiveSpec.getPath().getFileSystem(new Configuration());
        if (!fs.exists(tablePath)) {
            throw getException(String.format("Table location %s does not exist.", tablePath));
        }

        if (this.hiveSpec.getPartition().isPresent()) {

            if (!this.hiveSpec.getPartition().get().getLocation().isPresent()) {
                throw getException("Partition does not have a location parameter.");
            }
            Path partitionPath = new Path(this.hiveSpec.getPartition().get().getLocation().get());
            if (!fs.exists(this.hiveSpec.getPath())) {
                throw getException(String.format("Partition location %s does not exist.", partitionPath));
            }
        }
    }

    try (HiveRegister hiveRegister = HiveRegister.get(this.props, this.metastoreURI)) {
        log.info("Registering Hive Spec " + this.hiveSpec);
        ListenableFuture<Void> future = hiveRegister.register(this.hiveSpec);
        future.get();
    } catch (InterruptedException | ExecutionException ie) {
        throw new IOException("Hive registration was interrupted.", ie);
    }
}

From source file:zeitcoin.wallet.ui.MaybeMaintenanceFragment.java

private boolean maintenanceRecommended() {
    try {//  www  .  j  av  a 2  s. c o m
        final ListenableFuture<List<Transaction>> result = wallet.doMaintenance(null, false);
        return !result.get().isEmpty();
    } catch (final DeterministicUpgradeRequiresPassword x) {
        return true;
    } catch (final Exception x) {
        throw new RuntimeException(x);
    }
}