如果您想在内存上构建某种缓存,请考虑使用带有 SoftReferences 的 Map。SoftReferences 是一种倾向于将您的数据保留一段时间的引用,但不会阻止它被垃圾收集。
手机上的内存是稀缺的,因此将所有内容都保存在内存中可能不切实际。在这种情况下,您可能希望将缓存保存在设备的辅助存储中。
从Google 的 Collections中查看 MapMaker ,它可以让您方便地构建 2 级缓存。考虑这样做:
/** Function that attempts to load data from a slower medium */
Function<String, String> loadFunction = new Function<String, String>() {
@Override
public String apply(String key) {
// maybe check out from a slower cache, say hard disk
// if not available, retrieve from the internet
return result;
}
};
/** Thread-safe memory cache. If multiple threads are querying
* data for one SAME key, only one of them will do further work.
* The other threads will wait. */
Map<String, String> memCache = new MapMaker()
.concurrentLevel(4)
.softValues()
.makeComputingMap(loadFunction);
关于设备辅助存储上的缓存,请查看Context.getCacheDir()。如果你像我一样马虎,那就把所有东西都放在那里,希望系统在需要更多空间时为你清理东西:P