本文介绍了什么时候将一个字符串垃圾收集在java中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,当一个对象没有实时引用时,它有资格进行垃圾收集。现在在字符串的情况下,情况并非如此,因为字符串将进入字符串池,并且JVM将保持该对象的活动状态以用于重用。
所以这意味着一旦创建的字符串将永远不会被垃圾收集?

解决方案

首先,它只是 字符串文字,它们会自动实现/添加到字符串池中。由应用程序创建的字符串不会被拦截......除非您的应用程序明确调用 String.intern()





实际上,对应于字符串的字符串对象通常不适用于垃圾采集。这是因为在每个使用文字的方法的代码中都存在对字符串对象的隐式引用。这意味着只要该方法可以被执行,该字符串都是可访问的。



然而,这并不总是 。如果文字是在动态加载的类中定义的(例如,使用 Class.forName(...)),那么可以安排该类是卸载。如果发生这种情况,那么字面值的String对象将无法访问,并且当包含被拦截字符串的堆获取GC时将被回收。

In Java, when an object has got no live reference, it is eligible for garbage collection. 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?

解决方案

First, it is only String literals that get automatically interned / added to the String pool. Strings that are created by an application are not interned ... unless your application explicitly calls String.intern().

Second, in fact the rules for garbage collecting objects in the String pool are the same as for other Strings / other objects. The strings will be garbage collected if they ever become unreachable.

In fact the String objects that correspond to String literals typically are not candidates for garbage collection. This is because there is an implicit reference to the string object in the code of every method that uses the literal. This means that the String is reachable for as long as the method could be executed.

However, this is not always the case. If the literal was defined in a class that was dynamically loaded (e.g. using Class.forName(...)), then it is possible to arrange that the class is unloaded. If that happens, then the String object for the literal will be unreachable, and will be reclaimed when the heap containing the interned String gets GC'ed.

这篇关于什么时候将一个字符串垃圾收集在java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 19:44