计算物体的“重量",方法 [英] Calculating 'weight' of an object, howto

查看:104
本文介绍了计算物体的“重量",方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
在Java中,什么确定对象大小的最佳方法是什么?

Possible Duplicate:
In Java, what is the best way to determine the size of an object?

假设您有一个数据结构,可以向其中添加数据,例如列表:

Suppose you have a data structure which allows you to add data to it, say a list:

List<KeyValuePair>

由于系统的客户端实际上添加了内容...在某些时候,JVM将耗尽内存,这只是何时发生的问题.最好将包含此列表的对象定期保存到磁盘上,然后gc将其余的保存到磁盘上.

As client of the system actually adds content ... at some point, JVM will run out of memory, it is only a question of when this happens. It would be nice to periodically save the object that contains this list to disk and gc the rest.

使用Java,是否可以估计一个对象现在占用多少内存?

推荐答案

您正在寻找java.lang.instrument.Instrumentation.getObjectSize(Object object)

文档:

返回特定于实现的近似值 指定对象消耗的存储空间.结果可能包括一些 或对象的所有开销,因此对于进行比较很有用 在实施中,但不在实施之间.估计 一次调用JVM可能会改变.

Returns an implementation-specific approximation of the amount of storage consumed by the specified object. The result may include some or all of the object's overhead, and thus is useful for comparison within an implementation but not between implementations. The estimate may change during a single invocation of the JVM.

http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/instrument/Instrumentation.html#getObjectSize%28java.lang.Object%29

但是为了能够使用它:

访问Instrumentation接口实例的唯一方法是 以指示代理类的方式启动JVM- 请参阅包装规格. Instrumentation实例已传递 代理类的premain方法.代理商获得 工具实例,代理可以在实例上调用方法 在任何时候.

The only way to access an instance of the Instrumentation interface is for the JVM to be launched in a way that indicates the agent class - see the package specification. The Instrumentation instance is passed to the premain method of the agent class. Once an agent acquires the Instrumentation instance, the agent may call methods on the instance at any time.

良好的实现示例: http://www.javalobby.org/java/forums/t19309.html

这篇关于计算物体的“重量",方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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