Java中的memoization有哪些不同的技术?

我知道这个http://onjava.com/pub/a/onjava/2003/08/20/memoization.html但是还有什么吗?

使用普通的简单类型安全Java,记忆也很容易。

您可以使用以下可重用的类从头开始。

我使用这些作为缓存,其生命周期是webapp上的请求。

当然,如果您需要驱逐策略或更多function(如同步),请使用Guava MapMaker

如果需要使用许多参数来记忆方法,只需将参数放在具有这两种技术的列表中,并将该列表作为单个参数传递。

 abstract public class Memoize0 { //the memory private V value; public V get() { if (value == null) { value = calc(); } return value; } /** * will implement the calculation that * is to be remembered thanks to this class */ public abstract V calc(); } abstract public class Memoize1 { //The memory, it maps one calculation parameter to one calculation result private Map values = new HashMap(); public V get(P p) { if (!values.containsKey(p)) { values.put(p, calc(p)); } return values.get(p); } /** * Will implement the calculations that are * to be remembered thanks to this class * (one calculation per distinct parameter) */ public abstract V calc(P p); } 

就像这样使用

  Memoize0 configProvider = new Memoize0() { @Override public String calc() { return fetchConfigFromVerySlowDatabase(); } }; final String config = configProvider.get(); Memoize1 usernameProvider = new Memoize1() { @Override public String calc(Long id) { return fetchUsernameFromVerySlowDatabase(id); } }; final String username = usernameProvider.get(123L); 

要记忆没有参数的函数,请使用Guava的Suppliers.memoize(Supplier) 。 对于带参数的函数,请使用带参数值对象的CacheBuilder.build(CacheLoader)作为键。

是。 使用Guava的 缓存 。

例:

 import java.math.BigInteger; import com.google.common.base.Preconditions; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; public class Fibonacci { private static final LoadingCache CACHE = CacheBuilder.newBuilder().build(CacheLoader.from(Fibonacci::fib)); public static BigInteger fib(int n) { Preconditions.checkArgument(n >= 0); switch (n) { case 0: return BigInteger.ZERO; case 1: return BigInteger.ONE; default: return CACHE.getUnchecked(n - 1).add(CACHE.getUnchecked(n - 2)); } } }