The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.util  [50 examples] > Collections  [7 examples]

e344. Implementing a Least-Recently-Used (LRU) Cache

    // Create cache
    final int MAX_ENTRIES = 100;
    Map cache = new LinkedHashMap(MAX_ENTRIES+1, .75F, true) {
        // This method is called just after a new entry has been added
        public boolean removeEldestEntry(Map.Entry eldest) {
            return size() > MAX_ENTRIES;
        }
    };
    
    // Add to cache
    Object key = "key";
    cache.put(key, object);
    
    // Get object
    Object o = cache.get(key);
    if (o == null && !cache.containsKey(key)) {
        // Object not in cache. If null is not a possible value in the cache,
        // the call to cache.contains(key) is not needed
    }
    
    // If the cache is to be used by multiple threads,
    // the cache must be wrapped with code to synchronize the methods
    cache = (Map)Collections.synchronizedMap(cache);

 Related Examples
e342. Implementing a Queue
e343. Implementing a Stack
e345. Listing the Elements of a Collection
e346. Storing Primitive Types in a Collection
e347. Creating a Copy of a Collection
e348. Making a Collection Read-Only

See also: Arrays    Bits    Dates    Hash Tables    Lists    Property Files    Sets    Sorted Collections    Time    Timers   


© 2002 Addison-Wesley.