When will a string be garbage collected in java

2019-01-03 02:40发布

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?

2条回答
The star\"
2楼-- · 2019-01-03 03:10

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 literals1 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 practice, the String objects that correspond to String literals typically do not become 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.


1 - It is incorrect to say that all string literals are interned. If a String literal only appears in the source code as a sub-expression of a (compile-time) constant expression (JLS 15.28), then the literal will not appear in the ".class" file in any form. Such a literal won't be interned because it won't exist at runtime.

查看更多
干净又极端
3楼-- · 2019-01-03 03:13

You are correct; strings in the intern pool will never be GC'd.

However, most strings on not interned.
String literals are interned, and strings passed to String.intern() are interned, but all other strings are not interned and can be GC'd normally.

查看更多
登录 后发表回答