WeakReference to String and String constants

和自甴很熟 提交于 2019-12-09 03:13:47

问题


I have come across this example from wikipedia regarding weak reference:

import java.lang.ref.WeakReference;

public class ReferenceTest {
        public static void main(String[] args) throws InterruptedException {

            WeakReference r = new WeakReference(new String("I'm here"));
            WeakReference sr = new WeakReference("I'm here");
            System.out.println("before gc: r=" + r.get() + ", static=" + sr.get());
            System.gc();
            Thread.sleep(100);

            // only r.get() becomes null
            System.out.println("after gc: r=" + r.get() + ", static=" + sr.get());

        }
}

I don't understand in this scenario why only r.get() returns null but not the sr.get(). Can someone let me know the reason?

Many thanks.


回答1:


the literal "I'm here" is a compile time constant string and as such gets placed in the constant string pool, which (up until java 7) was never garbage collected. that means sr points to an object that will never be garbage collected. r, on the other hand, points to a copy of that string, which is not in any const pool and so is eligible for collection.

see the documentation for String.intern() for some more details on this string pool




回答2:


If this reference object has been cleared, either by the program or by the garbage collector, then this method returns null.

very well explained here



来源:https://stackoverflow.com/questions/20121173/weakreference-to-string-and-string-constants

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!