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.dsl.action.SelectAction.java

/**
 * Execute the SELECT action/*from  w  w  w . j  a va  2  s.  co  m*/
 * and return the first entity instance with {@link com.datastax.driver.core.ExecutionInfo}
 */
default Tuple2<ENTITY, ExecutionInfo> getOneWithStats() {
    try {
        return Uninterruptibles.getUninterruptibly(getOneAsyncWithStats());
    } catch (ExecutionException e) {
        throw extractCauseFromExecutionException(e);
    }
}

From source file:info.archinnov.achilles.internals.dsl.action.SelectJSONAction.java

/**
 * Execute the SELECT JSON * action/* w w  w. j av a 2  s. com*/
 * and return the first row as JSON with {@link com.datastax.driver.core.ExecutionInfo}
 */
default Tuple2<String, ExecutionInfo> getJSONWithStats() {
    try {
        return Uninterruptibles.getUninterruptibly(getJSONAsyncWithStats());
    } catch (ExecutionException e) {
        throw extractCauseFromExecutionException(e);
    }
}

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

/**
 * {@inheritDoc}/*from  w ww  .j av  a 2 s.c  o m*/
 */
@Override
public PreparedStatement prepare(RegularStatement statement) {
    try {
        return Uninterruptibles.getUninterruptibly(prepareAsync(statement));
    } catch (ExecutionException e) {
        throw DefaultResultSetFuture.extractCauseFromExecutionException(e);
    }
}

From source file:org.sonar.server.es.BaseIndexer.java

public void index(final IndexerTask task) {
    final long requestedAt = system2.now();
    Future submit = executor.submit(() -> {
        if (lastUpdatedAt == -1L) {
            lastUpdatedAt = esClient.getMaxFieldValue(indexType, dateFieldName);
        }/*from   ww  w. j  a v  a 2  s  .c o  m*/
        if (requestedAt > lastUpdatedAt) {
            long l = task.index(lastUpdatedAt);
            // l can be 0 if no documents were indexed
            lastUpdatedAt = Math.max(l, lastUpdatedAt);
        }
    });
    try {
        Uninterruptibles.getUninterruptibly(submit);
    } catch (ExecutionException e) {
        Throwables.propagate(e);
    }
}

From source file:org.kiji.maven.plugins.ShellExecUtil.java

/**
 * Execute a shell command, uninterruptibly wait for completion, and return the stdout.
 *
 * Note: The usual solution to execute shell commands from the JVM is as follows:
 * <code>//  w ww. jav  a  2 s .c  om
 * Process process = Runtime.getRuntime().exec(command);
 * process.waitFor(); // Wait for stdout from the program.
 * </code>
 *
 * However, Maven interrupts all process waits/sleeps/etc. in [[LifecyclePhase
 * .POST_INTEGRATION_TEST]]. The rationale for this is probably that Maven builds should not be
 * blocked during cleanup phases. In order to avoid this interference when running commands
 * against the bento script, we uninterruptibly wait for a process completion.
 *
 * @param command to execute.
 * @return stdout.
 * @throws IOException if the command execution encounters and I/O failure.
 * @throws ExecutionException if process future can be uninterruptibly acquired.
 */
public static ShellResult executeCommand(final String command) throws IOException, ExecutionException {
    final ExecutorService executor = Executors.newFixedThreadPool(2);

    final Process commandProcess;
    try {
        commandProcess = Runtime.getRuntime().exec(command);
    } catch (final IOException ioe) {
        throw new IOException(String.format("Failed to exec: %s", command), ioe);
    }

    final InputStreamReaderCallable stdoutCallable = new InputStreamReaderCallable(
            commandProcess.getInputStream());
    final InputStreamReaderCallable stderrCallable = new InputStreamReaderCallable(
            commandProcess.getErrorStream());
    final Future<String> stdoutFuture = executor.submit(stdoutCallable);
    final Future<String> stderrFuture = executor.submit(stderrCallable);

    // This code has been copied/adapted from Uninterruptibles#getUninterruptibly.
    boolean interrupted = false;
    int exitCode;
    try {
        while (true) {
            try {
                exitCode = commandProcess.waitFor();

                return new ShellResult(Uninterruptibles.getUninterruptibly(stderrFuture),
                        Uninterruptibles.getUninterruptibly(stdoutFuture), exitCode);
            } catch (final InterruptedException ise) {
                interrupted = true;
            }
        }
    } finally {
        if (interrupted) {
            Thread.currentThread().interrupt();
        }
    }
}

From source file:com.facebook.swift.service.async.AsyncClient.java

