介绍
- Memoization适用于没有参数的函数(Supplier)
- 当我们想要执行memoized方法时,我们可以简单地调用返回的Supplier的get方法,根据方法的返回值是否存在于内存中,get方法将返回内存中的值或执行memoized方法并将返回值传递给调用方。
- 在Suppliers类中有两种memoization的方法:memoize和memoizeWithExpiration。
Supplier Memoization Without Eviction
我们可以使用supplier的memoize方法并指定委托的supplier作为方法引用:
Supplier<String> memoizedSupplier = Suppliers.memoize(
CostlySupplier::generateBigNumber);
由于我们没有指定驱逐政策,一旦调用了get方法,返回的值将在Java应用程序仍在运行时保留在内存中。在初始调用之后进行的任何调用都将返回memoized值。
Supplier Memoization with Eviction by Time-To-Live (TTL)
假设我们只想在备忘录中保留供应商返回的值一段时间。
我们可以使用供应商的memoizeWithExpiration方法,并指定过期时间及其相应的时间单位(例如,秒,分钟),以及委托的supplier:
Supplier<String> memoizedSupplier = Suppliers.memoizeWithExpiration(
CostlySupplier::generateBigNumber, 5, TimeUnit.SECONDS);
在指定的时间过去(5秒)后,缓存将从内存中退出Supplier的返回值,随后对get方法的任何调用都将重新执行generateBigNumber。
例子
public class CostlySupplier {
private static BigInteger generateBigNumber() {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {}
return new BigInteger("12345");
}
}
@Test
public void givenMemoizedSupplier_whenGet_thenSubsequentGetsAreFast() {
Supplier<BigInteger> memoizedSupplier;
memoizedSupplier = Suppliers.memoize(CostlySupplier::generateBigNumber);
BigInteger expectedValue = new BigInteger("12345");
assertSupplierGetExecutionResultAndDuration(
memoizedSupplier, expectedValue, 2000D);
assertSupplierGetExecutionResultAndDuration(
memoizedSupplier, expectedValue, 0D);
assertSupplierGetExecutionResultAndDuration(
memoizedSupplier, expectedValue, 0D);
}
private <T> void assertSupplierGetExecutionResultAndDuration(
Supplier<T> supplier, T expectedValue, double expectedDurationInMs) {
Instant start = Instant.now();
T value = supplier.get();
Long durationInMs = Duration.between(start, Instant.now()).toMillis();
double marginOfErrorInMs = 100D;
assertThat(value, is(equalTo(expectedValue)));
assertThat(
durationInMs.doubleValue(),
is(closeTo(expectedDurationInMs, marginOfErrorInMs)));
}
原理
Suppliers#memoize
public static <T> Supplier<T> memoize(Supplier<T> delegate) {
return (delegate instanceof MemoizingSupplier)
? delegate
: new MemoizingSupplier<T>(Preconditions.checkNotNull(delegate));
}
看下 MemoizingSupplier类
@VisibleForTesting
static class MemoizingSupplier<T> implements Supplier<T>, Serializable {
final Supplier<T> delegate;
transient volatile boolean initialized;
// 读取和写入保证了读取可见的写入值
// value不需要使用volatile
transient T value;
MemoizingSupplier(Supplier<T> delegate) {
this.delegate = delegate;
}
@Override public T get() {
// 重点在这里 Double Checked Locking的变体
if (!initialized) {
synchronized (this) {
if (!initialized) {
T t = delegate.get();
value = t;
initialized = true;
return t;
}
}
}
return value;
}
@Override public String toString() {
return "Suppliers.memoize(" + delegate + ")";
}
private static final long serialVersionUID = 0;
}
Suppliers#memoizeWithExpiration
public static <T> Supplier<T> memoizeWithExpiration(
Supplier<T> delegate, long duration, TimeUnit unit) {
return new ExpiringMemoizingSupplier<T>(delegate, duration, unit);
}
@VisibleForTesting static class ExpiringMemoizingSupplier<T>
implements Supplier<T>, Serializable {
final Supplier<T> delegate;
final long durationNanos;
transient volatile T value;
// The special value 0 means "not yet initialized".
transient volatile long expirationNanos;
ExpiringMemoizingSupplier(
Supplier<T> delegate, long duration, TimeUnit unit) {
this.delegate = Preconditions.checkNotNull(delegate);
this.durationNanos = unit.toNanos(duration);
Preconditions.checkArgument(duration > 0);
}
@Override public T get() {
// Another variant of Double Checked Locking.
//
我们使用两个易失性读取。通过将我们的字段放入持有者类,
额外的内存消耗和间接比额外的易失性读取更昂贵。
long nanos = expirationNanos;
long now = Platform.systemNanoTime();
if (nanos == 0 || now - nanos >= 0) {
synchronized (this) {
if (nanos == expirationNanos) { // recheck for lost race
T t = delegate.get();
value = t;
nanos = now + durationNanos;
expirationNanos = (nanos == 0) ? 1 : nanos;
return t;
}
}
}
return value;
}
@Override public String toString() {
// This is a little strange if the unit the user provided was not NANOS,
// but we don't want to store the unit just for toString
return "Suppliers.memoizeWithExpiration(" + delegate + ", " +
durationNanos + ", NANOS)";
}
private static final long serialVersionUID = 0;
}