com.google.common.util.concurrent.SimpleTimeLimiter Java Examples

The following examples show how to use com.google.common.util.concurrent.SimpleTimeLimiter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EtcdTestSuite.java    From etcd-java with Apache License 2.0 7 votes vote down vote up
static void waitForStartup() throws Exception {
    if (etcdProcess == null) {
        return;
    }
    ExecutorService es = Executors.newSingleThreadExecutor();
    TimeLimiter tl = SimpleTimeLimiter.create(es);
    try {
        tl.callWithTimeout(() -> {
            Reader isr = new InputStreamReader(etcdProcess.getErrorStream());
            BufferedReader br = new BufferedReader(isr);
            String line;
            while ((line = br.readLine()) != null &&
                    !line.contains("ready to serve client requests")) {
                System.out.println(line);
            }
            return null;
        }, 10L, TimeUnit.SECONDS);
    } finally {
        es.shutdown();
    }
}
 
Example #2
Source File: DefaultCommandRunnerTest.java    From carnotzet with Apache License 2.0 6 votes vote down vote up
@Test
public void test_large_output() throws Exception {

	// create temp file of about 274k
	final File tmp = File.createTempFile("carnotzet-test", null);
	tmp.deleteOnExit();
	StringBuilder sb = new StringBuilder();
	for (int i = 0; i < 10000; i++){
		sb.append("This line is repeated a lot\n");
	}
	String expected = sb.toString();
	FileUtils.write(tmp, expected);

	// When
	String actual = new SimpleTimeLimiter().callWithTimeout(
			() -> DefaultCommandRunner.INSTANCE.runCommandAndCaptureOutput("cat", tmp.getAbsolutePath()),
			2, TimeUnit.SECONDS, true);

	// Then
	Assert.assertThat(actual, Is.is(expected.trim()));
}
 
Example #3
Source File: UrlChecker.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/** Probes {@code url} until it becomes available. */
public static void waitUntilAvailable(final URL url, int timeoutMs) {
  try {
    Void unusedReturnValue = SimpleTimeLimiter.create(newCachedThreadPool())
        .callWithTimeout(
            () -> {
              int exponentialBackoffMs = 1;
              while (true) {
                if (isAvailable(url)) {
                  return null;
                }
                Thread.sleep(exponentialBackoffMs *= 2);
              }
            },
            timeoutMs,
            TimeUnit.MILLISECONDS);
  } catch (Exception e) {
    throwIfUnchecked(e);
    throw new RuntimeException(e);
  }
}
 
Example #4
Source File: TestServer.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/** Stops the HTTP server. */
public void stop() {
  try {
    Void unusedReturnValue = SimpleTimeLimiter.create(newCachedThreadPool())
        .callWithTimeout(
            () -> {
              server.stop();
              return null;
            },
            SHUTDOWN_TIMEOUT_MS,
            TimeUnit.MILLISECONDS);
  } catch (Exception e) {
    throwIfUnchecked(e);
    throw new RuntimeException(e);
  }
}
 
Example #5
Source File: AbstractTraverserWorker.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
public AbstractTraverserWorker(TraverserConfiguration conf, IndexingService indexingService) {
  this.name = conf.getName();
  this.indexingService = indexingService;
  this.pollRequest = conf.getPollRequest();
  this.timeout = conf.getTimeout();
  this.timeunit = conf.getTimeunit();

  timeLimiterExecutor = Executors.newCachedThreadPool();
  timeLimiter = SimpleTimeLimiter.create(timeLimiterExecutor);
}
 
Example #6
Source File: ProgressFileReader.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
private void closeWatchService() throws Exception {
    TimeLimiter timeLimiter = new SimpleTimeLimiter();
    timeLimiter.callWithTimeout(new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            watchService.close();
            watchServiceThread.join();
            return true;
        }
    }, 2, TimeUnit.SECONDS, true);
}
 
Example #7
Source File: DockerUtils.java    From Singularity with Apache License 2.0 5 votes vote down vote up
public FixedTimeLimit(
  long duration,
  TimeUnit timeUnit,
  ExecutorService executorService
) {
  this(SimpleTimeLimiter.create(executorService), duration, timeUnit);
}
 
