2012-03-15 132 views
4

我在我的Android應用程序中使用Guava進行圖像加載並緩存它們的文件名。番石榴文件緩存

這裏是我的緩存:

private static final LoadingCache<String, String> imageCache = CacheBuilder.newBuilder() 
    .softValues() 
    .initialCapacity(3000) 
    .maximumSize(3000) 
    .concurrencyLevel(12) 
    .expireAfterAccess(IMAGE_EXPIRATION_TIMEOUT, TimeUnit.SECONDS) 
    .build(new CacheLoader<String, String>() { 
     @Override 
     public String load(String key) throws Exception { 
      Log.d(TAG, "load " + key); 
      Bitmap bitmap = null; 

      final File imageFile = new File(cacheDir, "http---com-jWs-jpg"); 

      return imageFile.getPath(); 
     } 
    }); 

而且使用:

String filename = imageCache.get(imageUrl); 
Log.e(TAG, ">>> i:cache size :"+ imageCache.size() +":"+ imageCache.stats() +":"+ imageCache.asMap()); 
return Drawable.createFromPath(filename); 

我的問題是:有我的列表中12周獨特的網址,但我有missCount算太大:

i:cache size :6:CacheStats{hitCount=36, missCount=48, loadSuccessCount=48, loadExceptionCount=0, totalLoadTime=46569827...) 

當我返回簡單的字符串(如文件路徑或簡單的空字符串),我只有12個未命中,和其他get是點擊率。我做錯了什麼?

+0

此代碼看起來不錯。你確定這是因爲正常的原因沒有過期嗎? – 2012-03-15 06:08:58

+0

public static final int IMAGE_EXPIRATION_TIMEOUT = 7200; - 我認爲,在幾秒鐘內過期太短 – skayred 2012-03-15 06:11:58

+0

超時時間以毫秒爲單位 - 即7秒 - 如果您使用大量內存,則「softValues」可能會獲得GC'd條目。嘗試添加記錄驅逐和原因的RemovalListener。 – 2012-03-15 06:24:10

回答

4

好吧,明白了。

.softValues()是原因,我的值被垃圾收集器收集。當我評論這一點時,現在一切正常。

+2

無論如何,三種不同的到期策略同時有點過分。 (每個項目都會增加額外的內存。) – 2012-03-15 14:08:06