简单的Java缓存库还是设计模式? [英] Simple Java caching library or design pattern?

查看:98
本文介绍了简单的Java缓存库还是设计模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要经常访问耗时的计算结果。结果很少发生变化,所以我不得不不时地重新计算数据,但是可以使用过时的结果一段时间。这样做最简单的方法是什么?现有的库方法还是设计模式?



我正在考虑像

  private static List myCachedList = null; 

...

//刷新列表一次在3600秒
if(needsRefresh(myCachedList,3600)){
//运行计算
myCachedList = ...
}
//从

$ b $使用更新或以前的值b

正确的实现可能不是微不足道的,它可能需要处理线程安全性,竞争条件等,所以我宁愿使用一个经过验证的实现,而不是在我自己的实现。

解决方案

恭喜,意识到写自己的可能会更麻烦,最初出现!



我会查看解决方案。番石榴是一个成熟的图书馆,通过流畅的工厂API可以轻松获得(可配置)高速缓存。


所有番石榴缓存,加载或不,支持方法get(K,
Callable V)。该方法返回与缓存中
中的键相关联的值,或者从指定的Callable计算它,并将其添加到缓存中的
。没有可观察到的状态与此缓存相关联修改
直到加载完成。该方法提供了一个简单的替代
常规的如果缓存,返回;否则创建,缓存和
返回模式。



I need to frequently access the result of a time-consuming calculation. The result changes infrequently, so I have to recalculate the data from time to time but it is ok to use the outdated result for a while. What would be the easiest way to do this and is there an existing library method or design pattern?

I am thinking of something like

private static List myCachedList = null;

...

// refresh list once in 3600 seconds
if (needsRefresh(myCachedList, 3600)) {
    // run the calculation
    myCachedList = ...
}
// use either updated or previous value from here on

A proper implementation might not be trivial, it might have to deal with thread safety, race conditions etc., so I would rather use a proven implementation than roll my own here.

解决方案

Congratulations for realising that writing your own can be more trouble it initially appears!

I would check out the Guava cache solution. Guava is a proven library and the caches are easily available (and configurable) via a fluent factory API.

All Guava caches, loading or not, support the method get(K, Callable<V>). This method returns the value associated with the key in the cache, or computes it from the specified Callable and adds it to the cache. No observable state associated with this cache is modified until loading completes. This method provides a simple substitute for the conventional "if cached, return; otherwise create, cache and return" pattern.

这篇关于简单的Java缓存库还是设计模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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