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?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
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.
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.