Now in case of a string, this is not the case because string will go into the string pool and JVM will keep the object alive for resuse. So that means a string once created will ‘never’ be garbage collected?
首先,它是字符串字面量获取自动interned /添加到字符串池。由应用程序创建的字符串不会被嵌入…除非应用程序显式调用String.intern()。
第二,事实上,在String池中垃圾收集对象的规则与其他Strings /其他对象相同。如果字符串变得不可达,它们将被垃圾回收。
实际上,对应于String字符串的String对象通常不是垃圾回收的候选对象。这是因为在使用字面量的每个方法的代码中都存在对字符串对象的隐式引用。这意味着只要方法可以被执行,String是可达的。
然而,这并不总是这样。如果字面量在动态加载的类中定义(例如使用Class.forName(…)),那么可以安排类被卸载。如果发生这种情况,那么该字符串的String对象将无法访问,并且当包含interned String的堆获得GC’ed时将被回收。