View Javadoc

1   /**
2    * Logback: the generic, reliable, fast and flexible logging framework.
3    * 
4    * Copyright (C) 2000-2008, QOS.ch
5    * 
6    * This library is free software, you can redistribute it and/or modify it under
7    * the terms of the GNU Lesser General Public License as published by the Free
8    * Software Foundation.
9    */
10  package ch.qos.logback.classic.pattern;
11  
12  import java.util.ArrayList;
13  import java.util.LinkedHashMap;
14  import java.util.List;
15  import java.util.Map;
16  
17  /**
18   * An lru cache based on Java's LinkedHashMap.
19   * 
20   * @author Ceki Gulcu
21   *
22   * @param <K>
23   * @param <V>
24   */
25  public class LRUCache<K, V> extends LinkedHashMap<K, V> {
26    private static final long serialVersionUID = -6592964689843698200L;
27  
28    final int cacheSize;
29  
30    public LRUCache(int cacheSize) {
31      super((int) (cacheSize*(4.0f/3)), 0.75f, true);
32      if(cacheSize < 1) {
33        throw new IllegalArgumentException("Cache size cannnot be smaller than 1");
34     } 
35      this.cacheSize = cacheSize;
36    }
37    
38    protected boolean removeEldestEntry(Map.Entry eldest) {
39      return (size() > cacheSize);
40    }
41    
42    List<K> keyList() {
43      ArrayList<K> al = new ArrayList<K>();
44      al.addAll(keySet());
45      return al;
46    }
47  }