following example shows that using an limited sized LRUCache results in a OutOfMemory Error when allocating new space outside of the LRUCache.

Properties: 64MB Process Size ; 10MB LRUCache Size ; 1MB chunks that I put into the LRUCache in a loop.

After 57 (64MB - 7MB) attempts I get :

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)

After an lrucache.evictall() the Cache is freed and there is enough space for allocation again. But I guess thats not the way to do.

Any hints ?

Here my Code :

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];
    }
}
有帮助吗?

解决方案

From 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.

So you should do something like this:

LruCache<String, MyDataClass> nativelrucache=new LruCache<String, MyDataClass>(iMegabyte*10){
    protected int sizeOf(String key, MyDataClass value) {
        return value.bytes.length;
    };
};
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top