@Test
public void testAsyncClient() throws Exception {
    ListenableFuture<String> getBeforeFuture;
    ListenableFuture<String> getAfterFuture;
    ListenableFuture<Void> putFuture;

    try (DelayedMap.AsyncClient client = createClient(DelayedMap.AsyncClient.class, syncServer).get()) {
        getBeforeFuture = client.getValueSlowly(200, TimeUnit.MILLISECONDS, "testKey");
        putFuture = client.putValueSlowly(400, TimeUnit.MILLISECONDS, "testKey", "testValue");
        getAfterFuture = client.getValueSlowly(600, TimeUnit.MILLISECONDS, "testKey");

        assertEquals(Uninterruptibles.getUninterruptibly(getBeforeFuture), "default");
        assertEquals(Uninterruptibles.getUninterruptibly(getAfterFuture), "testValue");
        Uninterruptibles.getUninterruptibly(putFuture);
    }/*from w w w .  j a v  a 2  s.c om*/
}

From source file:info.archinnov.achilles.internals.query.crud.FindWithOptions.java

public ENTITY get() {
    try {//w  w  w  . j ava  2 s . c  o  m
        return Uninterruptibles.getUninterruptibly(getAsync());
    } catch (ExecutionException e) {
        throw extractCauseFromExecutionException(e);
    }
}

From source file:google.registry.util.Concurrent.java

/**
 * Processes {@code items} in parallel using {@code funk}, with the specified number of threads.
 *
 * <p><b>Note:</b> Spawned threads will inherit the same namespace.
 *
 * @throws UncheckedExecutionException to wrap the exception thrown by {@code funk}. This will
 *     only contain the exception information for the first exception thrown.
 * @return transformed {@code items} in the same order.
 */// ww w.j  a  va2  s.  co m
public static <A, B> ImmutableList<B> transform(Collection<A> items, int threadCount,
        final Function<A, B> funk) {
    checkNotNull(funk);
    checkNotNull(items);
    ThreadFactory threadFactory = currentRequestThreadFactory();
    if (threadFactory == null) {
        // Fall back to non-concurrent transform if we can't get an App Engine thread factory (most
        // likely caused by hitting this code from a command-line tool). Default Java system threads
        // are not compatible with code that needs to interact with App Engine (such as Objectify),
        // which we often have in funk when calling Concurrent.transform().
        // For more info see: http://stackoverflow.com/questions/15976406
        return FluentIterable.from(items).transform(funk).toList();
    }
    ExecutorService executor = newFixedThreadPool(threadCount, threadFactory);
    try {
        List<Future<B>> futures = new ArrayList<>();
        for (final A item : items) {
            futures.add(executor.submit(new Callable<B>() {
                @Override
                public B call() {
                    return funk.apply(item);
                }
            }));
        }
        ImmutableList.Builder<B> results = new ImmutableList.Builder<>();
        for (Future<B> future : futures) {
            try {
                results.add(Uninterruptibles.getUninterruptibly(future));
            } catch (ExecutionException e) {
                throw new UncheckedExecutionException(e.getCause());
            }
        }
        return results.build();
    } finally {
        executor.shutdownNow();
    }
}

From source file:org.dcache.util.NettyPortRange.java

/**
 * Binds <code>server</socket> to <code>address</code>. A port is
 * chosen from this port range. If the port range is [0,0], then a
 * free port is chosen by the OS.//  ww  w  . ja  v a  2  s .  c  om
 *
 * @throws IOException if the bind operation fails.
 */
public Channel bind(ServerBootstrap server, InetAddress address) throws IOException {
    int start = random();
    int port = start;
    do {
        try {
            ChannelFuture future = server.bind(new InetSocketAddress(address, port));
            Uninterruptibles.getUninterruptibly(future);
            return future.channel();
        } catch (ExecutionException e) {
            if (!(e.getCause() instanceof BindException)) {
                Throwables.throwIfInstanceOf(e.getCause(), IOException.class);
                Throwables.throwIfUnchecked(e.getCause());
                throw new RuntimeException(e.getCause());
            }
        }
        port = succ(port);
    } while (port != start);

    throw new BindException("No free port within range");
}

From source file:info.archinnov.achilles.internals.dsl.TypedMapAware.java

/**
 * Execute the SELECT action and return a {@link info.archinnov.achilles.type.tuples.Tuple2}&lt;
 * {@link java.util.List}&lt;{@link info.archinnov.achilles.type.TypedMap}&gt;, {@link com.datastax.driver.core.ExecutionInfo}&gt;
 * <br/>//from w w w  . j av  a 2 s  .  c  o m
 */
default Tuple2<List<TypedMap>, ExecutionInfo> getTypedMapsWithStats() {
    try {
        return Uninterruptibles.getUninterruptibly(getTypedMapsAsyncWithStats());
    } catch (ExecutionException e) {
        throw extractCauseFromExecutionException(e);
    }
}