1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
7 /** A HashMap with a fixed size; drops extraneous elements. Uses an
8 * LRU strategy, either ordering elements based on insertion order
11 * @author crawshaw@ibex.org
13 public class Cache extends Basket.Hash {
14 public Cache(int maxSize, boolean accessOrder) {
15 super(maxSize * 2, 0.75F);
18 private static final long serialVersionUID = 23498092L;
20 private final int maxSize;
21 private final boolean accessOrder;
25 private int first = -1, last = -1;
27 public Cache(int maxSize, boolean accessOrder) {
28 super(maxSize * 2, 0.75F);
30 prev = new int[entries.length];
31 next = new int[entries.length];
32 for (int i=0; i < maxSize; i++) { prev[i] = next[i] = -1; }
34 this.maxSize = maxSize;
35 this.accessOrder = accessOrder;
38 public Object get(Object k) {
40 if (i < 0) return null;
41 if (accessOrder) { // move to front of linked list
44 if (first >= 0) prev[first] = i;
48 return entries[i + 1];
51 protected void entryAdded(int i) {
52 if (last >= 0) next[last] = i;
53 prev[i] = last >= 0 ? last : -1;
55 int ourlast = accessOrder ? last : first;
57 if (first < 0) first = last;
58 if (ourlast >= 0 && size > maxSize) remove(ourlast);
61 protected void entryRemoved(int i) {
62 if (prev[i] >= 0) next[prev[i]] = next[i];
63 if (next[i] >= 0) prev[next[i]] = prev[i];
64 if (last == i) last = prev[i] >= 0 ? prev[i] : -1;
65 if (first == i) first = next[i] >= 0 ? next[i] : -1;
68 protected void entryUpdated(int i) {
69 if (!accessOrder) { entryRemoved(i); entryAdded(i); }