Example #8
Source File: QueryRewriter.java    From presto with Apache License 2.0 4 votes vote down vote up
private List<Column> getColumns(Connection connection, CreateTableAsSelect createTableAsSelect)
        throws SQLException
{
    io.prestosql.sql.tree.Query createSelectClause = createTableAsSelect.getQuery();

    // Rewrite the query to select zero rows, so that we can get the column names and types
    QueryBody innerQuery = createSelectClause.getQueryBody();
    io.prestosql.sql.tree.Query zeroRowsQuery;
    if (innerQuery instanceof QuerySpecification) {
        QuerySpecification querySpecification = (QuerySpecification) innerQuery;
        innerQuery = new QuerySpecification(
                querySpecification.getSelect(),
                querySpecification.getFrom(),
                querySpecification.getWhere(),
                querySpecification.getGroupBy(),
                querySpecification.getHaving(),
                querySpecification.getOrderBy(),
                querySpecification.getOffset(),
                Optional.of(new Limit("0")));

        zeroRowsQuery = new io.prestosql.sql.tree.Query(createSelectClause.getWith(), innerQuery, Optional.empty(), Optional.empty(), Optional.empty());
    }
    else {
        zeroRowsQuery = new io.prestosql.sql.tree.Query(createSelectClause.getWith(), innerQuery, Optional.empty(), Optional.empty(), Optional.of(new Limit("0")));
    }

    ImmutableList.Builder<Column> columns = ImmutableList.builder();
    try (java.sql.Statement jdbcStatement = connection.createStatement()) {
        ExecutorService executor = newSingleThreadExecutor();
        TimeLimiter limiter = SimpleTimeLimiter.create(executor);
        java.sql.Statement limitedStatement = limiter.newProxy(jdbcStatement, java.sql.Statement.class, timeout.toMillis(), TimeUnit.MILLISECONDS);
        try (ResultSet resultSet = limitedStatement.executeQuery(formatSql(zeroRowsQuery))) {
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String name = metaData.getColumnName(i);
                int type = metaData.getColumnType(i);
                columns.add(new Column(name, APPROXIMATE_TYPES.contains(type)));
            }
        }
        catch (UncheckedTimeoutException e) {
            throw new SQLException("SQL statement execution timed out", e);
        }
        finally {
            executor.shutdownNow();
        }
    }

    return columns.build();
}
 
Example #9
Source File: TimeoutBackupStore.java    From presto with Apache License 2.0 4 votes vote down vote up
private static <T> T timeLimited(T target, Class<T> clazz, Duration timeout, ExecutorService executor, int maxThreads)
{
    executor = new ExecutorServiceAdapter(new BoundedExecutor(executor, maxThreads));
    TimeLimiter limiter = SimpleTimeLimiter.create(executor);
    return limiter.newProxy(target, clazz, timeout.toMillis(), MILLISECONDS);
}
 
Example #10
Source File: AttemptTimeLimiters.java    From neural with MIT License 4 votes vote down vote up
public FixedAttemptTimeLimit(long duration, TimeUnit timeUnit) {
    this(SimpleTimeLimiter.create(Executors.newSingleThreadExecutor()), duration, timeUnit);
}
 
Example #11
Source File: AttemptTimeLimiters.java    From neural with MIT License 4 votes vote down vote up
public FixedAttemptTimeLimit(long duration, TimeUnit timeUnit, ExecutorService executorService) {
    this(SimpleTimeLimiter.create(executorService), duration, timeUnit);
}
 
Example #12
Source File: AttemptTimeLimiters.java    From neural with MIT License 4 votes vote down vote up
public FixedAttemptTimeLimit(long duration, TimeUnit timeUnit) {
    this(SimpleTimeLimiter.create(Executors.newSingleThreadExecutor()), duration, timeUnit);
}
 
Example #13
Source File: AttemptTimeLimiters.java    From neural with MIT License 4 votes vote down vote up
public FixedAttemptTimeLimit(long duration, TimeUnit timeUnit, ExecutorService executorService) {
    this(SimpleTimeLimiter.create(executorService), duration, timeUnit);
}
 
Example #14
Source File: AppEngineTimeLimiter.java    From nomulus with Apache License 2.0 4 votes vote down vote up
public static TimeLimiter create() {
  return SimpleTimeLimiter.create(new NewRequestThreadExecutorService());
}