001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.classic.turbo.lru;
015
016import java.util.ArrayList;
017import java.util.Collections;
018import java.util.LinkedList;
019import java.util.List;
020
021/**
022 * This is an alternative (slower) implementation of LRUCache for testing
023 * purposes.
024 * 
025 * @author Ceki Gulcu
026 */
027public class T_LRUCache<K> {
028
029    int sequenceNumber;
030    final int cacheSize;
031    List<T_Entry<K>> cacheList = new LinkedList<T_Entry<K>>();
032
033    public T_LRUCache(int size) {
034        this.cacheSize = size;
035    }
036
037    synchronized public void put(K k) {
038        sequenceNumber++;
039        T_Entry<K> te = getEntry(k);
040        if (te != null) {
041            te.sequenceNumber = sequenceNumber;
042        } else {
043            te = new T_Entry<K>(k, sequenceNumber);
044            cacheList.add(te);
045        }
046        Collections.sort(cacheList);
047        while (cacheList.size() > cacheSize) {
048            cacheList.remove(0);
049        }
050    }
051
052    synchronized public K get(K k) {
053        T_Entry<K> te = getEntry(k);
054        if (te == null) {
055            return null;
056        } else {
057            te.sequenceNumber = ++sequenceNumber;
058            Collections.sort(cacheList);
059            return te.k;
060        }
061    }
062
063    synchronized public List<K> keyList() {
064        List<K> keyList = new ArrayList<K>();
065        for (T_Entry<K> e : cacheList) {
066            keyList.add(e.k);
067        }
068        return keyList;
069    }
070
071    private T_Entry<K> getEntry(K k) {
072        for (int i = 0; i < cacheList.size(); i++) {
073            T_Entry<K> te = cacheList.get(i);
074            if (te.k.equals(k)) {
075                return te;
076            }
077        }
078        return null;
079    }
080
081    public void dump() {
082        System.out.print("T:");
083        for (T_Entry<K> te : cacheList) {
084            // System.out.print(te.toString()+"->");
085            System.out.print(te.k + ", ");
086        }
087        System.out.println();
088    }
089
090}