下面列出了怎么用com.google.common.util.concurrent.SimpleTimeLimiter的API类实例代码及写法,或者点击链接到github查看源代码。
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();
}
}
@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()));
}
/** 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);
}
}
/** 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);
}
}
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);
}
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);
}
public FixedTimeLimit(
long duration,
TimeUnit timeUnit,
ExecutorService executorService
) {
this(SimpleTimeLimiter.create(executorService), duration, timeUnit);
}
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();
}
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);
}
public FixedAttemptTimeLimit(long duration, TimeUnit timeUnit) {
this(SimpleTimeLimiter.create(Executors.newSingleThreadExecutor()), duration, timeUnit);
}
public FixedAttemptTimeLimit(long duration, TimeUnit timeUnit, ExecutorService executorService) {
this(SimpleTimeLimiter.create(executorService), duration, timeUnit);
}
public FixedAttemptTimeLimit(long duration, TimeUnit timeUnit) {
this(SimpleTimeLimiter.create(Executors.newSingleThreadExecutor()), duration, timeUnit);
}
public FixedAttemptTimeLimit(long duration, TimeUnit timeUnit, ExecutorService executorService) {
this(SimpleTimeLimiter.create(executorService), duration, timeUnit);
}
public static TimeLimiter create() {
return SimpleTimeLimiter.create(new NewRequestThreadExecutorService());
}