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

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

Introduction

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

Prototype

@Override
    public V get() throws InterruptedException, ExecutionException 

Source Link

Usage

From source file:io.geobit.chain.dispatchers.AddressTransactionsDispatcher.java

public AddressTransactions getAddressUnspents(String address, int cont) {
    if (cont > 5)
        return null;
    AddressTransactions valCache = cache.getIfPresent("u/" + address);
    AddressUnspentsProvider aup1 = addUnsProviders.take();
    AddressUnspentsProvider aup2 = addUnsProviders.takeDifferent(aup1);
    log("aup1=" + aup1 + " aup2=" + aup2);
    Callable<AddressTransactions> runner1 = new AddressUnspentsRunnable(aup1, address);
    Callable<AddressTransactions> runner2 = new AddressUnspentsRunnable(aup2, address);
    final Long start = System.currentTimeMillis();
    ListenableFuture<AddressTransactions> listenableFuture1 = moreExecutor.submit(runner1);
    ListenableFuture<AddressTransactions> listenableFuture2 = moreExecutor.submit(runner2);
    SettableFuture<AddressTransactions> returned = SettableFuture.create();
    Futures.addCallback(listenableFuture1,
            new AddressUnspentsFutureCallback(start, aup1, returned, addUnsProviders));
    Futures.addCallback(listenableFuture2,
            new AddressUnspentsFutureCallback(start, aup2, returned, addUnsProviders));
    Runnable checker = new AddressUnspentsCheckRunnable(address, listenableFuture1, aup1, listenableFuture2,
            aup2, addUnsProviders, cache);
    moreExecutor.execute(checker);/*from   ww w.  j  ava  2  s. co m*/
    try {
        AddressTransactions valRet = returned.get();
        if (valCache != null && valCache.equals(valRet))
            return valRet;

        AddressTransactions first = listenableFuture1.get();
        AddressTransactions second = listenableFuture2.get();
        if (first != null && first.equals(second)) {
            cache.put("u/" + address, first);
            return first;
        }
    } catch (Exception e) {
    }
    return getAddressUnspents(address, cont + 1);
}

From source file:co.cask.cdap.internal.app.runtime.workflow.AbstractProgramWorkflowRunner.java

/**
 * Adds a listener to the {@link ProgramController} and blocks for completion.
 *
 * @param controller the {@link ProgramController} for the program
 * @param context    the {@link RuntimeContext}
 * @return {@link RuntimeContext} of the completed program
 * @throws Exception if the execution failed
 *//*from  w  w  w. j a va2 s  .  c  om*/
protected RuntimeContext executeProgram(final ProgramController controller, final RuntimeContext context)
        throws Exception {
    // Execute the program.
    final SettableFuture<RuntimeContext> completion = SettableFuture.create();
    controller.addListener(new AbstractListener() {
        @Override
        public void completed() {
            completion.set(context);
        }

        @Override
        public void killed() {
            completion.set(context);
        }

        @Override
        public void error(Throwable cause) {
            completion.setException(cause);
        }
    }, Threads.SAME_THREAD_EXECUTOR);

    // Block for completion.
    try {
        return completion.get();
    } catch (ExecutionException e) {
        Throwable cause = e.getCause();
        if (cause instanceof Exception) {
            throw (Exception) cause;
        }
        throw Throwables.propagate(cause);
    } catch (InterruptedException e) {
        try {
            Futures.getUnchecked(controller.stop());
        } catch (Throwable t) {
            // no-op
        }
        // reset the interrupt
        Thread.currentThread().interrupt();
        return null;
    }
}

From source file:io.geobit.chain.dispatchers.AddressTransactionsDispatcher.java

private AddressTransactions getAddressTransactions(String address, int cont) {
    if (cont > 5)
        return null;
    AddressTransactions valCache = cache.getIfPresent("a/" + address);
    AddressTransactionsProvider atp1 = addTxsProviders.take();
    AddressTransactionsProvider atp2 = addTxsProviders.takeDifferent(atp1);
    log("atp1=" + atp1 + " atp2=" + atp2);
    Callable<AddressTransactions> runner1 = new AddressTransactionsRunnable(atp1, address);
    Callable<AddressTransactions> runner2 = new AddressTransactionsRunnable(atp2, address);
    final Long start = System.currentTimeMillis();
    ListenableFuture<AddressTransactions> listenableFuture1 = moreExecutor.submit(runner1);
    ListenableFuture<AddressTransactions> listenableFuture2 = moreExecutor.submit(runner2);
    SettableFuture<AddressTransactions> returned = SettableFuture.create();
    Futures.addCallback(listenableFuture1,
            new AddressTransactionsFutureCallback(start, atp1, returned, addTxsProviders));
    Futures.addCallback(listenableFuture2,
            new AddressTransactionsFutureCallback(start, atp2, returned, addTxsProviders));
    Runnable checker = new AddressTransactionsCheckRunnable(address, listenableFuture1, atp1, listenableFuture2,
            atp2, addTxsProviders, cache);
    moreExecutor.execute(checker);//from   w  w w.  jav  a  2s.  co m
    try {
        AddressTransactions valRet = returned.get();
        if (valCache != null && valCache.equals(valRet))
            return valRet;

        AddressTransactions first = listenableFuture1.get();
        AddressTransactions second = listenableFuture2.get();
        if (first != null && first.equals(second)) {
            cache.put("a/" + address, first);
            return first;
        }
    } catch (Exception e) {
    }
    return getAddressTransactions(address, cont + 1);
}

