• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

LRU cache

 
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Which collection can be used to implement Least Recently Used cache in java?

We can use LinkedHashMap. I dont have a justification for this. Can someone help me understand this clearly?
 
Ranch Hand
Posts: 308
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Vinney,
in LRU cache the least recently used element in the cache is dropped when you add a new element, if you exceed the cache size.

You can customize a LinkedHashMap to behave exactly in that way.

  • 1)
  • You use a Map to store key,value pairs where the key is the cache address and value is the corresponding cache content.

  • 2)
  • In a LinkedHashMap you have a method called removeEldestEntry (see API documentation) that returns true if the eldest element in the linked map has to be deleted. (and in LRU it has to when you exceed the cache size)

  • 3)
  • LinkedHashMap has a constructor in which you can specify the ordering mode



    in the above constructor if the parameter accessOrder is set to true, the last accessed entry (i.e. the last one you retrieve with method get) becomes the first in list, the newest one, the most recently used.

    Now i suggest you to write a simple example in which you build a LinkedHashMap of,for instance, 5 elements (where five is the cache size) and to override removeEldestEntry method in such a way that you remove the eldest entry (last accessed one) when you try to insert the sixth element.
     
    Don't get me started about those stupid light bulbs.
    reply
      Bookmark Topic Watch Topic
    • New Topic