以编程方式计算Java对象占用的内存,包括它引用的对象 [英] Programmatically calculate memory occupied by a Java Object including objects it references

查看:139
本文介绍了以编程方式计算Java对象占用的内存,包括它引用的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以编程方式确切地找出给定Java对象占用的内存量,包括它引用的对象所占用的内存。

I need to programmatically find out exactly how much memory a given Java Object is occupying including the memory occupied by the objects that it is referencing.

我可以生成一个内存堆转储并使用工具分析结果。但是,生成堆转储需要花费大量时间,并且需要这样的工具来读取转储以生成报告。鉴于我可能需要多次执行此操作,如果我可以在项目中输入一些代码来运行,那么我的工作会更灵活。

I can generate a memory heap dump and analyse the results using a tool. However it takes a considerable amount of time to generate a heap dump and for such a tool to read the dump to generate reports. Given the fact that I will probably need to do this several times, my work would be a lot more agile if I could throw in some code in my project that would give me this value "runtime".

我怎样才能最好地实现这个目标?

How could I best achieve this?

ps:具体来说,我有一组javax.xml.transform.Templates类型的对象

ps: Specifically I have a collection of objects of type javax.xml.transform.Templates

推荐答案

您需要使用反射。由此产生的代码片段对于我来说太复杂了(尽管它很快将作为我正在构建的GPL工具包的一部分提供),但主要的想法是:

You will need to use reflection for that. The resulting piece of code is too complicated for me to post here (although it will soon be available as part of a GPL toolkit I am building), but the main idea is:


  • 对象头使用8个字节(对于类指针和引用计数)

  • 每个原始字段使用1,2,4或8个字节,具体取决于实际type

  • 每个对象引用(即非原始)字段使用4个字节(引用,加上引用的对象使用的任何内容)

您需要单独处理数组(8个字节的标头,4个字节的长度字段,4个*长度的表字节,以及内部使用的任何对象)。您需要使用反射处理迭代字段(以及它的父字段)的其他类型的对象。

You need to treat arrays separately (8 bytes of header, 4 bytes of length field, 4*length bytes of table, plus whatever the objects inside are using). You need to process other types of objects iterating through the fields (and it's parents fields) using reflection.

您还需要保留一组看到的对象。递归,以便不计算多次在多个地方引用的对象。

You also need to keep a set of "seen" objects during the recursion, so as not to count multiple times objects referenced in several places.

这篇关于以编程方式计算Java对象占用的内存,包括它引用的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