From source file:org.pentaho.di.core.KettleEnvironment.java

public static void init(List<PluginTypeInterface> pluginClasses, boolean simpleJndi) throws KettleException {
    SettableFuture<Boolean> ready;
    if (initialized.compareAndSet(null, ready = SettableFuture.create())) {

        try {/*  www .j a v a 2s .  c om*/
            // This creates .kettle and kettle.properties...
            //
            if (!KettleClientEnvironment.isInitialized()) {
                KettleClientEnvironment.init();
            }

            // Configure Simple JNDI when we run in stand-alone mode (spoon, pan, kitchen, carte, ... NOT on the platform
            //
            if (simpleJndi) {
                JndiUtil.initJNDI();
            }

            // Register the native types and the plugins for the various plugin types...
            //
            pluginClasses.forEach(PluginRegistry::addPluginType);
            PluginRegistry.init();

            // Also read the list of variables.
            //
            KettleVariablesList.init();

            // Initialize the Lifecycle Listeners
            //
            initLifecycleListeners();
            ready.set(true);
        } catch (Throwable t) {
            ready.setException(t);
            // If it's a KettleException, throw it, otherwise wrap it in a KettleException
            throw ((t instanceof KettleException) ? (KettleException) t : new KettleException(t));
        }

    } else {
        // A different thread is initializing
        ready = initialized.get();
        // Block until environment is initialized
        try {
            ready.get();
        } catch (Throwable t) {
            // If it's a KettleException, throw it, otherwise wrap it in a KettleException
            throw ((t instanceof KettleException) ? (KettleException) t : new KettleException(t));
        }
    }
}

From source file:io.geobit.chain.dispatchers.BalanceAndReceivedDispatcher.java

public Long getReceived(String address, int cont) {
    if (cont > 5)
        return null;
    Long valCache = recentCache.getIfPresent("r/" + address);
    if (valCache != null)
        return valCache;
    valCache = cache.getIfPresent("r/" + address);
    ReceivedProvider rec1 = receivedProviders.take();
    ReceivedProvider rec2 = receivedProviders.takeDifferent(rec1);
    log("rec1=" + rec1 + " rec2=" + rec2);

    Callable<Long> runner1 = new ReceivedRunnable(rec1, address);
    Callable<Long> runner2 = new ReceivedRunnable(rec2, address);
    final Long start = System.currentTimeMillis();
    ListenableFuture<Long> listenableFuture1 = moreExecutor.submit(runner1);
    ListenableFuture<Long> listenableFuture2 = moreExecutor.submit(runner2);
    SettableFuture<Long> returned = SettableFuture.create();
    Futures.addCallback(listenableFuture1,
            new ReceivedFutureCallback(start, rec1, returned, receivedProviders));
    Futures.addCallback(listenableFuture2,
            new ReceivedFutureCallback(start, rec2, returned, receivedProviders));
    Runnable checker = new ReceivedCheckRunnable(address, listenableFuture1, rec1, listenableFuture2, rec2,
            receivedProviders, cache);/*www .j  a v  a  2  s.  c  om*/
    moreExecutor.execute(checker);

    Long valRet;
    try {
        valRet = returned.get(); /* return the faster */
        if (valCache != null && valCache.equals(valRet)) {
            recentCache.put("r/" + address, valRet);
            return valRet;
        }

        Long first = listenableFuture1.get();
        Long second = listenableFuture2.get();
        if (first != null && first.equals(second)) {
            cache.put("r/" + address, first);
            recentCache.put("r/" + address, first);
            return first;
        }
        if (first != null)
            cache.put("r/" + address, first);
        else if (second != null)
            cache.put("r/" + address, second);

    } catch (Exception e) {
        error("BalanceAndReceivedDispatcher getReceived " + e.getMessage());
    }
    return getBalance(address, cont + 1);
}

From source file:co.cask.tigon.internal.app.runtime.distributed.AbstractProgramTwillRunnable.java

