• 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 ...
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
  • Piet Souris
  • Himai Minh

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.
    passwords must contain 14 characters, a number, punctuation, a small bird, a bit of cheese and a tiny ad.
    free, earth-friendly heat - a kickstarter for putting coin in your pocket while saving the earth
      Bookmark Topic Watch Topic
    • New Topic