String = "" 和 new String("")的区别

本文详细解析了Java中WeakReference的工作原理及其如何影响String对象的生命周期。通过对比不同初始化方式下String对象的处理流程,揭示了为何Strings=newString(1);和Strings=1;会造成不同的内存管理结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

找生产问题时候碰到一个的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

测试代码

public static void testWeakReference() throws Exception {
        String s = new String("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():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方法指定显式放到strings pool中

String str1 = new String("abc"); //jvm 在堆上创建一个String对象   
 
str1 = str1.intern();   
//程序显式将str1放到strings pool中,intern运行过程是这样的:首先查看strings pool   
//有没“abc”对象的引用,没有,则在堆中新建一个对象,然后将新对象的引用加入至   
//strings pool中。执行完该语句后,str1原来指向的String对象已经成为垃圾对象了,随时会   
//被GC收集。

参考:http://blog.youkuaiyun.com/kenwug/article/details/1606873

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值