Common Java Cookbook

Edition: 0.19

Download PDF or Read on Scribd

Download Examples (ZIP)

5.17. Creating a Least Recently Used Cache

5.17.1. Problem

You need to present common data to many clients, and you want to cache this common data in a data structure of limited size, evicting the least recently used entry when the maximum size limit has been reached.

5.17.2. Solution

Use LRUMap—a fixed size map that uses the least recently used algorithm to evict entries once the maximum size has been reached. The least recently used algorithm evicts the element that has not been used for the longest amount of time. The following example demonstrates the use of an LRUMap to store stock quotes:

import java.util.Map;
import org.apache.commons.collections.map.LRUMap;
cache = new LRUMap( 5 );
       
// Populate the cache with 5 stock prices
cache.put( "MSFT", new Float( 0.03 ) );
cache.put( "TSC", new Float( 0.001 ) );
cache.put( "LU", new Float( 23.30 ) );
cache.put( "CSCO", new Float( 242.20 ) );
cache.put( "P", new Float( 10.23 ) );
        
// Now use some of the entries in the cache
Float cscoPrice  = (Float) cache.get( "CSCO" );
Float msPrice = (Float) cache.get( "MSFT" );
Float tscPrice = (Float) cache.get( "TSC" );
Float luPrice = (Float) cache.get( "LU" );
Float pPrice = (Float) cache.get( "P" );
Float msPrice2 = (Float) cache.get( "MSFT" );
       
// Add another price to the Map, this should kick out the LRU item.
               cache.put( "AA", new Float( 203.20 ) );
                    
               // CSCO was the first price requested, it is therefore the
               // least recently used.
               if( !cache.containsKey("CSCO") ) {
                   System.out.println( "As expected CSCO was discarded" );
               }
            

Since the LRUMap created in this example can only hold five elements, the "CSCO" quote is evicted when "AA" is added to the map because it is the "least recently used."

5.17.3. Discussion

An LRUMap is appropriate when a system presents common data to a number of clients. For example, if a web site displays breaking news stories, objects representing these stories can be stored in a size-limited cache with an LRU eviction policy, such as LRUMap. Demand for objects that represent breaking news stories can be very time sensitive; many customers read the same story at the same time. Your application server has a size-limited LRUMap that holds 100 news stories, and, when a new story is added, the LRUMap evicts the stalest story in the Map.


Creative Commons License
Common Java Cookbook by Tim O'Brien is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License.
Permissions beyond the scope of this license may be available at http://www.discursive.com/books/cjcook/reference/jakartackbk-PREFACE-1.html. Copyright 2009. Common Java Cookbook Chunked HTML Output. Some Rights Reserved.