以编程方式分析java堆转储文件

时间:2012-06-20 20:13:51

标签: java heap-dump

我想编写一个程序(最好用java)来解析和分析java堆转储文件(由jmap创建)。我知道有很多很棒的工具已经这样做了(jhat,eclipse的MAT,等等),但是我想从特定的角度分析堆到我的应用程序。

我在哪里可以阅读堆转储文件的结构,如何阅读它的示例等等?找不到任何有用的搜索...

非常感谢。

2 个答案:

答案 0 :(得分:3)

以下是使用Eclipse版本完成的:Luna Service Release 1(4.4.1)和Eclipse Memory Analyzer V1.4.0

以编程方式与Java堆转储接口

环境设置

  1. 在eclipse中,帮助 - >安装新软件 - >安装Eclipse插件开发环境
  2. 在eclipse中,Window - >偏好 - >插件开发 - >目标平台 - >添加
  3. 没什么 - >地点 - >添加 - >安装
  4. 名称= MAT
  5. 位置= / path / to / MAT / installation / mat
  6. 项目设置

    1. 档案 - >新的 - >其他 - >插件项目

      名称:MAT Extension

    2. 下一步

      • 禁用激活器
      • 禁用对UI的贡献
      • 禁用API分析
    3. 接着
      • 停用模板
    4. 完成
    5. 代码生成

      打开plugin.xml

      1. 依赖关系 - >加
        • 选择org.eclipse.mat.api
      2. 扩展程序 - >加
        • 选择org.eclipse.mat.report.query
      3. 右键单击report.query - >新
        • 姓名:MyQuery
        • 点击“impl”生成课程
      4. 实施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文件顶部的工具栏的“Open Query Browser”,可以在MAT GUI中访问自定义查询。

        ISnapshot接口

        可以用来从堆转储中提取数据的最重要的接口是ISnapshot。 ISnapshot表示堆转储,并提供各种方法从中读取对象和类,获取对象的大小等...

        要获取ISnapshot的实例,可以在SnapshotFactory类上使用静态方法。但是,仅在使用API​​实现独立于Memory Analyzer的工具时才需要这样做。如果您正在编写MAT的扩展,那么您的编码将通过注入或作为方法参数获得与已打开的堆转储相对应的实例。

        Reference

        内置命令行实用程序

        如果您希望程序生成常规报告,则可以使用名为ParseHeapDump的命令行实用程序与任何download of Eclipse's MAT tool一起使用。您将能够获得MAT商店所有信息的有用html转储。

        > ParseHeapDump <heap dump> 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
        

        希望这是足以帮助您入门的信息。

答案 1 :(得分:0)

我不熟悉jhat,但Eclipse的MAT是开源的。他们的SVN link可用,或许你可以通过它来查看它们的解析器,甚至可以使用它。

相关问题