以下示例显示,在 LRUCache 之外分配新空间时,使用有限大小的 LRUCache 会导致 OutOfMemory 错误。
属性:64MB 进程大小;10MB LRUCache 大小;我循环放入 LRUCache 的 1MB 块。
经过 57 次(64MB - 7MB)尝试后,我得到:
05-15 09:05:51.385: E/AndroidRuntime(11630): FATAL EXCEPTION: main
05-15 09:05:51.385: E/AndroidRuntime(11630): java.lang.OutOfMemoryError
05-15 09:05:51.385: E/AndroidRuntime(11630): at com.example.testlrucachewithpathes.MyDataClass.<init>(MyDataClass.java:14)
在 lrucache.evictall() 之后,缓存被释放并且有足够的空间再次分配。但我想这不是办法。
有什么提示吗?
这是我的代码:
public class StartActivity extends Activity {
int iMegabyte=1000000;
LruCache<String, Object> nativelrucache=new LruCache<String, Object>(iMegabyte*10);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
// Do my stuff
Log.v("MEMORY STATE", getMemoryStatus());
// Case with MyDataClass ------------------------------------------------------------------------------------
for(int i=0;i<100;i++){
MyDataClass mdataclass=new MyDataClass(iMegabyte);
//lrucachemanager.put("ID_" + i, mdataclass);
Log.v("MEMORY STATE", "put data into cache : " + i);
nativelrucache.put("ID_" + i, mdataclass);
//nativelrucache.evictAll();
}
}
}
public class MyDataClass {
byte[] bytes;
public MyDataClass(int iSize){
//Arrays.fill( bytes, 0 );
bytes=new byte[iSize];
}
}