步骤 1:编写 Java 程序
首先,编写一个 Java 程序,当内存使用达到 11GB 时生成 heap dump 文件,并以日期命名。将以下代码保存为 MemoryMonitor.java
文件:
import com.sun.management.HotSpotDiagnosticMXBean;
import javax.management.MBeanServer;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MemoryMonitor {
private static final long HEAP_DUMP_THRESHOLD = 11L * 1024L * 1024L * 1024L; // 11 GB
private static final String DUMP_FILE_PATH = "/home/dumpfile/";
private static final MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
private static final HotSpotDiagnosticMXBean hotSpotDiagnosticMXBean;
static {
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
try {
hotSpotDiagnosticMXBean = ManagementFactory.newPlatformMXBeanProxy(
server,
"com.sun.management:type=HotSpotDiagnostic",
HotSpotDiagnosticMXBean.class);
} catch (Exception e) {
throw new RuntimeException("Failed to initialize HotSpotDiagnosticMXBean", e);
}
}
public static void main(String[] args) {
new Thread(MemoryMonitor::monitorMemory).start();
}
private static void monitorMemory() {
while (true) {
MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
long usedMemory = heapMemoryUsage.getUsed();
System.out.println("Used memory: " + usedMemory);
if (usedMemory >= HEAP_DUMP_THRESHOLD) {
try {
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String dumpFilePath = DUMP_FILE_PATH + "heapdump_" + timestamp + ".hprof";
hotSpotDiagnosticMXBean.dumpHeap(dumpFilePath, true);
System.out.println("Heap dump generated at " + dumpFilePath);
} catch (Exception e) {
e.printStackTrace();
}
break;
}
try {
Thread.sleep(10000); // Check every 10 seconds
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
}
}
步骤 2:编译 Java 程序
打开终端并运行以下命令来编译 Java 程序:
javac MemoryMonitor.java
步骤 3:创建启动脚本
创建一个启动脚本,以便在后台运行该程序并配置 JVM 参数。将以下内容保存为 start_memory_monitor.sh
文件:
#!/bin/bash
JAVA_OPTS="-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/home/dumpfile -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintGCTimeStamps -XX:+PrintGCApplicationStoppedTime -Xloggc:/home/dumpfile/gc.log -XX:OnOutOfMemoryError='kill -3 %p'"
nohup java $JAVA_OPTS -cp . MemoryMonitor > /home/dumpfile/memory_monitor.log 2>&1 &
echo "MemoryMonitor started in background."
步骤 4:赋予脚本执行权限
运行以下命令,赋予脚本执行权限:
chmod +x start_memory_monitor.sh
步骤 5:运行脚本
运行启动脚本,使 Java 程序在后台运行:
./start_memory_monitor.sh
总结
- 编写并保存
MemoryMonitor.java
文件。 - 在终端中运行
javac MemoryMonitor.java
编译 Java 程序。 - 创建并保存
start_memory_monitor.sh
启动脚本。 - 运行
chmod +x start_memory_monitor.sh
赋予启动脚本执行权限。 - 运行
./start_memory_monitor.sh
启动 Java 程序并使其在后台运行。