HashMap cacheMap = new HashMap();
HashMap mpp = new HashMap();
SoftReference soft = new SoftReference(mpp);
cacheMap.put("a", soft);
mapp = 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()));
}
控制台打印的是
{1=java.lang.Object@35ce36}
>>>>>>>>>>>>>>>>>>>>>>>>>>
{1=java.lang.Object@35ce36}请问下各位 为什么catch里面打出来的不是null
跟try里面取出来那个是一样的
你又没有将try里面取出来的那个删除了
{1=java.lang.Object@9931f5}
>>>>>>>>>>>>>>>>>>>>>>>>>>
java.lang.OutOfMemoryError: Java heap space
null
{1=java.lang.Object@35ce36}
>>>>>>>>>>>>>>>>>>>>>>>>>>
{1=java.lang.Object@35ce36}
我发现用1.6是会返回null,1.5会返回对象,但是我觉得1.6的测试有错。
如果你的代码改成 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());
map = null;//清空map引用 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) {
System.out.println(oom);
SoftReference sr2 = (SoftReference)cacheMap.get("a");
System.out.println(":" + (sr2.get()));
} }
则1.6与1.5都返回null
嘿嘿 不好意思 我方法外面有个 static HashMap mapp = new HashMap();贴的时候没贴上来 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());
map = null;//清空map引用 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) {
System.out.println(oom);
SoftReference sr2 = (SoftReference)cacheMap.get("a");
System.out.println(":" + (sr2.get()));
} }
谢谢你提醒 我也发现这个问题了 map 这个直接引用没有去掉 所以gc不会清除这个软引用的