Joao Sardinha
Joao Sardinha

Reputation: 3423

Using LruCache: Is cache attatched to a LruCache instance?

I might just be confused about how LruCache is supposed to work, but are does it not allow accessing objects from one instance that were saved on another instance? Surely this is not the case otherwise it kind of defeats the purpose of having cache.

Example:

class CacheInterface {

    private val lruCache: LruCache<String, Bitmap>

    init {
        val maxMemory = (Runtime.getRuntime().maxMemory() / 1024).toInt()
        // Use 1/8th of the available memory for this memory cache.
        val cacheSize = maxMemory / 8
        lruCache = object : LruCache<String, Bitmap>(cacheSize) {
            override fun sizeOf(key: String, value: Bitmap): Int {
                return value.byteCount / 1024
            }
        }
    }

    fun getBitmap(key: String): Bitmap? {
        return lruCache.get(key)
    }

    fun storeBitmap(key: String, bitmap: Bitmap) {
        lruCache.put(key, bitmap)
        Utils.log(lruCache.get(key))
    }

}
val bitmap = getBitmal()
val instance1 = CacheInterface()
instance1.storeBitmap("key1", bitmap)
log(instance1.getBitmap("key1")) //android.graphics.Bitmap@6854e91
log(CacheInterface().getBitmap("key1")) //null

As far as I understand, cache is stored until it's deleted by the user (manually or uninstalling the app), or cleared by the system when it exceeds the allowed space. What am I missing?

Upvotes: 0

Views: 451

Answers (3)

Joao Sardinha
Joao Sardinha

Reputation: 3423

Yes it is. I'll just share here what I was confused about in case anyone also is.

Initially because of this guide (Caching Bitmaps) that reccomends using LruCache, I was left under the impression that LruCache was an interface to access app's cache, but like @CommonsWare mentioned it has no I/O in it - it's just a utility class to hold memory using the LRU policy. To access your app's cache you need to use Context.getCacheDir(), good explanation here. In my case I ended up using a singleton of LruCache, since I already have a service running most of the time the app will not be killed every time it's closed.

Upvotes: 0

fancyyou
fancyyou

Reputation: 965

log(CacheInterface().getBitmap("key1")) //null

equals

val instance2 = CacheInterface()
log(instance2 .getBitmap("key1"))

instance1 != instance2

change to Singleton

object CacheInterface{
...
}

use

CacheInterface.storeBitmap("key1",bitmap)
CacheInterface.getBitmap("key1")

Upvotes: -1

ianhanniballake
ianhanniballake

Reputation: 199880

An LruCache object just stores references to objects in memory. As soon as you lose the reference to the LruCache, the LruCache object and all of the objects within that cache are garbage collected. There's nothing stored to disk.

Upvotes: 2

Related Questions