找生产问题时候碰到一个的WeakReference的问题:
测试代码
public static void testWeakReference() throws Exception { String s = "1"; ReferenceQueue q = new ReferenceQueue(); WeakReference w = new WeakReference(s, q); System.out.println("w.get():" + w.get()); s = null; System.gc(); System.out.println("s:" + s); System.out.println("w.get():" + w.get()); System.out.println("w.isEnqueued():" + w.isEnqueued()); }结果:
w.get():1
s:null
w.get():1 ---没有被gc后收集
w.isEnqueued():false
测试代码
结果:
w.get():1
s:null
w.get():null ---被gc后收集
w.isEnqueued():true
为什么 String s = new String("1");和String s= "1"; 会造成不同的结果?
原因:虽然两个语句都是返回一个String对象的引用,但是jvm对两者的处理方式是不一样的。对于第一种,jvm会马上在heap中创建一个String对 象,然后将该对象的引用返回给用户。对于第二种,jvm首先会在内部维护的strings pool中通过String的 equels 方法查找是对象池中是否存放有该String对象,如果有,则返回已有的String对象给用户,而不会在heap中重新创建一个新的String对象; 如果对象池中没有该String对象,jvm则在heap中创建新的String对象,将其引用返回给用户,同时将该引用添加至strings pool中。注意:使用第一种方法创建对象时,jvm是不会主动把该对象放到strings pool里面的,除非程序调用 String的intern方法。
此外,intern方法指定显式放到stringspool中:
String str1 = new String("abc"); //jvm 在堆上创建一个String对象
str1 = str1.intern();
//程序显式将str1放到strings pool中,intern运行过程是这样的:首先查看strings pool
//有没“abc”对象的引用,没有,则在堆中新建一个对象,然后将新对象的引用加入至
//strings pool中。执行完该语句后,str1原来指向的String对象已经成为垃圾对象了,随时会
//被GC收集。
参考:http://blog.csdn.net/kenwug/article/details/1606873