WeakHashMap使用WeakReference做WeakHashMap的Value。当key的引用被置为null的时候,map的内容会被很快gc。
package comz;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
class ObjectPoolClient {
private static WeakObjectPool objectPool = new WeakObjectPool();
public static void main(String args[]) throws Exception {
BufferedReader reader = new BufferedReader(new FileReader("d:/a.txt"));
List<String[]> parsedLines = new ArrayList<String[]>();
String line;
while ((line = reader.readLine()) != null) {
String[] elements = line.split(",");
for (int i = 0; i < elements.length; i++) {
// replace the string read from the file with the pool instance
elements[i] = (String) objectPool.replace(elements[i]);
}
parsedLines.add(elements);
}
reader.close();
// Cool, we saved a lot of memory by reusing the repeated strings!
doSomethingInteresting(parsedLines);
// Now, we get rid of the references and soon the garbage collector
// will reclaim the memory
parsedLines = null;
doMoreInterestingStuff();
}
}
下面是pool的实现:
package comz;
import java.lang.ref.WeakReference;
import java.util.Map;
import java.util.WeakHashMap;
/**
* Oversimplistic implementation of an object pool
*/
public class WeakObjectPool {
// Map where the key is an object, and the value is a weak reference
// to the same object. We use the key to do the lookup, and the value
// to actually return the object when it is found.
private Map map = new WeakHashMap();
public Object replace(Object object) {
WeakReference reference = (WeakReference) map.get(object);
if (reference != null) {
System.out.println("direct return");
Object result = reference.get();
// Another null check, since the GC may have kicked in between the
// two lines above.
if (result != null) {
return result;
}
}
// If we got here it is because the map doesn't have the key, add it.
System.out.println("add new one");
map.put(object, new WeakReference(object));
return object;
}
}
It means that once you lose the last strong reference to an object that is working as a key in a WeakHashMap, the garbage collector will soon reclaim that map entry.
最重要的还是要知道自己i这做什么。使用WeakHashMap,当key被回收或者置为null,那么value也会很快被回收。
-------------------------------
所以,个人感觉,用WeakHashMap做缓存有点不靠谱。慎用!