具有异步加载的LoadingCache [英] LoadingCache with async loading

查看:132
本文介绍了具有异步加载的LoadingCache的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在番石榴中,当使用LoadingCache时,将同步调用CacheLoader.但是,我的 load()操作可能花费太长时间(〜1秒),我想采取默认操作以防花费太长时间(> 200 ms)并异步加载该值.

有没有办法做到这一点?还是您可以推荐其他方法?

解决方案

咖啡因库是对Guava缓存的Java 8重写,允许异步自动将条目加载到缓存中,并返回CompletableFutures.它是由直接参与创建Guava缓存的人员编写的,并使用了受Guava启发的API(包括用于Guava接口的适配器).

根据Guava邮件列表上的帖子,它基于Guava缓存库的原始建议,并且包括原本打算用于Guava本身的更改,但由于各种原因而未包括在内(包括Guava需要兼容)使用Java的旧版本.

实际上,某些项目现在认为不赞成使用Guava缓存,而是使用Caffeine,例如.Spring已切换到Caffeine ,作者指出"Caffeine是ConcurrentLinkedHashMap和Guava缓存的Java 8继承者.项目应首选Caffeine,并在需要JDK8或更高版本时进行迁移."

In guava, when using LoadingCache CacheLoader is called synchronously. However, my load() operation may take too long (~1 sec), I want to take a default action in case it takes too long (>200 ms) and load the value asynchronously.

Is there a way to achieve this? Or are there any other approaches you can recommend?

解决方案

The Caffeine library is a Java 8 rewrite of Guava's cache that allows asynchronous automatic loading of entries into a cache, returning CompletableFutures. It is written by people who were directly involved in creating the Guava cache, and uses a Guava-inspired API (including an adapter to Guava's interfaces).

According to posts on the Guava mailing list, it is based on the original proposal for the Guava caching library, and includes changes that were originally intended for Guava itself, but were not included for various reasons (including Guava's need to be compatible with older versions of Java).

In fact, some projects now consider the Guava cache deprecated and use Caffeine instead, e.g. Spring has switched to Caffeine and the author states that "Caffeine is the Java 8 successor to ConcurrentLinkedHashMap and Guava's cache. Projects should prefer Caffeine and migrate when requiring JDK8 or higher."

这篇关于具有异步加载的LoadingCache的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