2
LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
       .maximumSize(1000)
       .build(
           new CacheLoader<Key, Graph>() {
             public Graph load(Key key) throws AnyException {
               return createExpensiveGraph(key);
             }
           });

createExpensiveGraph方法可能需要很长时间才能返回值。我想在方法中设置一个时间限制load,这样如果createExpensiveGraph方法在有限的时间内没有返回值,TimeLimitedException就会抛出 a。如何在load方法中设置时间限制?

4

2 回答 2

4

编辑:更正为newSingleThreadExecutoreclps指出的使用。

您可以使用 aCallable和 anExecutorService来实现超时行为:

final ExecutorService executor = Executors.newSingleThreadExecutor();

final LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
       .maximumSize(1000)
       .build(
           new CacheLoader<Key, Graph>() {
               public Graph load(final Key key) throws Exception {
                   return executor.submit(new Callable<Graph>() {
                       @Override
                       public Graph call() {
                           return createExpensiveGraph(key);
                       }
                   }).get(MY_TIME_LIMIT_SECONDS, TimeUnit.SECONDS);
               }
           });

get通话现场:

final Graph graph;
try {
    graph = graphs.get(myKey);
}
catch (ExecutionException executionException) {
    final Throwable cause = Throwables.getRootCause(executionException);
    if (cause instanceof TimeoutException) {
        // timeout specific logic
    }
    // other error handling
}

// use graph
于 2013-08-23T05:12:23.103 回答
3

Paul Bellora 所写的示例将无法正常工作,因为MoreExecutors.sameThreadExecutor().

来自javadocsMoreExecutors.sameThreadExecutor():_

任务在 Future 返回给调用者之前运行完成(除非执行器已关闭)。

因此,在完成执行get之前不会调用 on Future 。createExpensiveGraph使用Executors.newSingleThreadExecutor()或类似的 Executor 来支持超时。

于 2014-06-11T19:21:35.290 回答