3alto 3alto - 1 year ago 129
Android Question

why do we divide by 1024 for a custom LRUCache in android

final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);


final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024 / 8);

Howcome i have to divide the maxMemory by 1024. Furthermore, why would one divide again by 8. I've seen it done both ways in the tutorials i've seen for writing a custom LRUCache yet i don't understand the implications?

Answer Source

Howcome i have to divide the maxMemory by 1024

You do not have to divide anything by anything to use LRUCache.

What you do need is for the maxSize that you pass into the LRUCache constructor to be in the same units as you use in your sizeOf() method.

For example, here is a sample bit of LRUCache code, taken from the JavaDocs:

int cacheSize = 4 * 1024 * 1024; // 4MiB
LruCache<String, Bitmap> bitmapCache = new LruCache<String, Bitmap>(cacheSize) {
    protected int sizeOf(String key, Bitmap value) {
        return value.getByteCount();

Here, the unit of size is a byte. So, the comment indicates that they are passing in a number of bytes representing 4MiB, and sizeOf() returns the size of the Bitmap in bytes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download