File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes LRU cache Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "LRU cache" Watch "LRU cache" New topic
Author

LRU cache

Vinney Shanmugam
Ranch Hand

Joined: Aug 27, 2008
Posts: 104
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?
Nicola Garofalo
Ranch Hand

Joined: Apr 10, 2010
Posts: 308
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.

    Bye,
    Nicola
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: LRU cache