List of usage examples for com.google.common.util.concurrent Uninterruptibles getUninterruptibly
public static <V> V getUninterruptibly(Future<V> future) throws ExecutionException
From source file:com.google.cloud.pubsub.PubSubImpl.java
private static <V> V get(Future<V> future) { try {/*from w w w .ja va 2s . co m*/ return Uninterruptibles.getUninterruptibly(future); } catch (ExecutionException ex) { throw Throwables.propagate(ex.getCause()); } }
From source file:org.apache.cassandra.db.Mutation.java
public void apply(boolean durableWrites) { try {/* ww w . j a v a 2 s . co m*/ Uninterruptibles.getUninterruptibly(applyFuture(durableWrites)); } catch (ExecutionException e) { throw Throwables.propagate(e.getCause()); } }
From source file:com.google.caliper.runner.StreamService.java
@Override protected void doStart() { try {// w ww .j av a 2 s .c om // TODO(lukes): write the commandline to the trial output file? process = worker.startWorker(); } catch (IOException e) { notifyFailed(e); return; } // Failsafe kill the process and the executor service. // If the process has already exited cleanly, this will be a no-op. addListener(new Listener() { @Override public void starting() { } @Override public void running() { } @Override public void stopping(State from) { } @Override public void terminated(State from) { cleanup(); } @Override public void failed(State from, Throwable failure) { cleanup(); } void cleanup() { streamExecutor.shutdown(); process.destroy(); try { streamExecutor.awaitTermination(10, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } streamExecutor.shutdownNow(); } }, MoreExecutors.directExecutor()); // You may be thinking as you read this "Yo dawg, what if IOExceptions rain from the sky?" // If a stream we are reading from throws an IOException then we fail the entire Service. This // will cause the worker to be killed (if its not dead already) and the various StreamReaders to // be interrupted (eventually). // use the default charset because worker streams will use the default for output Charset processCharset = Charset.defaultCharset(); runningReadStreams.addAndGet(2); openStreams.addAndGet(1); streamExecutor.submit(threadRenaming("worker-stderr", new StreamReader("stderr", new InputStreamReader(process.getErrorStream(), processCharset)))); streamExecutor.submit(threadRenaming("worker-stdout", new StreamReader("stdout", new InputStreamReader(process.getInputStream(), processCharset)))); worker.socketFuture().addListener(new Runnable() { @Override public void run() { try { OpenedSocket openedSocket = Uninterruptibles.getUninterruptibly(worker.socketFuture()); logger.fine("successfully opened the pipe from the worker"); socketWriter = openedSocket.writer(); runningReadStreams.addAndGet(1); openStreams.addAndGet(1); streamExecutor .submit(threadRenaming("worker-socket", new SocketStreamReader(openedSocket.reader()))); } catch (ExecutionException e) { notifyFailed(e.getCause()); } } }, MoreExecutors.directExecutor()); notifyStarted(); }
From source file:com.datastax.driver.core.DefaultResultSetFuture.java
/** * Waits for the query to return and return its result. * * This method is usually more convenient than {@link #get} because it: * <ul>//from w ww. j a va2s. c o m * <li>Waits for the result uninterruptibly, and so doesn't throw * {@link InterruptedException}.</li> * <li>Returns meaningful exceptions, instead of having to deal * with ExecutionException.</li> * </ul> * As such, it is the preferred way to get the future result. * * @throws NoHostAvailableException if no host in the cluster can be * contacted successfully to execute this query. * @throws QueryExecutionException if the query triggered an execution * exception, that is an exception thrown by Cassandra when it cannot execute * the query with the requested consistency level successfully. * @throws QueryValidationException if the query is invalid (syntax error, * unauthorized or any other validation problem). */ public ResultSet getUninterruptibly() { try { return Uninterruptibles.getUninterruptibly(this); } catch (ExecutionException e) { throw extractCauseFromExecutionException(e); } }
From source file:com.datastax.driver.core.Connection.java
public void setKeyspace(String keyspace) throws ConnectionException { if (keyspace == null) return;/*from w w w. j a va2 s. c o m*/ if (this.keyspace != null && this.keyspace.equals(keyspace)) return; try { logger.trace("[{}] Setting keyspace {}", name, keyspace); Message.Response response = Uninterruptibles.getUninterruptibly( write(new QueryMessage("USE \"" + keyspace + "\"", ConsistencyLevel.DEFAULT_CASSANDRA_CL))); switch (response.type) { case RESULT: this.keyspace = keyspace; break; default: // The code set the keyspace only when a successful 'use' // has been perform, so there shouldn't be any error here. // It can happen however that the node we're connecting to // is not up on the schema yet. In that case, defuncting // the connection is not a bad choice. defunct(new ConnectionException(address, String.format("Problem while setting keyspace, got %s as response", response))); break; } } catch (ConnectionException e) { throw defunct(e); } catch (BusyConnectionException e) { logger.error( "Tried to set the keyspace on busy connection. This should not happen but is not critical"); } catch (ExecutionException e) { throw defunct(new ConnectionException(address, "Error while setting keyspace", e)); } }
From source file:com.datastax.driver.mapping.Mapper.java
/** * Creates a query that can be used to save the provided entity. * <p/>//w w w.j ava 2s . c om * 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. * * @param entity the entity to save. * @return a query that saves {@code entity} (based on it's defined mapping). */ public Statement saveQuery(T entity) { try { return Uninterruptibles.getUninterruptibly(saveQueryAsync(entity, this.defaultSaveOptions)); } catch (ExecutionException e) { throw DriverThrowables.propagateCause(e); } }
From source file:com.datastax.driver.core.Session.java
private PreparedStatement toPreparedStatement(String query, Connection.Future future) throws NoHostAvailableException { try {//from w w w . j a va 2 s . c om Message.Response response = Uninterruptibles.getUninterruptibly(future); switch (response.type) { case RESULT: ResultMessage rm = (ResultMessage) response; switch (rm.kind) { case PREPARED: ResultMessage.Prepared pmsg = (ResultMessage.Prepared) rm; try { manager.cluster.manager.prepare(pmsg.statementId, manager.poolsState.keyspace, query, future.getAddress()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // This method don't propage interruption, at least not for now. However, if we've // interrupted preparing queries on other node it's not a problem as we'll re-prepare // later if need be. So just ignore. } return PreparedStatement.fromMessage(pmsg, manager.cluster.getMetadata()); default: throw new DriverInternalError( String.format("%s response received when prepared statement was expected", rm.kind)); } case ERROR: ResultSetFuture.extractCause(ResultSetFuture.convertException(((ErrorMessage) response).error)); break; default: throw new DriverInternalError( String.format("%s response received when prepared statement was expected", response.type)); } throw new AssertionError(); } catch (ExecutionException e) { ResultSetFuture.extractCauseFromExecutionException(e); throw new AssertionError(); } catch (QueryExecutionException e) { // Preparing a statement cannot throw any of the QueryExecutionException throw new DriverInternalError("Received unexpected QueryExecutionException while preparing statement", e); } }
From source file:info.archinnov.achilles.internals.query.dsl.select.AbstractSelectWhere.java
public Tuple2<TypedMap, ExecutionInfo> getTypedMapWithStats() { try {//from w ww. ja v a 2 s . c o m return Uninterruptibles.getUninterruptibly(getTypedMapAsyncWithStats()); } catch (ExecutionException e) { throw extractCauseFromExecutionException(e); } }
From source file:org.grouplens.lenskit.eval.script.EvalScript.java
public Object methodMissing(String name, Object arg) { Object[] args = InvokerHelper.asArray(arg); logger.debug("searching for eval command {}", name); Object obj = null;// w w w . ja va2s . c o m try { obj = helper.callExternalMethod(name, args); } catch (NoSuchMethodException e) { throw new MissingMethodException(name, getClass(), args, true); } if (obj instanceof Builder) { return helper.finishBuilder((Builder<?>) obj); } else if (obj instanceof EvalTask) { final EvalTask<?> task = (EvalTask<?>) obj; if (currentTarget == null) { try { ListenableFuture<List<Object>> deps = Futures.allAsList(helper.getDeps(task)); helper.clearDeps(task); Runnable execute = new Runnable() { @Override public void run() { try { task.execute(); } catch (TaskExecutionException e) { throw new RuntimeException("task failure", e); } } }; deps.addListener(execute, MoreExecutors.sameThreadExecutor()); if (task.isDone()) { return Uninterruptibles.getUninterruptibly(task); } else { return task; } } catch (ExecutionException e) { throw new RuntimeException("task failure", e); } } else { EvalAntTask aTask = new EvalAntTask(task, helper.getDeps(task)); aTask.setProject(getAntProject()); aTask.setOwningTarget(currentTarget); aTask.init(); currentTarget.addTask(aTask); return obj; } } else { return obj; } }
From source file:com.github.jeluard.guayaba.util.concurrent.Scheduler.java
/** * @param maxTasks/* w w w . ja va 2 s .com*/ * @return a default {@link ExecutorService}. Assumes it will be used with {@link Scheduler} only. */ public static ExecutorService defaultExecutorService(final int maxTasks, final Logger logger) { final int availableProcessors = Runtime.getRuntime().availableProcessors(); final ThreadFactory threadFactory = ThreadFactoryBuilders .safeBuilder(Scheduler.THREAD_EXECUTOR_NAME, logger).build(); final ExecutorService executorService = new ThreadPoolExecutor(availableProcessors, availableProcessors * 2, 1l, TimeUnit.MINUTES, new ArrayBlockingQueue<Runnable>(maxTasks, true), threadFactory, new ThreadPoolExecutor.AbortPolicy()) { @Override protected <T> RunnableFuture<T> newTaskFor(final Callable<T> callable) { return new FutureTask<T>(callable) { @Override public String toString() { return callable.toString(); } }; } @Override protected void beforeExecute(final Thread thread, final Runnable runnable) { super.beforeExecute(thread, runnable); if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "About to execute <{0}> from <{1}>", new Object[] { runnable, thread }); } } @Override protected void afterExecute(final Runnable runnable, final Throwable t) { super.afterExecute(runnable, t); //No Runnable are directly executed in this ThreadPool so `t` will always be null. //Logs success/failures when applicable. if (logger.isLoggable(Level.WARNING)) { final Future future = Future.class.cast(runnable); //Safe cast. We never execute Runnable directly. if (future.isCancelled()) {//Only consider successful executions, ignore cancelled tasks. if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "Successfully executed <{0}>", runnable); } return; } try { Uninterruptibles.getUninterruptibly(future); } catch (ExecutionException e) { logger.log(Level.WARNING, "Failed to execute <" + runnable + ">", e.getCause()); } } } }; return executorService; }