Skip to content

Commit 25a2084

Browse files
committed
Add mallocTrim command to vmTool
1 parent d9811a0 commit 25a2084

File tree

4 files changed

+33
-2
lines changed

4 files changed

+33
-2
lines changed

arthas-vmtool/src/main/java/arthas/VmTool.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,4 +116,10 @@ public Class<?>[] getAllLoadedClasses() {
116116
return getAllLoadedClasses0(Class.class);
117117
}
118118

119+
@Override
120+
public boolean mallocTrim() {
121+
return mallocTrim0();
122+
}
123+
124+
private static synchronized native boolean mallocTrim0();
119125
}

arthas-vmtool/src/main/java/arthas/VmToolMXBean.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,4 +57,9 @@ public interface VmToolMXBean {
5757
* 获取所有已加载的类
5858
*/
5959
public Class<?>[] getAllLoadedClasses();
60+
61+
/**
62+
* glibc 释放空闲内存
63+
*/
64+
public boolean mallocTrim();
6065
}

arthas-vmtool/src/main/native/src/jni-library.cpp

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@
44
#include <jvmti.h>
55
#include "arthas_VmTool.h" // under target/native/javah/
66

7+
#ifdef __GLIBC__
8+
#include <malloc.h>
9+
#endif
710

811
static jvmtiEnv *jvmti;
912
static jlong tagCounter = 0;
@@ -204,4 +207,16 @@ JNIEXPORT jobjectArray JNICALL Java_arthas_VmTool_getAllLoadedClasses0
204207
}
205208
jvmti->Deallocate(reinterpret_cast<unsigned char *>(classes));
206209
return array;
207-
}
210+
}
211+
212+
213+
extern "C"
214+
JNIEXPORT jboolean JNICALL Java_arthas_VmTool_mallocTrim
215+
(JNIEnv *env, jclass thisClass) {
216+
#ifdef __GLIBC__
217+
if (!::malloc_trim(0)) {
218+
return JNI_FALSE;
219+
}
220+
#endif
221+
return JNI_TRUE;
222+
}

core/src/main/java/com/taobao/arthas/core/command/monitor200/VmToolCommand.java

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ public void setThreadId(int threadId) {
157157
}
158158

159159
public enum VmToolAction {
160-
getInstances, forceGc, interruptThread
160+
getInstances, forceGc, interruptThread, mallocTrim
161161
}
162162

163163
@Override
@@ -238,6 +238,11 @@ public void process(final CommandProcess process) {
238238
process.write("\n");
239239
process.end();
240240

241+
return;
242+
} else if (VmToolAction.mallocTrim.equals(action)) {
243+
boolean result = vmToolInstance().mallocTrim();
244+
process.write("\n");
245+
process.end(result ? 0 : -1, "mallocTrim result: " + result);
241246
return;
242247
}
243248

0 commit comments

Comments
 (0)