我对此深感困惑.我有一个静态类,用于管理已下载位图图像的缓存.此类可由多个线程访问,并且有可能进行并发访问.这是实现:
public class BitmapCache { private static final int MAX_NUMBER_BITMAPS_TO_CACHE = 30; private static Map<String, Bitmap> bitmapCache = new HashMap<String, Bitmap>(); private static List<String> cachedBitmapUrlsOrder = new ArrayList<String>(); private BitmapCache(){} public static synchronized voID addBitmapToCache(String url, Bitmap bitmap) { if (bitmapCache.size() >= MAX_NUMBER_BITMAPS_TO_CACHE) { Log.i("MyApp", "Max cache size reached. Removing oldest bitmap. Size = " + bitmapCache.size()); String oldestUrl = cachedBitmapUrlsOrder.remove(0); bitmapCache.remove(oldestUrl); } bitmapCache.put(url, bitmap); cachedBitmapUrlsOrder.add(url); } public static int size() { return bitmapCache.size(); } public static Bitmap get(String url) { return bitmapCache.get(url); } public synchronized static voID clearCache() { bitmapCache.clear(); }}
我正在尝试实现滚动缓存,以便在达到最大缓存大小(常见情况)时,从缓存中删除最旧的位图.运行我的应用程序将提供以下输出:
02-29 23:00:26.590: I/MyApp(10789): Max cache size reached. Removing oldest bitmap. Size = 3002-29 23:00:26.600: I/MyApp(10789): Max cache size reached. Removing oldest bitmap. Size = 3002-29 23:00:26.720: I/MyApp(10789): Max cache size reached. Removing oldest bitmap. Size = 3002-29 23:00:26.790: I/MyApp(10789): Max cache size reached. Removing oldest bitmap. Size = 3002-29 23:00:26.820: I/MyApp(10789): Max cache size reached. Removing oldest bitmap. Size = 3102-29 23:00:26.850: I/MyApp(10789): Max cache size reached. Removing oldest bitmap. Size = 3102-29 23:00:27.050: I/MyApp(10789): Max cache size reached. Removing oldest bitmap. Size = 3202-29 23:00:27.070: I/MyApp(10789): Max cache size reached. Removing oldest bitmap. Size = 3202-29 23:00:27.100: I/MyApp(10789): Max cache size reached. Removing oldest bitmap. Size = 3302-29 23:00:27.130: I/MyApp(10789): Max cache size reached. Removing oldest bitmap. Size = 3402-29 23:00:27.170: I/MyApp(10789): Max cache size reached. Removing oldest bitmap. Size = 3502-29 23:00:27.210: I/MyApp(10789): Max cache size reached. Removing oldest bitmap. Size = 3502-29 23:00:27.330: I/MyApp(10789): Max cache size reached. Removing oldest bitmap. Size = 3502-29 23:00:27.360: I/MyApp(10789): Max cache size reached. Removing oldest bitmap. Size = 35
当缓存大小达到30时,该代码正确地开始记录“已达到最大缓存大小”,并停留在此处几次执行.但随后奇怪的是,它开始增加到35.此时,它将停留在那里,以供数百个输出使用.我无法将其增加到35岁以上.
我的实现有什么问题?鉴于addBitmapToCache方法已同步,我对高速缓存的大小如何超出最大设置感到困惑.
解决方法:
几个问题.
首先,cachedBitmapUrlsOrder是一个列表.如果多次请求同一位图,会发生什么情况?您会在列表中找到一大堆重复的URL.因此,第一次达到限制时,您便从列表和地图中删除了一个URL.但是,相同的URL仍在列表中,没有匹配的映射条目.因此,后续尝试从列表中删除相同的URL不会从地图中删除任何内容,并且地图将会增长.
您可以通过使用bitmapCache.containsKey(url)在addBitmapToCache()开始时检查URL是否已被缓存来避免这种情况.如果是这样,则无需修改地图.只需确保该条目被记住为最新条目即可.
或者,将列表更改为唯一值的集合; URL到时间戳或Set的映射. (我让你决定.)
同样,get()和size()方法也应该同步.
并且get()应该更新检索到的条目的时间戳,以便它成为最新的.
总结以上是内存溢出为你收集整理的为何我的缓存机制无法按预期运行?全部内容,希望文章能够帮你解决为何我的缓存机制无法按预期运行?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)