让我们说我有一个可调用对象,我想将它用作缓存中的键和数据检索器。
Callable<SomeObject> callable = () => {
return dataSource.getSomethingBig();
}
SomeObject result = storage.getFromCacheOrSource(callable);
相同的可调用对象可能在其他地方构造并通过高速缓存调用。因此,我想使用可调用对象作为缓存中的键来从那里获取它,或者如果缓存中还没有数据(通过可调用对象得到)填充缓存。
public <T> T getFromCacheOrSource(Callable<T> callable) {
String key = getKeyFromCallable(callable);
if (cache.contains(key)) {
return cache.get(key);
}
T data = callable.call();
cache.put(key, data);
return data;
}
如果可调用对象的内容相同,如何从可调用对象构造一个始终相同的键?
getKeyFromCallable(Callable<T> callable) {
// What to do here to always return the same key for identical callables?
}