您可以使用 JDK 默认包含的 HotSpot Serviceability Agent 轻松制作这样的实用程序。
import sun.jvm.hotspot.memory.SystemDictionary;
import sun.jvm.hotspot.oops.InstanceKlass;
import sun.jvm.hotspot.oops.OopField;
import sun.jvm.hotspot.runtime.VM;
import sun.jvm.hotspot.tools.Tool;
public class InternedStrings extends Tool {
@Override
public void run() {
// Use Reflection-like API to reference String class and String.value field
SystemDictionary dict = VM.getVM().getSystemDictionary();
InstanceKlass stringKlass = (InstanceKlass) dict.find("java/lang/String", null, null);
OopField valueField = (OopField) stringKlass.findField("value", "[C");
// Counters
long[] stats = new long[2];
// Iterate through the String Pool printing out each String object
VM.getVM().getStringTable().stringsDo(s -> {
s.printValueOn(System.out);
System.out.println();
stats[0]++;
stats[1] += s.getObjectSize() + valueField.getValue(s).getObjectSize();
});
System.out.printf("%d strings with total size %d\n", stats[0], stats[1]);
}
public static void main(String[] args) {
// Use default SA tool launcher
new InternedStrings().execute(args);
}
}
运行工具:
java -cp $JAVA_HOME/lib/sa-jdi.jar:. InternedStrings <PID>
警告:这是一个在执行期间暂停目标 JVM 进程的外部工具。
更多Serviceability Agent示例here。
更新
如果您希望扫描所有字符串,而不仅仅是字符串池中的字符串,您可以使用类似的方法;只需将getStringTable().stringsDo() 替换为getObjectHeap().iterateObjectsOfKlass()。 Example.
更新 2
还可以使用 JVMTI 函数 IterateThroughHeap 在 Java 进程中迭代 Java 堆。这将比 Serviceability Agent 更少干扰。
jint JNICALL stringCallback(jlong class_tag, jlong size, jlong* tag_ptr,
const jchar* value, jint value_length, void* user_data) {
wprintf(L"%.*s\n", value_length, value);
return 0;
}
JNIEXPORT void JNICALL Java_HeapIterator_printStrings(JNIEnv* env, jclass cls) {
jvmtiHeapCallbacks callbacks = {NULL, NULL, NULL, NULL, stringCallback};
(*jvmti)->IterateThroughHeap(jvmti, 0, NULL, &callbacks, NULL);
}
完整的例子是here。