如何查看JVM字符串常量池中的字符串数量及内容?
Great question! Let’s break this down into two clear parts: viewing the actual strings stored in the JVM’s string constant pool, and checking how many strings are in there.
Unfortunately, there’s no official, straightforward way to directly list every string in the string constant pool. This is because the pool is an internal JVM implementation detail—different vendors (like Oracle HotSpot, OpenJ9) handle it differently, and it’s not exposed via standard Java APIs for regular application use.
That said, you can use indirect tools to get visibility:
- Heap Dumps + Analysis Tools: Starting with JDK 7, the string constant pool lives in the Java heap (it was in the PermGen space before that). You can take a heap dump using the
jmapcommand:
Load this dump into tools like VisualVM, Eclipse MAT, or JProfiler. These tools let you search for alljmap -dump:format=b,file=heapdump.hprof <your-jvm-pid>Stringinstances, and you can dig into references to identify which ones are linked to the constant pool (though this takes some manual work, since the pool stores references to heap-based String objects). - Java Agents with Instrumentation: You could write a custom Java agent using the Instrumentation API to track String creation, but this only monitors new strings being added to the pool—it won’t show you existing ones already in the pool. This requires writing custom code and attaching the agent to the JVM at startup.
Yes, there are reliable ways to get this count, depending on your JVM:
- HotSpot JVM-specific Flag: If you’re using Oracle’s HotSpot or OpenJDK, run your application with the
-XX:+PrintStringTableStatisticsflag. When the JVM exits, it will print detailed stats about the string constant pool (called the "StringTable" internally), including the number of literals stored. Here’s an example of the output:
TheStringTable statistics: Number of buckets : 65536 = 524288 bytes, each 8 bytes Number of entries : 14523 = 232368 bytes, each 16 bytes Number of literals : 14523 = 1161840 bytes, avg 80.0 bytes Total footprint : = 1916496 bytes Average bucket size : 0.222 Variance of bucket size : 0.222 Std. dev. of bucket size: 0.471 Maximum bucket size : 4Number of literalsline gives you the exact count of strings in the string constant pool. - JMX & Monitoring Tools: Tools like VisualVM or JConsole can connect to a running JVM and show you metrics about
Stringinstances. While they don’t explicitly label constant pool strings, you can get the total number ofStringobjects in the heap, and combine this with other context to infer pool-related counts. For more precise data, some JMX MBeans expose string-related stats, though this varies by JVM.
It’s worth noting that the string constant pool’s behavior changed in JDK 7: before that, it was part of the PermGen space, but now it resides in the main heap. This affects how tools access and report on its contents.
内容的提问来源于stack exchange,提问作者CrazySynthax

