在我的应用程序中,我有不同的列表视图,其中包含一些缩略图。今天我开始重构,我想实现 LRU 缓存。我正在遵循 Android 指南,但我想知道是否更好地为整个应用程序初始化一个 LRU 缓存,或者更好地为每个列表视图初始化 LRU 缓存。我害怕内存不足。因此,我有以下我自己无法回答的问题: - 一个用单例模式初始化的 LRU 缓存是个好主意吗?- 如果内存不足,是否会导致以下LRU Cache初始化的outOfMemory情况?
@Override
protected void onCreate(Bundle savedInstanceState) {
...
// Get max available VM memory, exceeding this amount will throw an
// OutOfMemory exception. Stored in kilobytes as LruCache takes an
// int in its constructor.
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// Use 1/8th of the available memory for this memory cache.
final int cacheSize = maxMemory / 8;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
// The cache size will be measured in kilobytes rather than
// number of items.
return bitmap.getByteCount() / 1024;
}
};
...
}
如果内存不足,LRU缓存会自动释放吗?我想知道当我使用 LRU 缓存时应用程序是否会出现释放内存的问题(应用程序因内存不足而崩溃?)
整个应用程序只有一个 LRU 缓存,会不会有问题?
- 整个应用程序有多个 LRU 缓存,它们会是一个问题吗?