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