I use -XX:+PrintNMTStatistics
to get Memory Status.
but it can't be store in file
so how can i save those info to a file ?
I use -XX:+PrintNMTStatistics
to get Memory Status.
but it can't be store in file
so how can i save those info to a file ?
-XX:+PrintNMTStatistics
prints to JVM console, and this can't be changed.
However, it is possible to create your own utility that will dump NMT statistics to a file before JVM exits.
The idea is similar to this answer: create a JVMTI agent that intercepts VMDeath
event and then uses JVM Management Interface to call VM.native_memory
diagnostic command.
#include <jvmti.h>
#include <stdio.h>
#include <string.h>
static const char* filename;
extern void* JNICALL JVM_GetManagement(jint version);
static void* get_management_func() {
void** jmm;
if ((jmm = JVM_GetManagement(0x20010000)) != NULL) return jmm[39];
if ((jmm = JVM_GetManagement(0x20020000)) != NULL) return jmm[37];
if ((jmm = JVM_GetManagement(0x20030000)) != NULL) return jmm[38];
return NULL;
}
static void save_to_file(const char* result_str) {
FILE* f = fopen(filename, "w");
if (f != NULL) {
fprintf(f, "%s", result_str);
fclose(f);
} else {
fprintf(stderr, "%s", result_str);
}
}
void JNICALL VMDeath(jvmtiEnv* jvmti, JNIEnv* env) {
jstring (JNICALL *func)(JNIEnv*, jstring) = get_management_func();
if (func == NULL) {
fprintf(stderr, "JMM interface is not supported on this JVM\n");
return;
}
jstring cmd = (*env)->NewStringUTF(env, "VM.native_memory summary");
jstring result = func(env, cmd);
if (result != NULL) {
const char* result_str = (*env)->GetStringUTFChars(env, result, NULL);
save_to_file(result_str);
(*env)->ReleaseStringUTFChars(env, result, result_str);
}
}
JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM* vm, char* options, void* reserved) {
filename = options != NULL ? strdup(options) : "";
jvmtiEnv* jvmti;
(*vm)->GetEnv(vm, (void**)&jvmti, JVMTI_VERSION_1_0);
jvmtiEventCallbacks callbacks = {0};
callbacks.VMDeath = VMDeath;
(*jvmti)->SetEventCallbacks(jvmti, &callbacks, sizeof(callbacks));
(*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, JVMTI_EVENT_VM_DEATH, NULL);
return 0;
}
Save the above code to nmtdump.c
and compile it:
gcc -I $JAVA_HOME/include -I $JAVA_HOME/include/linux -shared -fPIC -olibnmtdump.so nmtdump.c
Then run Java with our agent:
java -XX:NativeMemoryTracking=summary -agentpath:/path/to/libnmtdump.so=dump.txt ...
Now, when JVM exits, it will save NMT report to dump.txt
.