1 7 package com.ibm.icu.impl; 8 9 import java.lang.ref.ReferenceQueue ; 10 import java.lang.ref.SoftReference ; 11 12 15 public class SoftCache { 16 private final LRUMap map; 17 private final ReferenceQueue queue = new ReferenceQueue (); 18 19 22 public SoftCache() { 23 map = new LRUMap(); 24 } 25 26 32 public SoftCache(int initialSize, int maxSize) { 33 map = new LRUMap(initialSize, maxSize); 34 } 35 36 42 public synchronized Object put(Object key, Object value) { 43 if (key == null || value == null) { 44 throw new IllegalArgumentException ("Key and value must not be null"); 45 } 46 ProcessQueue(); 47 Object obj = map.put(key, new SoftMapEntry(key, value, queue)); 48 return obj; 49 } 50 51 56 public synchronized Object get(Object key) { 57 ProcessQueue(); 58 Object obj = null; 59 SoftMapEntry entry = (SoftMapEntry)map.get(key); 60 if (entry != null) { 61 obj = entry.get(); 62 if (obj == null) { 63 map.remove(key); 67 } 68 } 69 return obj; 70 } 71 72 78 public synchronized Object remove(Object key) { 79 return map.remove(key); 80 } 81 82 85 public synchronized void clear() { 86 ProcessQueue(); 87 map.clear(); 88 } 89 90 93 private void ProcessQueue() { 94 while (true) { 95 SoftMapEntry entry = (SoftMapEntry)queue.poll(); 96 if (entry == null) { 97 break; 98 } 99 map.remove(entry.getKey()); 100 } 101 } 102 103 106 private static class SoftMapEntry extends SoftReference { 107 private final Object key; 108 109 private SoftMapEntry(Object key, Object value, ReferenceQueue queue) { 110 super(value, queue); 111 this.key = key; 112 } 113 114 private Object getKey() { 115 return key; 116 } 117 } 118 } | Popular Tags |