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