@Override
public void run() {
    LOG.info("Starting metrics service");
    Futures.getUnchecked(Services.chainStart(zkClientService, metricsCollectionService, resourceReporter));

    LOG.info("Starting runnable: {}", name);
    controller = injector.getInstance(getProgramClass()).run(program, programOpts);
    final SettableFuture<ProgramController.State> state = SettableFuture.create();
    controller.addListener(new AbstractListener() {
        @Override//from  w  w  w . j a  v  a 2s  .  c  o m
        public void stopped() {
            state.set(ProgramController.State.STOPPED);
        }

        @Override
        public void error(Throwable cause) {
            LOG.error("Program runner error out.", cause);
            state.setException(cause);
        }
    }, MoreExecutors.sameThreadExecutor());

    runlatch.countDown();
    try {
        state.get();
        LOG.info("Program stopped.");
    } catch (Throwable t) {
        LOG.error("Program terminated due to error.", t);
        throw Throwables.propagate(t);
    }
}

From source file:io.geobit.chain.dispatchers.BlockAndTransactionDispatcher.java

private Block getBlock(Integer height, int cont) {
    if (cont > 5)
        return null;
    Block valCache = blocksCache.get(height);
    if (valCache != null)
        return valCache; /* the block in confirmed cache is returned */

    BlockProvider blo1 = blockProviders.take();
    BlockProvider blo2 = blockProviders.takeDifferent(blo1);
    BlockProvider blo3 = blockProviders.takeDifferent(blo1, blo2);

    log("blo1=" + blo1 + " blo2=" + blo2 + " blo3=" + blo3);
    Callable<Block> runner1 = new BlockRunnable(blo1, height);
    Callable<Block> runner2 = new BlockRunnable(blo2, height);
    Callable<Block> runner3 = new BlockRunnable(blo3, height);
    final Long start = System.currentTimeMillis();
    ListenableFuture<Block> listenableFuture1 = moreExecutor.submit(runner1);
    ListenableFuture<Block> listenableFuture2 = moreExecutor.submit(runner2);
    ListenableFuture<Block> listenableFuture3 = moreExecutor.submit(runner3);
    SettableFuture<Block> first = SettableFuture.create();
    SettableFuture<Block> second = SettableFuture.create();

    Futures.addCallback(listenableFuture1, new BlockFutureCallback(start, blo1, first, second, blockProviders));
    Futures.addCallback(listenableFuture2, new BlockFutureCallback(start, blo2, first, second, blockProviders));
    Futures.addCallback(listenableFuture3, new BlockFutureCallback(start, blo3, first, second, blockProviders));
    Runnable checker = new BlockCheckRunnable(height, listenableFuture1, blo1, listenableFuture2, blo2,
            listenableFuture3, blo3, blockProviders, blocksCache);
    moreExecutor.execute(checker);/*  ww w  . j a v a 2  s  .  c  om*/
    try {

        Block firstBlock = first.get();
        Block secondBlock = second.get();
        if (firstBlock != null && firstBlock.equals(secondBlock)) {
            blocksCache.put(height, firstBlock);
            log(blocksCache.toString());
            return firstBlock;
        }
    } catch (Exception e) {
    }
    return getBlock(height, cont + 1);
}

From source file:com.amazonaws.services.kinesis.producer.KinesisProducer.java

/**
 * Get metrics from the KPL./* www .j  a v  a  2  s. c om*/
 * 
 * <p>
 * The KPL computes and buffers useful metrics. Use this method to retrieve
 * them. The same metrics are also uploaded to CloudWatch (unless disabled).
 * 
 * <p>
 * Multiple metrics exist for the same name, each with a different list of
 * dimensions (e.g. stream name). This method will fetch all metrics with
 * the provided name.
 * 
 * <p>
 * See the stand-alone metrics documentation for details about individual
 * metrics.
 * 
 * <p>
 * This method is synchronous and will block while the data is being
 * retrieved.
 * 
 * @param metricName
 *            Name of the metrics to fetch.
 * @param windowSeconds
 *            Fetch data from the last N seconds. The KPL maintains data at
 *            per second granularity for the past minute. To get total
 *            cumulative data since the start of the program, use the
 *            overloads that do not take this argument.
 * @return A list of metrics with the provided name.
 * @throws ExecutionException
 *             If an error occurred while fetching metrics from the child
 *             process.
 * @throws InterruptedException
 *             If the thread is interrupted while waiting for the response
 *             from the child process.
 * @see Metric
 */
public List<Metric> getMetrics(String metricName, int windowSeconds)
        throws InterruptedException, ExecutionException {
    MetricsRequest.Builder mrb = MetricsRequest.newBuilder();
    if (metricName != null) {
        mrb.setName(metricName);
    }
    if (windowSeconds > 0) {
        mrb.setSeconds(windowSeconds);
    }

    long id = messageNumber.getAndIncrement();
    SettableFuture<List<Metric>> f = SettableFuture.create();
    futures.put(id, f);

    child.add(Message.newBuilder().setId(id).setMetricsRequest(mrb.build()).build());

    return f.get();
}

