5

I have implemented a standard LRUCache in Android that stores Objects. Each key is a unique ObjectId associated with the Object stored. My problem is that the only way to retrieve an Object from cache is by the ObjectId (no iterator). What would be the best way to implement a getAll() method? Another option would be to store all the ObjectIds in a list somewhere, so I can iterate over the lists and get all of the Objects - but what would be the best way of holding all of the ObjectIds?

Thanks!

Nelson.b.austin
  • 3,080
  • 6
  • 37
  • 63

3 Answers3

6

If you're using (or extending) the LruCache that Android provides, it has a snapshot method that returns a map of keys (your ObjectIds) and values (your Objects). You can do something like this:

Map<ObjectIds, Object> snapshot = lruCache.snapshot();
for (ObjectIds id : snapshot.keySet()) {
  Object myObject = lruCache.get(id);
}

If you're not using Android's LruCache, then I imagine it would depend on your implementation. (I'd also be curious what motivated you to implement your own instead of subclassing the provided one!)

Michiyo
  • 1,161
  • 1
  • 14
  • 33
  • This doesn't seem like a good solution. The moment you do `lruCache.get()`. That particular entry will be placed at the head of the queue. – gaurav414u Jun 15 '22 at 20:45
5

Using snapshot to get current collection at the moment

lruCache.snapshot().values()
tu4n
  • 4,200
  • 6
  • 36
  • 49
-1

It does not make sense to iterate over the objects in a LRU cache. You can not know which object is still in the cache and which got evicted (you actually can, but that's another story). It sound like you'd probably better off with a different data structure like a Hashmap or so. Nothing will ever get evicted from there.

A common use-case is to have a List of all possible object keys in memory. If you need one, you check if it is in the cache. If not, receive it and add it to the cache.

SimonSays
  • 10,867
  • 7
  • 44
  • 59
  • "It does not make sense to iterate over the objects in a LRU cache." Well, it makes sense for me, so if you do know how to do it please share your knowledge. (I have one cache which may contain a mixture of apples and oranges. Apples and oranges are normally treated the same way, so it would not be a good idea to have separate caches for them. But once in a while I have to accept that all of the apples have gone bad, so I want to evict the apples. The oranges are still OK, so I don't want to do an evictAll().) – RenniePet Sep 01 '14 at 21:32
  • I agree -- there are valid scenarios for iterating over a snapshot of the cached items, regardless of whether some of the items in the snapshot may have been evicted by the time we iterate over them. – Mark McClelland Mar 30 '16 at 21:35