我构建了一个基本的 java 代理,允许调用 jvmtiForceGarbageCollection
函数:
#include <stdlib.h>
#include <stdio.h>
#include <jvmti.h>
typedef struct {
jvmtiEnv *jvmti;
} GlobalAgentData;
static GlobalAgentData *gdata;
JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM *jvm, char *options, void *reserved)
{
printf("load garbager agent\n");
jvmtiEnv *jvmti = NULL;
// put a jvmtiEnv instance at jvmti.
jint result = jvm->GetEnv((void **) &jvmti, JVMTI_VERSION_1_1);
if (result != JNI_OK) {
printf("ERROR: Unable to access JVMTI!\n");
}
// store jvmti in a global data
gdata = (GlobalAgentData*) malloc(sizeof(GlobalAgentData));
gdata->jvmti = jvmti;
return JNI_OK;
}
extern "C"
JNIEXPORT void JNICALL Java_Garbager_forceGarbageCollection(JNIEnv *env, jclass thisClass)
{
printf("force garbage collection\n");
gdata->jvmti->ForceGarbageCollection();
}
该代理通过JNI调用:
class Garbager {
public static void main(String[] args) {
Garbager.garbageMemory();
}
static void garbageMemory() {
forceGarbageCollection();
}
private static native void forceGarbageCollection();
}
在 MacOSX 上编译代理:
clang -shared -undefined dynamic_lookup -o garbager-agent.so -I /Library/Java/JavaVirtualMachines/jdk1.8.0_40.jdk/Contents/Home/include/ -I /Library/Java/JavaVirtualMachines/jdk1.8.0_40.jdk/Contents/Home/include/darwin garbager-agent.cpp
要启动Garbager
:
java -agentpath:garbager-agent.so Garbager
基于本教程:拥有你的堆:使用 JVMTI 迭代类实例