2003/12/13 08:13:34
[org.ibex.core.git] / src / org / xwt / util / Cache.java
index 27647d6..1822363 100644 (file)
@@ -1,8 +1,16 @@
-// Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
+// Copyright (C) 2003 Adam Megacz <adam@xwt.org> all rights reserved.
+//
+// You may modify, copy, and redistribute this code under the terms of
+// the GNU Library Public License version 2.1, with the exception of
+// the portion of clause 6a after the semicolon (aka the "obnoxious
+// relink clause")
+
 package org.xwt.util;
 
 import java.util.*;
 
+// FIXME needs to be a weak hash
+
 /**
  *  A Hash table with a fixed size; drops extraneous elements.  Uses
  *  LRU strategy.
@@ -13,10 +21,19 @@ public class Cache extends Hash {
     Node mru = null;
     Node lru = null;
 
+    private int maxSize;
+    private Cache() { }
+    public Cache(int maxSize) {
+        super(maxSize * 2, 3);
+        this.maxSize = maxSize;
+    }
+
     /** A doubly-linked list */
     private class Node {
         final Object val;
-        public Node(Object val) { this.val = val; }
+        final Object k1;
+        final Object k2;
+        public Node(Object k1, Object k2, Object val) { this.k1 = k1; this.k2 = k2; this.val = val; }
         Node next = null;
         Node prev = null;
         void remove() {
@@ -65,7 +82,7 @@ public class Cache extends Hash {
     }
 
     public void put(Object k1, Object k2, Object v) {
-        Node n = new Node(v);
+        Node n = new Node(k1, k2, v);
         if (lru == null) {
             lru = mru = n;
         } else {
@@ -74,6 +91,7 @@ public class Cache extends Hash {
         }
         if (super.get(k1, k2) != null) remove(k1, k2);
         super.put(k1, k2, n);
+        if (size > maxSize) remove(lru.k1, lru.k2);
     }
 
 }