[code="java"]
HashMap cacheMap = new HashMap();
HashMap mpp = new HashMap();
SoftReference soft = new SoftReference(mpp);
cacheMap.put("a", soft);
mpp = null;
soft = null;
HashMap map = (HashMap)((SoftReference)cacheMap.get("a")).get();
map.put("1", new Object());
try{
SoftReference sr = (SoftReference)cacheMap.get("a");
System.out.println(sr.get());
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>");
HashMap map1 = new HashMap();
for(int i = 0; i < Integer.MAX_VALUE; i++) {
map1.put("KEY" + i, "VALUE" + i);
}
}catch(OutOfMemoryError oom) {
SoftReference sr2 = (SoftReference)cacheMap.get("a");
System.out.println((sr2.get()));
}
[/code]
控制台打印的是
{1=java.lang.Object@35ce36}
{1=java.lang.Object@35ce36}
请问下各位 为什么catch里面打出来的不是null
[b]问题补充:[/b]
[quote]
但输出是
引用
{1=java.lang.Object@de6ced}
null
测试环境是32位Windows上的JRE 1.6.0u11,Client VM。
反而是要得到像楼主看到的那种输出,还得在for循环里想办法用一下map才行,例如用map.get("1")之类的来挂住它。
[/quote]
我在CSDN上面问 也是有个兄弟也是你的这个回答 奇怪了 难道gc的实现相差这么多吗?
我的jdk.1.5.0_06 hotspot的vm
系统跟你一样
sun文档上写的是 虚拟机实现不鼓励清除最近访问或使用过的软引用
难道是这个原因?
奇怪,刚才试了下这段代码,
[code="java"]import java.lang.ref.*;
import java.util.*;
public class TestSoftReference {
public static void main(String[] args) {
HashMap cacheMap = new HashMap();
HashMap mpp = new HashMap();
SoftReference soft = new SoftReference(mpp);
cacheMap.put("a", soft);
mpp = null;
soft = null;
HashMap map = (HashMap)((SoftReference)cacheMap.get("a")).get();
map.put("1", new Object());
try{
SoftReference sr = (SoftReference)cacheMap.get("a");
System.out.println(sr.get());
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>");
// make an OutOfMemoryError
HashMap map1 = new HashMap();
for(int i = 0; i < Integer.MAX_VALUE; i++) {
map1.put("KEY" + i, "VALUE" + i);
}
} catch(OutOfMemoryError oom) {
SoftReference sr2 = (SoftReference)cacheMap.get("a");
System.out.println((sr2.get()));
}
}
}[/code]
但输出是
[quote]{1=java.lang.Object@de6ced}
null[/quote]
测试环境是32位Windows上的JRE 1.6.0u11,Client VM。
反而是要得到像楼主看到的那种输出,还得在for循环里想办法用一下map才行,例如用map.get("1")之类的来挂住它。