Weak reference to String Pool object

As I read below sample wikipedia code http://en.wikipedia.org/wiki/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()); } } 

Exit before gc: r = I'm here, static = I'm here after gc: r = null, static = I'm here

I can not understand the result after gc, where there is a strong reference to the line indicated by sr (WeakReference), to the line in the string pool

+4
source share
3 answers

sr does not collect garbage because String internally caches strings. Therefore, internal caches still have a link, and therefore WeakRefence does not collect garbage.

A statically constructed line, as in the case of sr, is added to the cache. String objects created using the new Stirng ("...") are not. Therefore, it is usually best not to use a new String ("...").

0
source

Here, in the first case, when you create a string object using new String("I'm here") , so the object is always created on heap.So then, if you call System.gc(); Then this object can be directly accessible for garbage collection.

While in the second case, you pass the string as an object reference. A new String object will not be created here, since the string is directly initialized with a reference to the object. So it will not be available for garbage collection. Since this string will remain in the string-pool .

0
source

Objects in String pools will not be garbage collected since they are not on the heap. If you want to place new String() in the pool, you can use String#intern()

0
source

Source: https://habr.com/ru/post/1489869/


All Articles