在JVM发生FGC前后dump内存

本文介绍如何监控Java应用程序中的Full Garbage Collection (FGC)事件,并自动在FGC前后进行内存快照,以便分析被回收的对象。文章提供了手动及自动dump内存的方法,包括使用JVM参数和Java代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[size=medium]一.需求[/size]

[size=small]有时候web应用经常会发生FGC,我们想知道FGC把那些对象给回收了,思路很简单就是看看FGC之前内存中有那些实例,FGC之后内存中又有那些实例,通过前后的比较,我们就能很容易知道FGC回收了那些实例,当然我们可以手工去dump内存,在FGC发生之前dump一下内存,再在FGC发生之后dump一下内存,但是这dump的时间点不好把握,能否让JVM自动去dump就更好了。
[/size]
[size=medium]二.手工dump内存的方法[/size]

jmap -dump:format=b,file=/home/admin/xxx.bin PID
其中PID是java的进程ID

[size=medium]三.让JVM自己dump内存[/size]

在JVM启动的时候增加下面两个参数[color=red]-XX:+HeapDumpBeforeFullGC -XX:+HeapDumpAfterFullGC[/color]就可以在FGC的前后dump一下内存。不过增加这两个参数会在每次FGC的时候dump内存,dump内存本身对应用有影响,但是不会导致JVM停机。特别是在web应用启动的时候,就会不断的去dump内存,因为web应用启动的时候会频繁发生FGC。

[size=medium]四.使用Java代码来dump内存[/size]


import java.lang.management.ManagementFactory;

import javax.management.MBeanServer;

import com.sun.management.HotSpotDiagnosticMXBean;

public class HeapDumper {
// This is the name of the HotSpot Diagnostic MBean
private static final String HOTSPOT_BEAN_NAME =
"com.sun.management:type=HotSpotDiagnostic";

// field to store the hotspot diagnostic MBean
private static volatile HotSpotDiagnosticMXBean hotspotMBean;

/*
* Call this method from your application whenever you
* want to dump the heap snapshot into a file.
*
* @param fileName name of the heap dump file
* @param live flag that tells whether to dump
* only the live objects
*/
static void dumpHeap(String fileName, boolean live) {
// initialize hotspot diagnostic MBean
initHotspotMBean();
try {
hotspotMBean.dumpHeap(fileName, live);
} catch (RuntimeException re) {
throw re;
} catch (Exception exp) {
throw new RuntimeException(exp);
}
}

// initialize the hotspot diagnostic MBean field
private static void initHotspotMBean() {
if (hotspotMBean == null) {
synchronized (HeapDumper.class) {
if (hotspotMBean == null) {
hotspotMBean = getHotspotMBean();
}
}
}
}

// get the hotspot diagnostic MBean from the
// platform MBean server
private static HotSpotDiagnosticMXBean getHotspotMBean() {
try {
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
HotSpotDiagnosticMXBean bean =
ManagementFactory.newPlatformMXBeanProxy(server,
HOTSPOT_BEAN_NAME, HotSpotDiagnosticMXBean.class);
return bean;
} catch (RuntimeException re) {
throw re;
} catch (Exception exp) {
throw new RuntimeException(exp);
}
}

public static void main(String[] args) {
// default heap dump file name
String fileName = "heap.bin";
// by default dump only the live objects
boolean live = true;

// simple command line options
switch (args.length) {
case 2:
live = args[1].equals("true");
case 1:
fileName = args[0];
}

// dump the heap
dumpHeap(fileName, live);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值