java - 如何使用限制时间的guava缓存加载功能?

标签 java caching guava

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 被抛出。如何在 load 方法中设置时间限制?

最佳答案

编辑:更正为使用 newSingleThreadExecutor 作为 pointed out by eclps .

你可以使用 Callable和一个 ExecutorService实现超时行为:

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

关于java - 如何使用限制时间的guava缓存加载功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18394210/

相关文章:

java - Guava:将 Multimap 转换为通用父类(super class)型是否有效?

java - 用另一个 List 扩展 ImmutableList.of()

javascript - 插入的 &lt;script&gt; 标签可以在不使用 JavaScript 中的 eval 的情况下多次运行吗?

windows - 从 Windows 批处理脚本自动缓存 git 凭据?

java-8 - 相当于来自 guava Enums.getIfPresent() 的 java 8 将返回 java.util.Optional?

java - Android 上的单元测试事件序列

java - Java读取大文件——Java堆空间

java - 在 Spring Boot 中自动将参数从表单传递到 URL

java - Intellij Idea - 打开/打开 "programming assists"

c# - 静态缓存错误