1 7 8 package com.sun.jmx.remote.util; 9 10 import java.lang.ref.SoftReference ; 11 import java.util.Iterator ; 12 import java.util.LinkedList ; 13 import java.util.List ; 14 import java.util.WeakHashMap ; 15 16 25 public class CacheMap extends WeakHashMap { 26 39 public CacheMap(int nSoftReferences) { 40 if (nSoftReferences < 0) { 41 throw new IllegalArgumentException ("nSoftReferences = " + 42 nSoftReferences); 43 } 44 this.nSoftReferences = nSoftReferences; 45 } 46 47 public Object put(Object key, Object value) { 48 cache(key); 49 return super.put(key, value); 50 } 51 52 public Object get(Object key) { 53 cache(key); 54 return super.get(key); 55 } 56 57 64 65 private void cache(Object key) { 66 Iterator it = cache.iterator(); 67 while (it.hasNext()) { 68 SoftReference sref = (SoftReference ) it.next(); 69 Object key1 = sref.get(); 70 if (key1 == null) 71 it.remove(); 72 else if (key.equals(key1)) { 73 it.remove(); 75 cache.add(0, sref); 76 return; 77 } 78 } 79 80 int size = cache.size(); 81 if (size == nSoftReferences) { 82 if (size == 0) 83 return; it.remove(); 85 } 86 87 cache.add(0, new SoftReference (key)); 88 } 89 90 98 private final LinkedList cache = new LinkedList (); 99 private final int nSoftReferences; 100 } 101 | Popular Tags |