问题
When string is created by using literal, it gets stored in pool. But when new operator is used to create String object, it stores the object in Heap.
But is the object in heap just a pointer to literal stored in pool or is it a simple String object stored in heap which is eligible for GC?
回答1:
Terminology:
The constant pool is an area in (each) .class file that contains various constants, including strings. No runtime objects exist in the constant pool. It is a region of a file.
The string pool is a runtime data structure used by the JVM to manage certain kinds of strings. (Specifically,
String
objects that correspond to literals, andString
objects added to the pool byString::intern()
.)
Your question is actually talking about the string pool, not the constant pool.
To answer your questions:
String pool - do String always exist in constant pool?
No. A string object created using new String()
doesn't exist in either the string pool or the constant pool.
When string is created by using literal, it gets stored in pool.
It (already!) exists the constant pool and gets created in the string pool. (The actual creation can be at class load time, or when the literal is first used. This depends on the Java implementation.)
But when new operator is used to create String object, it stores the object in Heap.
Yes. But the string pool is also part of the Heap. Like I said, it is a data structure, not a region of storage.
(In the old days, the string pool lived in a special heap called the PermGen heap. But PermGen was replaced with something else (MetaSpace), and the string pool doesn't use either ... anymore.
But is the object in heap just a pointer to literal stored in pool or is it a simple String object stored in heap which is eligible for GC?
This is really confused.
All strings are represented as String
objects in the (a) heap. Even strings in the string pool. Even when the string pool was in PermGen.
All String
objects that are unreachable are eligible for garbage collection. Even for strings in the string pool. Even for String
objects that represent string literals.
But ... wait ... so can string literals be garbage collected?
Yes!! If a String
object that represents a string literal becomes unreachable at runtime it is eligible for garbage collection, just like any other String
object.
A string literal can become unreachable if the code object(s) that use the literal become unreachable. It can happen, when a classloader becomes unreachable.
And yes, PermGen was garbage collected. At least since JDK 1.2. (IIRC Java 1.0 and maybe 1.1 didn't implement GC for the PermGen heap. But that was fixed a long time ago.)
来源:https://stackoverflow.com/questions/57414169/string-pool-do-string-always-exist-in-constant-pool