JVM如何在字符串常量池查找字符串?字面量未存在时的查找机制疑问
Great question—this is one of those under-the-hood JVM details that feels counterintuitive at first glance, but it all clicks once you break down the process. Let’s walk through it step by step:
The key misunderstanding: You’re not looking for the object—you’re looking for its content
The String Constant Pool (backed byConcurrentHashMap) doesn’t store actual string objects as keys. Instead, it uses the character sequence (or a hashed representation of it) as the key, mapped to the reference of the String object. When the JVM processes your literalString literal = "Hello Java!", it doesn’t need the object to exist first—it just needs the content of the literal to perform the lookup.The full flow from compile time to runtime
Let’s break down what happens when your code is executed:- Compile time: The literal
"Hello Java!"is added to your.classfile’s Constant Pool as aCONSTANT_String_infoentry. This entry doesn’t hold the String object—it stores raw character data (or a reference to it) plus metadata like its precomputed hash value. - Class loading: When your class is loaded into the JVM, the
CONSTANT_String_infoentries are moved to the Runtime Constant Pool. At this point, the String object still doesn’t exist in memory. - Literal resolution: When the JVM encounters the line
String literal = "Hello Java!", it triggers theintern()logic for the literal:- First, it uses the precomputed hash of the literal’s character sequence to check the
ConcurrentHashMap(the String Constant Pool) for an existing entry. - If no entry exists: The JVM creates a new
Stringobject, then adds an entry to the map where the key is the literal’s content/hash, and the value is the reference to this new object. - Finally, it returns the reference (either the existing one or the new one) to assign to
literal.
- First, it uses the precomputed hash of the literal’s character sequence to check the
- Compile time: The literal
A real-world analogy to make it stick
Think of the String Constant Pool like a library’s catalog:- When you ask for "Hello Java!", you’re giving the librarian the title (the character sequence), not the book itself.
- The librarian checks the catalog (the
ConcurrentHashMap) for that title. - If the book exists in the catalog, they point you to its location (the object reference).
- If not, they order a new copy (create the String object), add it to the shelves, update the catalog with the title and location, then point you to it.
Bonus: Why
ConcurrentHashMapis the right choice
The switch from a fixed-size array (in early JVM versions) toConcurrentHashMapwas all about efficiency. The map allows for O(1) average lookup time using the content’s hash, and it handles concurrent access safely—critical since multiple threads might be resolving string literals at the same time.
内容的提问来源于stack exchange,提问作者Rahul Mathur

