gpt4 book ai didi

android - LRUCache 未按预期工作

转载 作者:行者123 更新时间:2023-11-30 02:53:50 24 4
gpt4 key购买 nike

以下示例表明,在 LRUCache 之外分配新空间时,使用有限大小的 LRUCache 会导致 OutOfMemory 错误。

属性:64MB 进程大小; 10MB LRUCache 大小;我循环放入 LRUCache 的 1MB block 。

在 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];
}
}

最佳答案

来自 http://developer.android.com/reference/android/util/LruCache.html

By default, the cache size is measured in the number of entries. Override sizeOf(K, V) to size the cache in different units.

所以你应该这样做:

LruCache<String, MyDataClass> nativelrucache=new LruCache<String, MyDataClass>(iMegabyte*10){
protected int sizeOf(String key, MyDataClass value) {
return value.bytes.length;
};
};

关于android - LRUCache 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23671687/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com