November 2004
Intermediate to advanced
400 pages
10h 31m
English
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.
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" ...
Read now
Unlock full access