org.tamacat.util.CacheLRU.java Source code

Java tutorial

Introduction

Here is the source code for org.tamacat.util.CacheLRU.java

Source

    /*
     * Copyright (c) 2009, TamaCat.org
     * All rights reserved.
     */
    //package org.tamacat.util;

import java.util.ArrayList;
    import java.util.Collection;
    import java.util.LinkedHashMap;
    import java.util.Set;

public class CacheLRU<K,V> {

   private int maxSize;
   private LinkedHashMap<K, V> cache;
   private ArrayList<K> used;
   
   public CacheLRU(int maxSize) {
      this.maxSize = maxSize;
      this.cache = new LinkedHashMap<K,V>(maxSize);
      this.used = new ArrayList<K>(maxSize);
   }
   
   public CacheLRU() {
      this(10);
   }
   
   public synchronized V get(K key) {
      updateUsed(key);
      return cache.get(key);
   }
   
   public synchronized V put(K key, V value) {
      if (cache.size() >= maxSize && used.size() > 0) {
         cache.remove(used.get(0));
         used.remove(0);
      }
      updateUsed(key);
      return cache.put(key, value);
   }
   
   private void updateUsed(K key) {
      used.remove(key);
      used.add(key);      
   }
   
   public synchronized int size() {
      return cache.size();
   }
   
   public synchronized V remove(K key) {
      used.remove(key);
      return cache.remove(key);
   }
   
   public synchronized void clear() {
      cache.clear();
      used.clear();
   }
   
   public Set<K> keySet() {
      return cache.keySet();
   }
   
   public Collection<V> values() {
      return cache.values();
   }
   
   @Override
   public String toString() {
      return getClass().getName() + "@" + hashCode() + "" + cache.toString();
   }
}

    ------------

    /*
     * Copyright (c) 2009, TamaCat.org
     * All rights reserved.
     */
    package org.tamacat.util;

    import static org.junit.Assert.*;

    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;

    public class CacheLRUTest {

        @Before
        public void setUp() throws Exception {
        }

        @After
        public void tearDown() throws Exception {
        }

        @Test
        public void testGet() {
            int maxSize = 3;
            CacheLRU<String, String> cache = new CacheLRU<String, String>(maxSize);
            cache.put("1", "1");
            cache.put("2", "2");
            cache.put("3", "3");
            assertEquals(maxSize, cache.size());
            //cache.get("2");
            //cache.get("1");
            //System.out.println(cache.toString());
            cache.put("4", "4");
            cache.put("5", "5");
            //System.out.println(cache.toString());
            assertEquals(maxSize, cache.size());
        }

    }