以编程方式分析java堆转储文件
我想编写一个程序(最好用java)来解析和分析java堆转储文件(由jmap创建)。 我知道有很多很棒的工具已经这样做了(jhat,eclipse的MAT等等),但是我想从特定的角度分析堆到我的应用程序。
我在哪里可以阅读有关堆转储文件的结构,如何阅读它的示例等等? 没有找到任何有用的搜索它…
非常感谢。
我不熟悉jhat,但Eclipse的MAT是开源的。 他们的SVN链接可用,也许您可以查看它们的解析器,甚至可以使用它。
以下是使用Eclipse Version:Luna Service Release 1(4.4.1)和Eclipse Memory Analyzer V1.4.0完成的
以编程方式与Java堆转储连接
环境设置
- 在eclipse中,帮助 – >安装新软件 – >安装Eclipse插件开发环境
- 在eclipse中,Window – > Preferences – > Plug-in Development – > Target Platform – > Add
- 没什么 – >地点 – >添加 – >安装
- 名称= MAT
- 位置= / path / to / MAT / installation / mat
项目设置
-
文件 – >新建 – >其他 – >插件项目
名称:MAT扩展
-
下一个
- 禁用激活器
- 禁用对UI的贡献
- 禁用API分析
- 下一个
- 禁用模板
- 完
代码生成
打开plugin.xml
- 依赖关系 – >添加
- 选择org.eclipse.mat.api
- 扩展程序 – >添加
- 选择org.eclipse.mat.report.query
- 右键单击report.query – > New
- 名称:MyQuery
- 单击“impl”以生成类
实现IQuery
@CommandName("MyQuery") //for the command line interface @Name("My Query") //display name for the GUI @Category("Custom Queries") //list this Query will be put under in the GUI @Help("This is my first query.") //help displayed public class MyQuery implements IQuery { public MyQuery{} @Argument //snapshot will be populated before the call to execute happens public ISnapshot snapshot; /* * execute : only method overridden from IQuery * Prints out "My first query." to the output file. */ @Override public IResult execute(IProgressListener arg0) throws Exception { CharArrayWriter outWriter = new CharArrayWriter(100); PrintWriter out = new PrintWriter(outWriter); SnapshotInfo snapshotInfo = snapshot.getSnapshotInfo(); out.println("Used Heap Size: " + snapshotInfo.getUsedHeapSize()); out.println("My first query.") return new TextResult(outWriter.toString(), false); } }
ctrl + shift + o将生成正确的“import”语句。 通过访问已打开的hprof文件顶部的工具栏的“打开查询浏览器”,可以在MAT GUI中访问自定义查询。
ISnapshot接口
可以用来从堆转储中提取数据的最重要的接口是ISnapshot。 ISnapshot表示堆转储,并提供各种方法从中读取对象和类,获取对象的大小等…
要获取ISnapshot的实例,可以在SnapshotFactory类上使用静态方法。 但是,只有在API用于实现独立于Memory Analyzer的工具时才需要这样做。 如果您正在编写MAT的扩展,那么您的编码将通过注入或作为方法参数获得与已打开的堆转储相对应的实例。
参考
内置命令行实用程序
如果您希望程序生成常规报告,可以使用任何下载Eclipse的MAT工具的命令行实用程序ParseHeapDump。 您将能够获得MAT商店所有信息的有用html转储。
> ParseHeapDump org.eclipse.mat.api:suspects org.eclipse.mat.api:top_components org.eclipse.mat.api:overview #will dump out all general reports available through MAT
希望这足以让您入门。