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.Collections;
18  import java.util.LinkedList;
19  import java.util.List;
20  
21  /**
22   * This is an alternative (slower) implementation of LRUCache for testing
23   * purposes.
24   * 
25   * @author Ceki Gulcu
26   */
27  public class T_LRUCache<K> {
28  
29      int sequenceNumber;
30      final int cacheSize;
31      List<T_Entry<K>> cacheList = new LinkedList<T_Entry<K>>();
32  
33      public T_LRUCache(int size) {
34          this.cacheSize = size;
35      }
36  
37      synchronized public void put(K k) {
38          sequenceNumber++;
39          T_Entry<K> te = getEntry(k);
40          if (te != null) {
41              te.sequenceNumber = sequenceNumber;
42          } else {
43              te = new T_Entry<K>(k, sequenceNumber);
44              cacheList.add(te);
45          }
46          Collections.sort(cacheList);
47          while (cacheList.size() > cacheSize) {
48              cacheList.remove(0);
49          }
50      }
51  
52      synchronized public K get(K k) {
53          T_Entry<K> te = getEntry(k);
54          if (te == null) {
55              return null;
56          } else {
57              te.sequenceNumber = ++sequenceNumber;
58              Collections.sort(cacheList);
59              return te.k;
60          }
61      }
62  
63      synchronized public List<K> keyList() {
64          List<K> keyList = new ArrayList<K>();
65          for (T_Entry<K> e : cacheList) {
66              keyList.add(e.k);
67          }
68          return keyList;
69      }
70  
71      private T_Entry<K> getEntry(K k) {
72          for (int i = 0; i < cacheList.size(); i++) {
73              T_Entry<K> te = cacheList.get(i);
74              if (te.k.equals(k)) {
75                  return te;
76              }
77          }
78          return null;
79      }
80  
81      public void dump() {
82          System.out.print("T:");
83          for (T_Entry<K> te : cacheList) {
84              // System.out.print(te.toString()+"->");
85              System.out.print(te.k + ", ");
86          }
87          System.out.println();
88      }
89  
90  }