Example usage for com.google.common.util.concurrent Uninterruptibles getUninterruptibly

List of usage examples for com.google.common.util.concurrent Uninterruptibles getUninterruptibly

Introduction

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

Prototype

public static <V> V getUninterruptibly(Future<V> future) throws ExecutionException 

Source Link

Usage

From source file:info.archinnov.achilles.internals.query.dsl.select.AbstractSelectWhere.java

public TypedMap getTypedMap() {
    try {/*from   ww  w  .  j  a  v  a  2s .c o m*/
        return Uninterruptibles.getUninterruptibly(getTypedMapAsync());
    } catch (ExecutionException e) {
        throw extractCauseFromExecutionException(e);
    }
}

From source file:com.palantir.giraffe.command.Commands.java

/**
 * Waits for the command associated with a {@code CommandFuture} to
 * terminate./*from www . ja v a2 s. co  m*/
 * <p>
 * This method is uninterruptible; to allow interruption, use
 * {@link CommandFuture#get()}.
 *
 * @param future the {@link CommandFuture} to block on
 *
 * @return the {@linkplain CommandResult result} of executing the command
 *
 * @throws CommandException if the command fails by throwing a
 *         {@code CommandException}
 * @throws IOException if an I/O error occurs while executing the command or
 *         the command fails for any other reason.
 */
public static CommandResult waitFor(CommandFuture future) throws IOException {
    checkNotNull(future);
    try {
        return Uninterruptibles.getUninterruptibly(future);
    } catch (ExecutionException e) {
        throw propagateCause(e);
    }
}

From source file:com.datastax.driver.core.ResultSet.java

private void fetchMoreResultsBlocking() {
    try {/*  w  w w .  j  a  v a  2s  .  com*/
        Uninterruptibles.getUninterruptibly(fetchMoreResults());
    } catch (ExecutionException e) {
        throw ResultSetFuture.extractCauseFromExecutionException(e);
    }
}

From source file:info.archinnov.achilles.internals.query.raw.NativeQuery.java

/**
 * Execute the native query and return a list of {@link info.archinnov.achilles.type.TypedMap}
 * with execution info//from   w  w w  . j  av a 2 s .  com
 *
 * @return Tuple2&lt;List&lt;TypedMap&gt;, ExecutionInfo&gt;
 */
public Tuple2<List<TypedMap>, ExecutionInfo> getListWithStats() {
    try {
        return Uninterruptibles.getUninterruptibly(getListAsyncWithStats());
    } catch (ExecutionException e) {
        throw extractCauseFromExecutionException(e);
    }
}

From source file:org.bitcoinj_extra.examples.ExamplePaymentChannelClient.java

private void openAndSend(int timeoutSecs, InetSocketAddress server, String channelID, final int times,
        PaymentChannelClient.VersionSelector versionSelector)
        throws IOException, ValueOutOfRangeException, InterruptedException {
    // Use protocol version 1 for simplicity
    PaymentChannelClientConnection client = new PaymentChannelClientConnection(server, timeoutSecs,
            appKit.wallet(), myKey, channelSize, channelID, versionSelector);
    // Opening the channel requires talking to the server, so it's asynchronous.
    final CountDownLatch latch = new CountDownLatch(1);
    Futures.addCallback(client.getChannelOpenFuture(), new FutureCallback<PaymentChannelClientConnection>() {
        @Override/*from w  w  w  .  j a va2s  .  c  om*/
        public void onSuccess(PaymentChannelClientConnection client) {
            // By the time we get here, if the channel is new then we already made a micropayment! The reason is,
            // we are not allowed to have payment channels that pay nothing at all.
            log.info("Success! Trying to make {} micropayments. Already paid {} satoshis on this channel",
                    times, client.state().getValueSpent());
            final Coin MICROPAYMENT_SIZE = CENT.divide(10);
            for (int i = 0; i < times; i++) {
                try {
                    // Wait because the act of making a micropayment is async, and we're not allowed to overlap.
                    // This callback is running on the user thread (see the last lines in openAndSend) so it's safe
                    // for us to block here: if we didn't select the right thread, we'd end up blocking the payment
                    // channels thread and would deadlock.
                    Uninterruptibles.getUninterruptibly(client.incrementPayment(MICROPAYMENT_SIZE));
                } catch (ValueOutOfRangeException e) {
                    log.error("Failed to increment payment by a CENT, remaining value is {}",
                            client.state().getValueRefunded());
                    throw new RuntimeException(e);
                } catch (ExecutionException e) {
                    log.error("Failed to increment payment", e);
                    throw new RuntimeException(e);
                }
                log.info("Successfully sent payment of one CENT, total remaining on channel is now {}",
                        client.state().getValueRefunded());
            }
            if (client.state().getValueRefunded().compareTo(MICROPAYMENT_SIZE) < 0) {
                // Now tell the server we're done so they should broadcast the final transaction and refund us what's
                // left. If we never do this then eventually the server will time out and do it anyway and if the
                // server goes away for longer, then eventually WE will time out and the refund tx will get broadcast
                // by ourselves.
                log.info("Settling channel for good");
                client.settle();
            } else {
                // Just unplug from the server but leave the channel open so it can resume later.
                client.disconnectWithoutSettlement();
            }
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable throwable) {
            log.error("Failed to open connection", throwable);
            latch.countDown();
        }
    }, Threading.USER_THREAD);
    latch.await();
}

From source file:com.google.caliper.runner.worker.Worker.java

private void startSocketStream() {
    try {/*  w  w  w.ja  va 2s  .c  om*/
        OpenedSocket openedSocket = Uninterruptibles.getUninterruptibly(socketFuture);
        logger.fine("successfully opened the pipe from the worker");
        socketWriter = openedSocket.writer();
        runningReadStreams.incrementAndGet();
        openStreams.incrementAndGet();
        @SuppressWarnings("unused") // go/futurereturn-lsc
        Future<?> possiblyIgnoredError = streamExecutor
                .submit(threadRenaming("worker-socket", new SocketStreamReader(openedSocket.reader())));
    } catch (ExecutionException e) {
        notifyFailed(e.getCause());
    }
}

From source file:org.bitcoinj.examples.ExamplePaymentChannelClient.java

private void openAndSend(int timeoutSecs, InetSocketAddress server, String channelID, final int times,
        IPaymentChannelClient.ClientChannelProperties clientChannelProperties)
        throws IOException, ValueOutOfRangeException, InterruptedException {
    // Use protocol version 1 for simplicity
    PaymentChannelClientConnection client = new PaymentChannelClientConnection(server, timeoutSecs,
            appKit.wallet(), myKey, channelSize, channelID, null, clientChannelProperties);
    // Opening the channel requires talking to the server, so it's asynchronous.
    final CountDownLatch latch = new CountDownLatch(1);
    Futures.addCallback(client.getChannelOpenFuture(), new FutureCallback<PaymentChannelClientConnection>() {
        @Override//from ww w .  j  av  a  2s  .c  om
        public void onSuccess(PaymentChannelClientConnection client) {
            // By the time we get here, if the channel is new then we already made a micropayment! The reason is,
            // we are not allowed to have payment channels that pay nothing at all.
            log.info("Success! Trying to make {} micropayments. Already paid {} satoshis on this channel",
                    times, client.state().getValueSpent());
            final Coin MICROPAYMENT_SIZE = CENT.divide(10);
            for (int i = 0; i < times; i++) {
                try {
                    // Wait because the act of making a micropayment is async, and we're not allowed to overlap.
                    // This callback is running on the user thread (see the last lines in openAndSend) so it's safe
                    // for us to block here: if we didn't select the right thread, we'd end up blocking the payment
                    // channels thread and would deadlock.
                    Uninterruptibles.getUninterruptibly(client.incrementPayment(MICROPAYMENT_SIZE));
                } catch (ValueOutOfRangeException e) {
                    log.error("Failed to increment payment by a CENT, remaining value is {}",
                            client.state().getValueRefunded());
                    throw new RuntimeException(e);
                } catch (ExecutionException e) {
                    log.error("Failed to increment payment", e);
                    throw new RuntimeException(e);
                }
                log.info("Successfully sent payment of one CENT, total remaining on channel is now {}",
                        client.state().getValueRefunded());
            }
            if (client.state().getValueRefunded().compareTo(MICROPAYMENT_SIZE) < 0) {
                // Now tell the server we're done so they should broadcast the final transaction and refund us what's
                // left. If we never do this then eventually the server will time out and do it anyway and if the
                // server goes away for longer, then eventually WE will time out and the refund tx will get broadcast
                // by ourselves.
                log.info("Settling channel for good");
                client.settle();
            } else {
                // Just unplug from the server but leave the channel open so it can resume later.
                client.disconnectWithoutSettlement();
            }
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable throwable) {
            log.error("Failed to open connection", throwable);
            latch.countDown();
        }
    }, Threading.USER_THREAD);
    latch.await();
}

From source file:info.archinnov.achilles.internals.query.raw.NativeQuery.java

/**
 * Execute the native query and return a list of {@link info.archinnov.achilles.type.TypedMap}
 *
 * @return List&lt;TypedMap&gt;//ww w. j av a  2s  .  c o  m
 */
public List<TypedMap> getList() {
    try {
        return Uninterruptibles.getUninterruptibly(getListAsync());
    } catch (ExecutionException e) {
        throw extractCauseFromExecutionException(e);
    }
}

From source file:com.datastax.driver.mapping.Mapper.java

/**
 * Creates a query that can be used to save the provided entity.
 * <p/>/* ww  w .  j  av a2s  .  c  o  m*/
 * This method is useful if you want to setup a number of options (tracing,
 * conistency level, ...) of the returned statement before executing it manually
 * or need access to the {@code ResultSet} object after execution (to get the
 * trace, the execution info, ...), but in other cases, calling {@link #save}
 * or {@link #saveAsync} is shorter.
 * This method allows you to provide a suite of {@link Option} to include in
 * the SAVE query. Options currently supported for SAVE are :
 * <ul>
 * <li>Timestamp</li>
 * <li>Time-to-live (ttl)</li>
 * <li>Consistency level</li>
 * <li>Tracing</li>
 * </ul>
 *
 * @param entity the entity to save.
 * @return a query that saves {@code entity} (based on it's defined mapping).
 */
public Statement saveQuery(T entity, Option... options) {
    try {
        return Uninterruptibles.getUninterruptibly(
                saveQueryAsync(entity, toMapWithDefaults(options, this.defaultSaveOptions)));
    } catch (ExecutionException e) {
        throw DriverThrowables.propagateCause(e);
    }
}

From source file:com.spotify.hdfs2cass.cassandra.thrift.CrunchBulkRecordWriter.java

private void close() throws IOException {
    logger.info("Closing bulk record writer");
    ProgressHeartbeat heartbeat = new ProgressHeartbeat(context, 120);
    heartbeat.startHeartbeat();// w  w  w .java2  s . c o m
    try {
        if (writer != null) {
            writer.close();
            Future<StreamState> future = loader.stream(Collections.<InetAddress>emptySet(),
                    new ProgressIndicator());
            try {
                Uninterruptibles.getUninterruptibly(future);
            } catch (ExecutionException e) {
                throw new RuntimeException(
                        "Streaming to the following hosts failed: " + loader.getFailedHosts(), e);
            }
        }
    } finally {
        heartbeat.stopHeartbeat();
    }
    logger.info("Succesfully closed bulk record writer");
}