From source file:io.geobit.chain.dispatchers.BlockAndTransactionDispatcher.java

public String getTransHex(String txHash, int cont) {
    if (cont > 5)
        return null;
    String valCache = transHexCache.getIfPresent(txHash);
    if (valCache != null)
        return valCache;

    TransHexProvider trh1 = transHexProviders.take();
    TransHexProvider trh2 = transHexProviders.takeDifferent(trh1);
    TransHexProvider trh3 = transHexProviders.takeDifferent(trh1, trh2);

    log("trh1=" + trh1 + " trh2=" + trh2 + " trh3=" + trh3);
    Callable<String> runner1 = new TransHexRunnable(trh1, txHash);
    Callable<String> runner2 = new TransHexRunnable(trh2, txHash);
    Callable<String> runner3 = new TransHexRunnable(trh3, txHash);
    final Long start = System.currentTimeMillis();
    ListenableFuture<String> listenableFuture1 = moreExecutor.submit(runner1);
    ListenableFuture<String> listenableFuture2 = moreExecutor.submit(runner2);
    ListenableFuture<String> listenableFuture3 = moreExecutor.submit(runner3);
    SettableFuture<String> first = SettableFuture.create();
    SettableFuture<String> second = SettableFuture.create();

    Futures.addCallback(listenableFuture1,
            new TransHexFutureCallback(start, trh1, first, second, transHexProviders));
    Futures.addCallback(listenableFuture2,
            new TransHexFutureCallback(start, trh2, first, second, transHexProviders));
    Futures.addCallback(listenableFuture3,
            new TransHexFutureCallback(start, trh3, first, second, transHexProviders));
    Runnable checker = new TransHexCheckRunnable(txHash, listenableFuture1, trh1, listenableFuture2, trh2,
            listenableFuture3, trh3, transHexProviders, transHexCache);
    moreExecutor.execute(checker);//from   ww w  .ja  v a 2s .  c om
    try {

        String firstTx = first.get();
        String secondTx = second.get();
        if (firstTx != null && firstTx.equals(secondTx)) {
            transHexCache.put(txHash, firstTx);
            log(txCache.toString());
            return firstTx;
        }
    } catch (Exception e) {
    }
    return getTransHex(txHash, cont + 1);
}

From source file:io.geobit.chain.dispatchers.BlockAndTransactionDispatcher.java

private Transaction getTransaction(String txHash, int cont) {
    if (cont > 5)
        return null;
    Transaction valCache = txCache.get(txHash);
    if (valCache != null)
        return valCache; /* the block in confirmed cache is returned */

    TransactionProvider tra1 = transactionProviders.take();
    TransactionProvider tra2 = transactionProviders.takeDifferent(tra1);
    TransactionProvider tra3 = transactionProviders.takeDifferent(tra1, tra2);

    log("tra1=" + tra1 + " tra2=" + tra2 + " tra3=" + tra3);
    Callable<Transaction> runner1 = new TransactionRunnable(tra1, txHash);
    Callable<Transaction> runner2 = new TransactionRunnable(tra2, txHash);
    Callable<Transaction> runner3 = new TransactionRunnable(tra3, txHash);
    final Long start = System.currentTimeMillis();
    ListenableFuture<Transaction> listenableFuture1 = moreExecutor.submit(runner1);
    ListenableFuture<Transaction> listenableFuture2 = moreExecutor.submit(runner2);
    ListenableFuture<Transaction> listenableFuture3 = moreExecutor.submit(runner3);
    SettableFuture<Transaction> first = SettableFuture.create();
    SettableFuture<Transaction> second = SettableFuture.create();

    Futures.addCallback(listenableFuture1,
            new TransactionFutureCallback(start, tra1, first, second, transactionProviders));
    Futures.addCallback(listenableFuture2,
            new TransactionFutureCallback(start, tra2, first, second, transactionProviders));
    Futures.addCallback(listenableFuture3,
            new TransactionFutureCallback(start, tra3, first, second, transactionProviders));
    Runnable checker = new TransactionCheckRunnable(txHash, listenableFuture1, tra1, listenableFuture2, tra2,
            listenableFuture3, tra3, transactionProviders, txCache);
    moreExecutor.execute(checker);//w w  w . j  a  v a2  s  . c  o  m
    try {

        Transaction firstTx = first.get();
        Transaction secondTx = second.get();
        if (firstTx != null && firstTx.equals(secondTx)) {
            txCache.put(txHash, firstTx);
            log(txCache.toString());
            return firstTx;
        }
    } catch (Exception e) {
    }
    return getTransaction(txHash, cont + 1);
}